@gjsify/video 0.3.12 → 0.3.14

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.
@@ -1,25 +1,24 @@
1
1
  import Gst from "gi://Gst?version=1.0";
2
2
  import { DOMException } from "@gjsify/dom-exception";
3
+
4
+ //#region src/gst-init.ts
3
5
  let initialized = false;
4
6
  function ensureGstInit() {
5
- if (initialized) return;
6
- Gst.init(null);
7
- initialized = true;
7
+ if (initialized) return;
8
+ Gst.init(null);
9
+ initialized = true;
8
10
  }
11
+ /** Throws if the gtk4paintablesink element is not registered. */
9
12
  function ensurePaintableSinkAvailable() {
10
- ensureGstInit();
11
- const factory = Gst.ElementFactory.find("gtk4paintablesink");
12
- if (!factory) {
13
- throwNotSupported(
14
- 'GStreamer element "gtk4paintablesink" not available. Install gst-plugins-rs:\n Fedora: dnf install gstreamer1-plugin-gtk4\n Ubuntu/Debian: apt install gstreamer1.0-gtk4\n Verify with: gst-inspect-1.0 gtk4paintablesink'
15
- );
16
- }
13
+ ensureGstInit();
14
+ const factory = Gst.ElementFactory.find("gtk4paintablesink");
15
+ if (!factory) {
16
+ throwNotSupported("GStreamer element \"gtk4paintablesink\" not available. Install gst-plugins-rs:\n" + " Fedora: dnf install gstreamer1-plugin-gtk4\n" + " Ubuntu/Debian: apt install gstreamer1.0-gtk4\n" + " Verify with: gst-inspect-1.0 gtk4paintablesink");
17
+ }
17
18
  }
18
19
  function throwNotSupported(message) {
19
- throw new DOMException(message, "NotSupportedError");
20
+ throw new DOMException(message, "NotSupportedError");
20
21
  }
21
- export {
22
- Gst,
23
- ensureGstInit,
24
- ensurePaintableSinkAvailable
25
- };
22
+
23
+ //#endregion
24
+ export { Gst, ensureGstInit, ensurePaintableSinkAvailable };
package/lib/esm/index.js CHANGED
@@ -1,10 +1,5 @@
1
- import { VideoBridge } from "./video-bridge.js";
2
1
  import { buildMediaStreamPipeline, buildUriPipeline, createPaintableSink } from "./pipeline-builder.js";
2
+ import { VideoBridge } from "./video-bridge.js";
3
3
  import { HTMLVideoElement } from "@gjsify/dom-elements";
4
- export {
5
- HTMLVideoElement,
6
- VideoBridge,
7
- buildMediaStreamPipeline,
8
- buildUriPipeline,
9
- createPaintableSink
10
- };
4
+
5
+ export { HTMLVideoElement, VideoBridge, buildMediaStreamPipeline, buildUriPipeline, createPaintableSink };
@@ -1,87 +1,115 @@
1
- import { ensureGstInit, ensurePaintableSinkAvailable, Gst } from "./gst-init.js";
1
+ import { Gst, ensureGstInit, ensurePaintableSinkAvailable } from "./gst-init.js";
2
+
3
+ //#region src/pipeline-builder.ts
4
+ /**
5
+ * Create a gtk4paintablesink and extract its Gdk.Paintable.
6
+ * Optionally wraps in glsinkbin for GL-accelerated rendering
7
+ * (following the showtime pattern).
8
+ */
2
9
  function createPaintableSink() {
3
- ensurePaintableSinkAvailable();
4
- const paintableSink = Gst.ElementFactory.make("gtk4paintablesink", "videosink");
5
- if (!paintableSink) {
6
- throw new Error("Failed to create gtk4paintablesink element");
7
- }
8
- const paintable = paintableSink.paintable;
9
- if (!paintable) {
10
- throw new Error("gtk4paintablesink has no paintable property");
11
- }
12
- let glSink = null;
13
- const glContext = paintable.gl_context;
14
- if (glContext) {
15
- glSink = Gst.ElementFactory.make("glsinkbin", "glsink");
16
- if (glSink) {
17
- glSink.sink = paintableSink;
18
- }
19
- }
20
- return {
21
- sink: glSink ?? paintableSink,
22
- paintable,
23
- glSink
24
- };
10
+ ensurePaintableSinkAvailable();
11
+ const paintableSink = Gst.ElementFactory.make("gtk4paintablesink", "videosink");
12
+ if (!paintableSink) {
13
+ throw new Error("Failed to create gtk4paintablesink element");
14
+ }
15
+ const paintable = paintableSink.paintable;
16
+ if (!paintable) {
17
+ throw new Error("gtk4paintablesink has no paintable property");
18
+ }
19
+ let glSink = null;
20
+ const glContext = paintable.gl_context;
21
+ if (glContext) {
22
+ glSink = Gst.ElementFactory.make("glsinkbin", "glsink");
23
+ if (glSink) {
24
+ glSink.sink = paintableSink;
25
+ }
26
+ }
27
+ return {
28
+ sink: glSink ?? paintableSink,
29
+ paintable,
30
+ glSink
31
+ };
25
32
  }
33
+ /**
34
+ * Build a pipeline for rendering a MediaStream video track.
35
+ *
36
+ * Expects the track's _gstSource element (from getUserMedia) and the
37
+ * track's _gstPipeline. The source is removed from its original pipeline
38
+ * (created by getUserMedia) and re-parented into a new pipeline with:
39
+ * source → tee → queue → videoconvert → gtk4paintablesink
40
+ *
41
+ * The tee element allows other consumers (e.g. RTCPeerConnection.addTrack)
42
+ * to request additional branches without moving the source across pipelines.
43
+ */
26
44
  function buildMediaStreamPipeline(gstSource, gstPipeline) {
27
- ensureGstInit();
28
- const { sink, paintable } = createPaintableSink();
29
- if (gstPipeline) {
30
- gstPipeline.set_state(Gst.State.NULL);
31
- gstPipeline.remove(gstSource);
32
- }
33
- const pipeline = new Gst.Pipeline({ name: "video-bridge-pipeline" });
34
- const tee = Gst.ElementFactory.make("tee", "source-tee");
35
- if (!tee) {
36
- throw new Error("Failed to create tee element");
37
- }
38
- tee.allow_not_linked = true;
39
- const queue = Gst.ElementFactory.make("queue", "preview-queue");
40
- if (!queue) {
41
- throw new Error("Failed to create queue element");
42
- }
43
- const videoconvert = Gst.ElementFactory.make("videoconvert", "convert");
44
- if (!videoconvert) {
45
- throw new Error("Failed to create videoconvert element");
46
- }
47
- pipeline.add(gstSource);
48
- pipeline.add(tee);
49
- pipeline.add(queue);
50
- pipeline.add(videoconvert);
51
- pipeline.add(sink);
52
- if (!gstSource.link(tee)) {
53
- throw new Error("Failed to link source \u2192 tee");
54
- }
55
- const teeSrcPad = tee.request_pad_simple ? tee.request_pad_simple("src_%u") : tee.get_request_pad("src_%u");
56
- const queueSinkPad = queue.get_static_pad("sink");
57
- if (teeSrcPad && queueSinkPad) {
58
- teeSrcPad.link(queueSinkPad);
59
- } else {
60
- throw new Error("Failed to link tee \u2192 queue");
61
- }
62
- if (!queue.link(videoconvert)) {
63
- throw new Error("Failed to link queue \u2192 videoconvert");
64
- }
65
- if (!videoconvert.link(sink)) {
66
- throw new Error("Failed to link videoconvert \u2192 sink");
67
- }
68
- return { pipeline, paintable, tee };
45
+ ensureGstInit();
46
+ const { sink, paintable } = createPaintableSink();
47
+ if (gstPipeline) {
48
+ gstPipeline.set_state(Gst.State.NULL);
49
+ gstPipeline.remove(gstSource);
50
+ }
51
+ const pipeline = new Gst.Pipeline({ name: "video-bridge-pipeline" });
52
+ const tee = Gst.ElementFactory.make("tee", "source-tee");
53
+ if (!tee) {
54
+ throw new Error("Failed to create tee element");
55
+ }
56
+ tee.allow_not_linked = true;
57
+ const queue = Gst.ElementFactory.make("queue", "preview-queue");
58
+ if (!queue) {
59
+ throw new Error("Failed to create queue element");
60
+ }
61
+ const videoconvert = Gst.ElementFactory.make("videoconvert", "convert");
62
+ if (!videoconvert) {
63
+ throw new Error("Failed to create videoconvert element");
64
+ }
65
+ pipeline.add(gstSource);
66
+ pipeline.add(tee);
67
+ pipeline.add(queue);
68
+ pipeline.add(videoconvert);
69
+ pipeline.add(sink);
70
+ if (!gstSource.link(tee)) {
71
+ throw new Error("Failed to link source tee");
72
+ }
73
+ const teeSrcPad = tee.request_pad_simple ? tee.request_pad_simple("src_%u") : tee.get_request_pad("src_%u");
74
+ const queueSinkPad = queue.get_static_pad("sink");
75
+ if (teeSrcPad && queueSinkPad) {
76
+ teeSrcPad.link(queueSinkPad);
77
+ } else {
78
+ throw new Error("Failed to link tee queue");
79
+ }
80
+ if (!queue.link(videoconvert)) {
81
+ throw new Error("Failed to link queue videoconvert");
82
+ }
83
+ if (!videoconvert.link(sink)) {
84
+ throw new Error("Failed to link videoconvert sink");
85
+ }
86
+ return {
87
+ pipeline,
88
+ paintable,
89
+ tee
90
+ };
69
91
  }
92
+ /**
93
+ * Build a pipeline for playing a URI (video.src = "file:///..." or URL).
94
+ *
95
+ * Uses GStreamer playbin with gtk4paintablesink as video-sink.
96
+ */
70
97
  function buildUriPipeline(uri) {
71
- ensureGstInit();
72
- const { sink, paintable } = createPaintableSink();
73
- const playbin = Gst.ElementFactory.make("playbin", "playbin");
74
- if (!playbin) {
75
- throw new Error("Failed to create playbin element");
76
- }
77
- playbin.uri = uri;
78
- playbin.video_sink = sink;
79
- const pipeline = new Gst.Pipeline({ name: "video-bridge-uri-pipeline" });
80
- pipeline.add(playbin);
81
- return { pipeline, paintable };
98
+ ensureGstInit();
99
+ const { sink, paintable } = createPaintableSink();
100
+ const playbin = Gst.ElementFactory.make("playbin", "playbin");
101
+ if (!playbin) {
102
+ throw new Error("Failed to create playbin element");
103
+ }
104
+ playbin.uri = uri;
105
+ playbin.video_sink = sink;
106
+ const pipeline = new Gst.Pipeline({ name: "video-bridge-uri-pipeline" });
107
+ pipeline.add(playbin);
108
+ return {
109
+ pipeline,
110
+ paintable
111
+ };
82
112
  }
83
- export {
84
- buildMediaStreamPipeline,
85
- buildUriPipeline,
86
- createPaintableSink
87
- };
113
+
114
+ //#endregion
115
+ export { buildMediaStreamPipeline, buildUriPipeline, createPaintableSink };
@@ -1,3 +1,5 @@
1
+ import { Gst } from "./gst-init.js";
2
+ import { buildMediaStreamPipeline, buildUriPipeline } from "./pipeline-builder.js";
1
3
  import GObject from "gi://GObject";
2
4
  import GLib from "gi://GLib?version=2.0";
3
5
  import Gtk from "gi://Gtk?version=4.0";
@@ -5,319 +7,341 @@ import { attachEventControllers } from "@gjsify/event-bridge";
5
7
  import { Event } from "@gjsify/dom-events";
6
8
  import { BridgeEnvironment } from "@gjsify/bridge-types";
7
9
  import { HTMLVideoElement } from "@gjsify/dom-elements";
8
- import { buildMediaStreamPipeline, buildUriPipeline } from "./pipeline-builder.js";
9
- import { Gst as GstRuntime } from "./gst-init.js";
10
+
11
+ //#region src/video-bridge.ts
10
12
  const PLAY_ICON = "media-playback-start-symbolic";
11
13
  const PAUSE_ICON = "media-playback-pause-symbolic";
12
14
  const AUTO_HIDE_SECONDS = 2;
13
15
  const POSITION_TICK_MS = 200;
14
16
  function formatTime(seconds) {
15
- if (!isFinite(seconds) || isNaN(seconds)) return "--:--";
16
- const m = Math.floor(seconds / 60);
17
- const s = Math.floor(seconds % 60);
18
- return `${m}:${s.toString().padStart(2, "0")}`;
17
+ if (!isFinite(seconds) || isNaN(seconds)) return "--:--";
18
+ const m = Math.floor(seconds / 60);
19
+ const s = Math.floor(seconds % 60);
20
+ return `${m}:${s.toString().padStart(2, "0")}`;
19
21
  }
20
- const VideoBridge = GObject.registerClass(
21
- { GTypeName: "GjsifyVideoBridge" },
22
- class VideoBridge2 extends Gtk.Box {
23
- constructor(params) {
24
- super({ ...params, orientation: Gtk.Orientation.VERTICAL });
25
- this._timeOrigin = GLib.get_monotonic_time();
26
- this._pipeline = null;
27
- // Bus associated with _pipeline; stored so `_destroyPipeline` can
28
- // disconnect the handlers + `remove_signal_watch` before the pipeline
29
- // is nulled. Without cleanup, changing `video.src` repeatedly
30
- // accumulates handler connections on each pipeline's bus.
31
- this._pipelineBus = null;
32
- this._pipelineBusHandlers = [];
33
- this._readyCallbacks = [];
34
- this._resizeCallbacks = [];
35
- this._ready = false;
36
- // Control bar + its per-tick change-detection state (null when
37
- // showControls(false) or never called). Keeping _lastSeekValue /
38
- // _lastTimeText on the same object lets them live and die with the
39
- // controls; no separate reset needed.
40
- this._controls = null;
41
- this._positionTimerId = null;
42
- // change-value on seekScale fires on user interaction only; the guard prevents
43
- // programmatic set_value from bouncing through the signal on some compositors.
44
- this._updatingFromTimer = false;
45
- // Auto-hide: a single re-armed GLib source. Mouse motion re-starts the
46
- // 2s timer by removing and re-adding, so we never pile up pending sources.
47
- this._hideTimerId = null;
48
- this._overlay = new Gtk.Overlay({ hexpand: true, vexpand: true });
49
- this.append(this._overlay);
50
- this._picture = new Gtk.Picture({ hexpand: true, vexpand: true });
51
- this._overlay.set_child(this._picture);
52
- this._video = new HTMLVideoElement();
53
- const host = {
54
- performanceNow: () => (GLib.get_monotonic_time() - this._timeOrigin) / 1e3,
55
- getWidth: () => this.get_allocated_width(),
56
- getHeight: () => this.get_allocated_height(),
57
- getDevicePixelRatio: () => this.get_native()?.get_surface()?.get_scale_factor() ?? 1
58
- };
59
- this._environment = new BridgeEnvironment(host);
60
- this._environment.document.body.appendChild(this._video);
61
- attachEventControllers(this, () => this._video);
62
- this._video.addEventListener("srcobjectchange", () => this._onSrcObjectChange());
63
- this._video.addEventListener("srcchange", () => this._onSrcChange());
64
- this.connect("realize", () => {
65
- if (this._ready) return;
66
- this._ready = true;
67
- for (const cb of this._readyCallbacks) {
68
- cb(this._video);
69
- }
70
- this._readyCallbacks = [];
71
- });
72
- let lastWidth = 0;
73
- let lastHeight = 0;
74
- const checkResize = () => {
75
- const width = this.get_allocated_width();
76
- const height = this.get_allocated_height();
77
- if (width === lastWidth && height === lastHeight) return;
78
- lastWidth = width;
79
- lastHeight = height;
80
- this._video.dispatchEvent(new Event("resize"));
81
- for (const cb of this._resizeCallbacks) cb(width, height);
82
- };
83
- this.connect("notify::width-request", checkResize);
84
- this.connect("notify::height-request", checkResize);
85
- this.connect("map", checkResize);
86
- this.connect("unrealize", () => {
87
- this._destroyPipeline();
88
- this._stopPositionTimer();
89
- this._resizeCallbacks = [];
90
- });
91
- }
92
- get element() {
93
- return this._video;
94
- }
95
- get videoElement() {
96
- return this._video;
97
- }
98
- get environment() {
99
- return this._environment;
100
- }
101
- onReady(cb) {
102
- if (this._ready) {
103
- cb(this._video);
104
- return;
105
- }
106
- this._readyCallbacks.push(cb);
107
- }
108
- onResize(cb) {
109
- this._resizeCallbacks.push(cb);
110
- }
111
- installGlobals() {
112
- globalThis.HTMLVideoElement = HTMLVideoElement;
113
- if (typeof globalThis.performance === "undefined") {
114
- const timeOrigin = this._timeOrigin;
115
- globalThis.performance = {
116
- now: () => (GLib.get_monotonic_time() - timeOrigin) / 1e3,
117
- timeOrigin: Date.now()
118
- };
119
- }
120
- }
121
- /**
122
- * Show or hide the built-in play/pause + seek + time + volume control bar.
123
- * Controls auto-hide after 2 seconds of mouse inactivity.
124
- */
125
- showControls(show = true) {
126
- if (show && !this._controls) {
127
- this._controls = this._buildControlBar();
128
- const { bar } = this._controls;
129
- bar.set_halign(Gtk.Align.FILL);
130
- bar.set_valign(Gtk.Align.END);
131
- bar.set_visible(false);
132
- this._overlay.add_overlay(bar);
133
- this._startPositionTimer();
134
- this._setupAutoHideMotion(bar);
135
- } else if (!show && this._controls) {
136
- this._overlay.remove_overlay(this._controls.bar);
137
- this._controls = null;
138
- this._stopPositionTimer();
139
- if (this._hideTimerId !== null) {
140
- GLib.Source.remove(this._hideTimerId);
141
- this._hideTimerId = null;
142
- }
143
- }
144
- }
145
- _setupAutoHideMotion(controlBar) {
146
- for (const widget of [this, controlBar]) {
147
- const motion = new Gtk.EventControllerMotion();
148
- motion.connect("motion", () => this._revealControls());
149
- motion.connect("enter", () => this._revealControls());
150
- widget.add_controller(motion);
151
- }
152
- }
153
- _revealControls() {
154
- if (!this._controls) return;
155
- this._controls.bar.set_visible(true);
156
- if (this._hideTimerId !== null) GLib.Source.remove(this._hideTimerId);
157
- this._hideTimerId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, AUTO_HIDE_SECONDS, () => {
158
- this._hideTimerId = null;
159
- this._controls?.bar.set_visible(false);
160
- return GLib.SOURCE_REMOVE;
161
- });
162
- }
163
- _buildControlBar() {
164
- const bar = new Gtk.Box({
165
- orientation: Gtk.Orientation.HORIZONTAL,
166
- spacing: 6,
167
- margin_start: 6,
168
- margin_end: 6,
169
- margin_top: 4,
170
- margin_bottom: 4
171
- });
172
- bar.add_css_class("osd");
173
- const playBtn = new Gtk.Button({ icon_name: PAUSE_ICON });
174
- playBtn.connect("clicked", () => {
175
- if (this._video.paused) {
176
- this._video.play();
177
- playBtn.set_icon_name(PAUSE_ICON);
178
- } else {
179
- this._video.pause();
180
- playBtn.set_icon_name(PLAY_ICON);
181
- }
182
- });
183
- bar.append(playBtn);
184
- const seekAdj = new Gtk.Adjustment({ lower: 0, upper: 1, step_increment: 1, page_increment: 10 });
185
- const seekScale = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, seekAdj);
186
- seekScale.set_hexpand(true);
187
- seekScale.set_draw_value(false);
188
- seekScale.connect("change-value", (_scale, _scroll, value) => {
189
- if (!this._updatingFromTimer && isFinite(value)) {
190
- this._video.currentTime = value;
191
- }
192
- return false;
193
- });
194
- bar.append(seekScale);
195
- const timeLabel = new Gtk.Label({ label: "--:-- / --:--", use_markup: false });
196
- bar.append(timeLabel);
197
- const volumeBtn = new Gtk.VolumeButton({ value: 1 });
198
- volumeBtn.connect("value-changed", (_btn, value) => {
199
- this._video.volume = value;
200
- });
201
- bar.append(volumeBtn);
202
- return { bar, playBtn, seekAdj, seekScale, timeLabel, volumeBtn, lastSeekValue: NaN, lastTimeText: "" };
203
- }
204
- _startPositionTimer() {
205
- if (this._positionTimerId !== null) return;
206
- this._positionTimerId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, POSITION_TICK_MS, () => {
207
- const controls = this._controls;
208
- if (!controls) return GLib.SOURCE_REMOVE;
209
- const cur = this._video.currentTime;
210
- const dur = this._video.duration;
211
- if (isFinite(dur) && dur > 0) {
212
- if (controls.seekAdj.upper !== dur) controls.seekAdj.upper = dur;
213
- if (cur !== controls.lastSeekValue) {
214
- this._updatingFromTimer = true;
215
- controls.seekAdj.set_value(cur);
216
- this._updatingFromTimer = false;
217
- controls.lastSeekValue = cur;
218
- }
219
- }
220
- const text = `${formatTime(cur)} / ${formatTime(dur)}`;
221
- if (text !== controls.lastTimeText) {
222
- controls.timeLabel.set_label(text);
223
- controls.lastTimeText = text;
224
- }
225
- const icon = this._video.paused ? PLAY_ICON : PAUSE_ICON;
226
- if (controls.playBtn.get_icon_name() !== icon) controls.playBtn.set_icon_name(icon);
227
- return GLib.SOURCE_CONTINUE;
228
- });
229
- }
230
- _stopPositionTimer() {
231
- if (this._positionTimerId !== null) {
232
- GLib.Source.remove(this._positionTimerId);
233
- this._positionTimerId = null;
234
- }
235
- }
236
- _onSrcObjectChange() {
237
- this._destroyPipeline();
238
- const stream = this._video.srcObject;
239
- if (!stream) return;
240
- const tracks = stream.getVideoTracks?.() ?? [];
241
- const track = tracks.find((t) => t._gstSource != null);
242
- if (!track?._gstSource) {
243
- console.warn("VideoBridge: MediaStream has no video track with GStreamer source");
244
- return;
245
- }
246
- try {
247
- const { pipeline, paintable, tee } = buildMediaStreamPipeline(track._gstSource, track._gstPipeline);
248
- this._attachPipeline(pipeline, paintable);
249
- track._gstPipeline = pipeline;
250
- track._gstTee = tee;
251
- } catch (err) {
252
- console.error("VideoBridge: Failed to build MediaStream pipeline:", err);
253
- }
254
- }
255
- _onSrcChange() {
256
- this._destroyPipeline();
257
- if (!this._video.src) return;
258
- try {
259
- const { pipeline, paintable } = buildUriPipeline(this._video.src);
260
- this._attachPipeline(pipeline, paintable);
261
- } catch (err) {
262
- console.error("VideoBridge: Failed to build URI pipeline:", err);
263
- }
264
- }
265
- _attachPipeline(pipeline, paintable) {
266
- this._pipeline = pipeline;
267
- this._video._pipeline = pipeline;
268
- this._picture.set_paintable(paintable);
269
- const bus = pipeline.get_bus();
270
- if (bus) {
271
- bus.add_signal_watch();
272
- this._pipelineBus = bus;
273
- this._pipelineBusHandlers = [
274
- bus.connect("message::error", (_b, msg) => {
275
- const [err, debug] = msg.parse_error();
276
- console.error(`VideoBridge pipeline error: ${err?.message ?? "unknown"} (${debug ?? ""})`);
277
- this._video.dispatchEvent(new Event("error"));
278
- }),
279
- bus.connect("message::warning", (_b, msg) => {
280
- const [err, debug] = msg.parse_warning();
281
- console.warn(`VideoBridge pipeline warning: ${err?.message ?? "unknown"} (${debug ?? ""})`);
282
- })
283
- ];
284
- }
285
- const ret = pipeline.set_state(GstRuntime.State.PLAYING);
286
- if (ret === GstRuntime.StateChangeReturn.FAILURE) {
287
- console.error("VideoBridge: pipeline state change to PLAYING failed");
288
- }
289
- this._video.readyState = 4;
290
- this._video.dispatchEvent(new Event("loadedmetadata"));
291
- this._video.dispatchEvent(new Event("canplay"));
292
- this._video.dispatchEvent(new Event("playing"));
293
- }
294
- _destroyPipeline() {
295
- if (this._pipelineBus) {
296
- for (const id of this._pipelineBusHandlers) {
297
- try {
298
- this._pipelineBus.disconnect(id);
299
- } catch {
300
- }
301
- }
302
- try {
303
- this._pipelineBus.remove_signal_watch();
304
- } catch {
305
- }
306
- this._pipelineBus = null;
307
- this._pipelineBusHandlers = [];
308
- }
309
- if (this._pipeline) {
310
- try {
311
- this._pipeline.set_state(GstRuntime.State.NULL);
312
- } catch {
313
- }
314
- this._pipeline = null;
315
- this._video._pipeline = null;
316
- }
317
- this._picture.set_paintable(null);
318
- }
319
- }
320
- );
321
- export {
322
- VideoBridge
323
- };
22
+ /**
23
+ * A `Gtk.Box` subclass that hosts a `Gtk.Picture` for video rendering.
24
+ *
25
+ * - Owns an `HTMLVideoElement` whose DOM API is wired to GStreamer
26
+ * - Renders video via `gtk4paintablesink` → `Gdk.Paintable` → `Gtk.Picture`
27
+ * - Supports `video.srcObject = mediaStream` (getUserMedia / WebRTC)
28
+ * - Supports `video.src = 'file://…'` or HTTP URL (URI playback via playbin)
29
+ * - `onReady(cb)` fires with the HTMLVideoElement when the widget realizes
30
+ * - `showControls(true)` appends a play/pause + seek + time + volume bar
31
+ *
32
+ * ```ts
33
+ * const bridge = new VideoBridge();
34
+ * bridge.showControls(true);
35
+ * bridge.onReady((video) => { video.src = 'https://example.com/video.mp4'; });
36
+ * window.set_child(bridge);
37
+ * ```
38
+ */
39
+ const VideoBridge = GObject.registerClass({ GTypeName: "GjsifyVideoBridge" }, class VideoBridge extends Gtk.Box {
40
+ constructor(params) {
41
+ super({
42
+ ...params,
43
+ orientation: Gtk.Orientation.VERTICAL
44
+ });
45
+ this._timeOrigin = GLib.get_monotonic_time();
46
+ this._pipeline = null;
47
+ this._pipelineBus = null;
48
+ this._pipelineBusHandlers = [];
49
+ this._readyCallbacks = [];
50
+ this._resizeCallbacks = [];
51
+ this._ready = false;
52
+ this._controls = null;
53
+ this._positionTimerId = null;
54
+ this._updatingFromTimer = false;
55
+ this._hideTimerId = null;
56
+ this._overlay = new Gtk.Overlay({
57
+ hexpand: true,
58
+ vexpand: true
59
+ });
60
+ this.append(this._overlay);
61
+ this._picture = new Gtk.Picture({
62
+ hexpand: true,
63
+ vexpand: true
64
+ });
65
+ this._overlay.set_child(this._picture);
66
+ this._video = new HTMLVideoElement();
67
+ const host = {
68
+ performanceNow: () => (GLib.get_monotonic_time() - this._timeOrigin) / 1e3,
69
+ getWidth: () => this.get_allocated_width(),
70
+ getHeight: () => this.get_allocated_height(),
71
+ getDevicePixelRatio: () => this.get_native()?.get_surface()?.get_scale_factor() ?? 1
72
+ };
73
+ this._environment = new BridgeEnvironment(host);
74
+ this._environment.document.body.appendChild(this._video);
75
+ attachEventControllers(this, () => this._video);
76
+ this._video.addEventListener("srcobjectchange", () => this._onSrcObjectChange());
77
+ this._video.addEventListener("srcchange", () => this._onSrcChange());
78
+ this.connect("realize", () => {
79
+ if (this._ready) return;
80
+ this._ready = true;
81
+ for (const cb of this._readyCallbacks) {
82
+ cb(this._video);
83
+ }
84
+ this._readyCallbacks = [];
85
+ });
86
+ let lastWidth = 0;
87
+ let lastHeight = 0;
88
+ const checkResize = () => {
89
+ const width = this.get_allocated_width();
90
+ const height = this.get_allocated_height();
91
+ if (width === lastWidth && height === lastHeight) return;
92
+ lastWidth = width;
93
+ lastHeight = height;
94
+ this._video.dispatchEvent(new Event("resize"));
95
+ for (const cb of this._resizeCallbacks) cb(width, height);
96
+ };
97
+ this.connect("notify::width-request", checkResize);
98
+ this.connect("notify::height-request", checkResize);
99
+ this.connect("map", checkResize);
100
+ this.connect("unrealize", () => {
101
+ this._destroyPipeline();
102
+ this._stopPositionTimer();
103
+ this._resizeCallbacks = [];
104
+ });
105
+ }
106
+ get element() {
107
+ return this._video;
108
+ }
109
+ get videoElement() {
110
+ return this._video;
111
+ }
112
+ get environment() {
113
+ return this._environment;
114
+ }
115
+ onReady(cb) {
116
+ if (this._ready) {
117
+ cb(this._video);
118
+ return;
119
+ }
120
+ this._readyCallbacks.push(cb);
121
+ }
122
+ onResize(cb) {
123
+ this._resizeCallbacks.push(cb);
124
+ }
125
+ installGlobals() {
126
+ globalThis.HTMLVideoElement = HTMLVideoElement;
127
+ if (typeof globalThis.performance === "undefined") {
128
+ const timeOrigin = this._timeOrigin;
129
+ globalThis.performance = {
130
+ now: () => (GLib.get_monotonic_time() - timeOrigin) / 1e3,
131
+ timeOrigin: Date.now()
132
+ };
133
+ }
134
+ }
135
+ /**
136
+ * Show or hide the built-in play/pause + seek + time + volume control bar.
137
+ * Controls auto-hide after 2 seconds of mouse inactivity.
138
+ */
139
+ showControls(show = true) {
140
+ if (show && !this._controls) {
141
+ this._controls = this._buildControlBar();
142
+ const { bar } = this._controls;
143
+ bar.set_halign(Gtk.Align.FILL);
144
+ bar.set_valign(Gtk.Align.END);
145
+ bar.set_visible(false);
146
+ this._overlay.add_overlay(bar);
147
+ this._startPositionTimer();
148
+ this._setupAutoHideMotion(bar);
149
+ } else if (!show && this._controls) {
150
+ this._overlay.remove_overlay(this._controls.bar);
151
+ this._controls = null;
152
+ this._stopPositionTimer();
153
+ if (this._hideTimerId !== null) {
154
+ GLib.Source.remove(this._hideTimerId);
155
+ this._hideTimerId = null;
156
+ }
157
+ }
158
+ }
159
+ _setupAutoHideMotion(controlBar) {
160
+ for (const widget of [this, controlBar]) {
161
+ const motion = new Gtk.EventControllerMotion();
162
+ motion.connect("motion", () => this._revealControls());
163
+ motion.connect("enter", () => this._revealControls());
164
+ widget.add_controller(motion);
165
+ }
166
+ }
167
+ _revealControls() {
168
+ if (!this._controls) return;
169
+ this._controls.bar.set_visible(true);
170
+ if (this._hideTimerId !== null) GLib.Source.remove(this._hideTimerId);
171
+ this._hideTimerId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, AUTO_HIDE_SECONDS, () => {
172
+ this._hideTimerId = null;
173
+ this._controls?.bar.set_visible(false);
174
+ return GLib.SOURCE_REMOVE;
175
+ });
176
+ }
177
+ _buildControlBar() {
178
+ const bar = new Gtk.Box({
179
+ orientation: Gtk.Orientation.HORIZONTAL,
180
+ spacing: 6,
181
+ margin_start: 6,
182
+ margin_end: 6,
183
+ margin_top: 4,
184
+ margin_bottom: 4
185
+ });
186
+ bar.add_css_class("osd");
187
+ const playBtn = new Gtk.Button({ icon_name: PAUSE_ICON });
188
+ playBtn.connect("clicked", () => {
189
+ if (this._video.paused) {
190
+ this._video.play();
191
+ playBtn.set_icon_name(PAUSE_ICON);
192
+ } else {
193
+ this._video.pause();
194
+ playBtn.set_icon_name(PLAY_ICON);
195
+ }
196
+ });
197
+ bar.append(playBtn);
198
+ const seekAdj = new Gtk.Adjustment({
199
+ lower: 0,
200
+ upper: 1,
201
+ step_increment: 1,
202
+ page_increment: 10
203
+ });
204
+ const seekScale = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, seekAdj);
205
+ seekScale.set_hexpand(true);
206
+ seekScale.set_draw_value(false);
207
+ seekScale.connect("change-value", (_scale, _scroll, value) => {
208
+ if (!this._updatingFromTimer && isFinite(value)) {
209
+ this._video.currentTime = value;
210
+ }
211
+ return false;
212
+ });
213
+ bar.append(seekScale);
214
+ const timeLabel = new Gtk.Label({
215
+ label: "--:-- / --:--",
216
+ use_markup: false
217
+ });
218
+ bar.append(timeLabel);
219
+ const volumeBtn = new Gtk.VolumeButton({ value: 1 });
220
+ volumeBtn.connect("value-changed", (_btn, value) => {
221
+ this._video.volume = value;
222
+ });
223
+ bar.append(volumeBtn);
224
+ return {
225
+ bar,
226
+ playBtn,
227
+ seekAdj,
228
+ seekScale,
229
+ timeLabel,
230
+ volumeBtn,
231
+ lastSeekValue: NaN,
232
+ lastTimeText: ""
233
+ };
234
+ }
235
+ _startPositionTimer() {
236
+ if (this._positionTimerId !== null) return;
237
+ this._positionTimerId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, POSITION_TICK_MS, () => {
238
+ const controls = this._controls;
239
+ if (!controls) return GLib.SOURCE_REMOVE;
240
+ const cur = this._video.currentTime;
241
+ const dur = this._video.duration;
242
+ if (isFinite(dur) && dur > 0) {
243
+ if (controls.seekAdj.upper !== dur) controls.seekAdj.upper = dur;
244
+ if (cur !== controls.lastSeekValue) {
245
+ this._updatingFromTimer = true;
246
+ controls.seekAdj.set_value(cur);
247
+ this._updatingFromTimer = false;
248
+ controls.lastSeekValue = cur;
249
+ }
250
+ }
251
+ const text = `${formatTime(cur)} / ${formatTime(dur)}`;
252
+ if (text !== controls.lastTimeText) {
253
+ controls.timeLabel.set_label(text);
254
+ controls.lastTimeText = text;
255
+ }
256
+ const icon = this._video.paused ? PLAY_ICON : PAUSE_ICON;
257
+ if (controls.playBtn.get_icon_name() !== icon) controls.playBtn.set_icon_name(icon);
258
+ return GLib.SOURCE_CONTINUE;
259
+ });
260
+ }
261
+ _stopPositionTimer() {
262
+ if (this._positionTimerId !== null) {
263
+ GLib.Source.remove(this._positionTimerId);
264
+ this._positionTimerId = null;
265
+ }
266
+ }
267
+ _onSrcObjectChange() {
268
+ this._destroyPipeline();
269
+ const stream = this._video.srcObject;
270
+ if (!stream) return;
271
+ const tracks = stream.getVideoTracks?.() ?? [];
272
+ const track = tracks.find((t) => t._gstSource != null);
273
+ if (!track?._gstSource) {
274
+ console.warn("VideoBridge: MediaStream has no video track with GStreamer source");
275
+ return;
276
+ }
277
+ try {
278
+ const { pipeline, paintable, tee } = buildMediaStreamPipeline(track._gstSource, track._gstPipeline);
279
+ this._attachPipeline(pipeline, paintable);
280
+ track._gstPipeline = pipeline;
281
+ track._gstTee = tee;
282
+ } catch (err) {
283
+ console.error("VideoBridge: Failed to build MediaStream pipeline:", err);
284
+ }
285
+ }
286
+ _onSrcChange() {
287
+ this._destroyPipeline();
288
+ if (!this._video.src) return;
289
+ try {
290
+ const { pipeline, paintable } = buildUriPipeline(this._video.src);
291
+ this._attachPipeline(pipeline, paintable);
292
+ } catch (err) {
293
+ console.error("VideoBridge: Failed to build URI pipeline:", err);
294
+ }
295
+ }
296
+ _attachPipeline(pipeline, paintable) {
297
+ this._pipeline = pipeline;
298
+ this._video._pipeline = pipeline;
299
+ this._picture.set_paintable(paintable);
300
+ const bus = pipeline.get_bus();
301
+ if (bus) {
302
+ bus.add_signal_watch();
303
+ this._pipelineBus = bus;
304
+ this._pipelineBusHandlers = [bus.connect("message::error", (_b, msg) => {
305
+ const [err, debug] = msg.parse_error();
306
+ console.error(`VideoBridge pipeline error: ${err?.message ?? "unknown"} (${debug ?? ""})`);
307
+ this._video.dispatchEvent(new Event("error"));
308
+ }), bus.connect("message::warning", (_b, msg) => {
309
+ const [err, debug] = msg.parse_warning();
310
+ console.warn(`VideoBridge pipeline warning: ${err?.message ?? "unknown"} (${debug ?? ""})`);
311
+ })];
312
+ }
313
+ const ret = pipeline.set_state(Gst.State.PLAYING);
314
+ if (ret === Gst.StateChangeReturn.FAILURE) {
315
+ console.error("VideoBridge: pipeline state change to PLAYING failed");
316
+ }
317
+ this._video.readyState = 4;
318
+ this._video.dispatchEvent(new Event("loadedmetadata"));
319
+ this._video.dispatchEvent(new Event("canplay"));
320
+ this._video.dispatchEvent(new Event("playing"));
321
+ }
322
+ _destroyPipeline() {
323
+ if (this._pipelineBus) {
324
+ for (const id of this._pipelineBusHandlers) {
325
+ try {
326
+ this._pipelineBus.disconnect(id);
327
+ } catch {}
328
+ }
329
+ try {
330
+ this._pipelineBus.remove_signal_watch();
331
+ } catch {}
332
+ this._pipelineBus = null;
333
+ this._pipelineBusHandlers = [];
334
+ }
335
+ if (this._pipeline) {
336
+ try {
337
+ this._pipeline.set_state(Gst.State.NULL);
338
+ } catch {}
339
+ this._pipeline = null;
340
+ this._video._pipeline = null;
341
+ }
342
+ this._picture.set_paintable(null);
343
+ }
344
+ });
345
+
346
+ //#endregion
347
+ export { VideoBridge };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjsify/video",
3
- "version": "0.3.12",
3
+ "version": "0.3.14",
4
4
  "description": "VideoBridge — GTK container for HTMLVideoElement backed by GStreamer gtk4paintablesink",
5
5
  "type": "module",
6
6
  "module": "lib/esm/index.js",
@@ -26,20 +26,20 @@
26
26
  "bridge"
27
27
  ],
28
28
  "dependencies": {
29
- "@girs/gdk-4.0": "^4.0.0-4.0.0-rc.9",
30
- "@girs/gjs": "^4.0.0-rc.9",
31
- "@girs/glib-2.0": "^2.88.0-4.0.0-rc.9",
32
- "@girs/gobject-2.0": "^2.88.0-4.0.0-rc.9",
33
- "@girs/gst-1.0": "^1.28.1-4.0.0-rc.9",
34
- "@girs/gtk-4.0": "^4.23.0-4.0.0-rc.9",
35
- "@gjsify/bridge-types": "^0.3.12",
36
- "@gjsify/dom-elements": "^0.3.12",
37
- "@gjsify/dom-events": "^0.3.12",
38
- "@gjsify/dom-exception": "^0.3.12",
39
- "@gjsify/event-bridge": "^0.3.12"
29
+ "@girs/gdk-4.0": "4.0.0-4.0.0-rc.9",
30
+ "@girs/gjs": "4.0.0-rc.9",
31
+ "@girs/glib-2.0": "2.88.0-4.0.0-rc.9",
32
+ "@girs/gobject-2.0": "2.88.0-4.0.0-rc.9",
33
+ "@girs/gst-1.0": "1.28.1-4.0.0-rc.9",
34
+ "@girs/gtk-4.0": "4.23.0-4.0.0-rc.9",
35
+ "@gjsify/bridge-types": "^0.3.14",
36
+ "@gjsify/dom-elements": "^0.3.14",
37
+ "@gjsify/dom-events": "^0.3.14",
38
+ "@gjsify/dom-exception": "^0.3.14",
39
+ "@gjsify/event-bridge": "^0.3.14"
40
40
  },
41
41
  "devDependencies": {
42
- "@gjsify/cli": "^0.3.12",
42
+ "@gjsify/cli": "^0.3.14",
43
43
  "@types/node": "^25.6.0",
44
44
  "typescript": "^6.0.3"
45
45
  }