aboutsummaryrefslogtreecommitdiffstats
path: root/desktop/island/Obs.qml
blob: 593e97819eedb241ace511a346da8f4a39c85b16 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

pragma Singleton

import Quickshell
import Quickshell.Io
import QtQuick
import QtWebSockets
import "Logic.js" as Logic

// OBS Studio over obs-websocket v5. Connected means OBS is running with
// its server enabled, so nothing checks for the process. State follows
// OBS's events; actions only send requests and never set state
// optimistically.
Singleton {
    id: root

    property bool connected: false
    property bool recording: false
    property bool paused: false
    // RecordStateChanged is authoritative once one has arrived; the 1s poll
    // then only carries the clock, so a response from just before the pause
    // cannot put the panel back into "not recording".
    property bool stateFromEvents: false
    property real duration: 0
    property var scenes: []
    property string scene: ""
    // The current scene's items as { name, kind }, for the window-source
    // properties button. Kept current with the same GetSceneItemList call.
    property var sources: []
    // The webcam: the first v4l2_input item in the current scene, -1 for none.
    // ponytail: a webcam inside a group or nested scene is not found; walk
    // GetGroupSceneItemList if one ever is.
    property int camId: -1
    property bool camOn: false
    property real camW: 0
    property real camH: 0
    // The global "Desktop Audio" input's name, "" when none is configured.
    property string desktopAudio: ""
    property bool desktopMuted: false
    property real baseWidth: 0
    property real baseHeight: 0

    function toggleRecord() { request("ToggleRecord"); }
    function togglePause() { request("ToggleRecordPause"); }
    function setScene(name) { if (name) request("SetCurrentProgramScene", { sceneName: name }); }
    function toggleCam() {
        if (camId >= 0)
            request("SetSceneItemEnabled", { sceneName: scene, sceneItemId: camId, sceneItemEnabled: !camOn });
    }
    function toggleAudio() {
        if (desktopAudio)
            request("SetInputMute", { inputName: desktopAudio, inputMuted: !desktopMuted });
    }
    // Opens OBS's source dialog, which is where the Wayland portal picker runs.
    function openSource(name) {
        if (name) request("OpenInputPropertiesDialog", { inputName: name });
    }
    // The corner math assumes the webcam item is top-left aligned (alignment 5).
    function moveCam(corner) {
        if (camId < 0 || baseWidth <= 0 || camW <= 0 || camH <= 0) return;
        const p = Logic.cornerPos(corner, baseWidth, baseHeight, camW, camH, 16);
        request("SetSceneItemTransform", { sceneName: scene, sceneItemId: camId,
            sceneItemTransform: { positionX: p.x, positionY: p.y } });
    }

    // --- config -----------------------------------------------------------

    // OBS's own file, so no copy of the password exists anywhere else.
    FileView {
        id: cfg
        path: `${Quickshell.env("XDG_CONFIG_HOME") || Quickshell.env("HOME") + "/.config"}/obs-studio/plugin_config/obs-websocket/config.json`
        watchChanges: true
        onFileChanged: reload()
    }

    function config() {
        try { return JSON.parse(cfg.text()); } catch (e) { return null; }
    }

    // --- socket -----------------------------------------------------------

    property bool warned: false
    property bool wasOpen: false

    WebSocket {
        id: sock
        onStatusChanged: {
            if (sock.status === WebSocket.Open) { root.wasOpen = true; return; }
            if (sock.status === WebSocket.Connecting) return;
            // QML's WebSocket hides the close code, so a wrong password
            // (4009) and OBS quitting look the same. Say it once per run.
            if (root.wasOpen && !root.connected && !root.warned) {
                console.warn("obs: closed before Identified, wrong password?");
                root.warned = true;
            }
            root.reset();
        }
        onTextMessageReceived: message => {
            try { root.receive(JSON.parse(message)); }
            catch (e) { console.warn(`obs: bad message: ${e}`); }
        }
    }

    function reset() {
        connected = false; wasOpen = false;
        recording = false; paused = false; duration = 0;
        stateFromEvents = false;
        scenes = []; scene = ""; camId = -1; camOn = false;
        sources = [];
        camW = 0; camH = 0;
        desktopAudio = ""; desktopMuted = false;
        baseWidth = 0; baseHeight = 0;
    }

    // Retry while not connected; a closed or failed socket is reopened by
    // toggling active.
    Timer {
        interval: 3000
        repeat: true
        running: !root.connected
        triggeredOnStart: true
        onTriggered: {
            if (sock.status === WebSocket.Open || sock.status === WebSocket.Connecting) return;
            const c = root.config();
            if (!c || !c.server_enabled) return;
            sock.active = false;
            sock.url = `ws://127.0.0.1:${c.server_port}`;
            sock.active = true;
        }
    }

    // --- protocol -----------------------------------------------------------

    property int seq: 0

    function send(op, d) { sock.sendTextMessage(JSON.stringify({ op: op, d: d })); }

    function request(type, data) {
        if (!connected) return;
        send(6, { requestType: type, requestId: String(++seq), requestData: data || {} });
    }

    function identify(token) {
        const d = { rpcVersion: 1, eventSubscriptions: 4 | 8 | 64 | 128 }; // Scenes | Inputs | Outputs | SceneItems
        if (token) d.authentication = token;
        send(1, d);
    }

    Process {
        id: auth
        command: ["sh", `${Quickshell.shellDir}/island/obs-auth.sh`]
        stdinEnabled: true
        property string data: ""
        onStarted: { auth.write(auth.data); auth.stdinEnabled = false; }
        stdout: StdioCollector { onStreamFinished: root.identify(text.trim()) }
    }

    function receive(m) {
        switch (m.op) {
        case 0: { // Hello
            const a = m.d.authentication;
            if (!a) { identify(""); break; }
            const c = config();
            auth.data = `${c ? c.server_password : ""}${a.salt}\n${a.challenge}\n`;
            auth.stdinEnabled = true;
            auth.running = false;
            auth.running = true;
            break;
        }
        case 2: // Identified
            connected = true;
            warned = false;
            request("GetRecordStatus");
            request("GetSceneList");
            request("GetSpecialInputs");
            request("GetVideoSettings");
            break;
        case 5:
            event(m.d.eventType, m.d.eventData || {});
            break;
        case 7:
            response(m.d);
            break;
        }
    }

    function event(type, d) {
        switch (type) {
        case "RecordStateChanged":
            stateFromEvents = true;
            // obs-websocket reports outputActive false while PAUSED, so a
            // paused take must still count as recording or the panel offers
            // Record and a click stops it.
            paused = d.outputState === "OBS_WEBSOCKET_OUTPUT_PAUSED";
            recording = d.outputActive || paused
                || d.outputState === "OBS_WEBSOCKET_OUTPUT_RESUMED";
            if (!recording) duration = 0;
            break;
        case "CurrentProgramSceneChanged":
            scene = d.sceneName;
            request("GetSceneItemList", { sceneName: scene });
            break;
        case "SceneListChanged":
        case "SceneItemCreated":
        case "SceneItemRemoved":
            request("GetSceneList");
            break;
        case "SceneItemEnableStateChanged":
            if (d.sceneName === scene && d.sceneItemId === camId) camOn = d.sceneItemEnabled;
            break;
        case "InputMuteStateChanged":
            if (d.inputName === desktopAudio) desktopMuted = d.inputMuted;
            break;
        }
    }

    function response(d) {
        if (!d.requestStatus.result) {
            console.warn(`obs: ${d.requestType} failed: ${d.requestStatus.comment ?? d.requestStatus.code}`);
            return;
        }
        const r = d.responseData || {};
        switch (d.requestType) {
        case "GetRecordStatus":
            duration = r.outputDuration;
            // Seed the state on connect; after that the events own it.
            if (!root.stateFromEvents) {
                paused = r.outputPaused;
                recording = r.outputActive || r.outputPaused;
            }
            break;
        case "GetSceneList":
            // obs-websocket lists scenes bottom-up; reversed is OBS's own order.
            scenes = r.scenes.slice().reverse().map(s => s.sceneName);
            scene = r.currentProgramSceneName;
            request("GetSceneItemList", { sceneName: scene });
            break;
        case "GetSceneItemList": {
            sources = r.sceneItems.map(i => ({ name: i.sourceName, kind: i.inputKind }));
            const it = r.sceneItems.find(i => i.inputKind === "v4l2_input");
            camId = it ? it.sceneItemId : -1;
            camOn = !!it && it.sceneItemEnabled;
            camW = it ? it.sceneItemTransform.width : 0;
            camH = it ? it.sceneItemTransform.height : 0;
            break;
        }
        case "GetSpecialInputs":
            desktopAudio = r.desktop1 || "";
            if (desktopAudio) request("GetInputMute", { inputName: desktopAudio });
            break;
        case "GetVideoSettings":
            baseWidth = r.baseWidth;
            baseHeight = r.baseHeight;
            break;
        case "GetInputMute":
            desktopMuted = r.inputMuted;
            break;
        }
    }

    // OBS owns the clock, so pausing freezes it with no local bookkeeping.
    // ponytail: one local request a second, only while recording.
    Timer {
        interval: 1000
        repeat: true
        running: root.recording && !root.paused
        onTriggered: root.request("GetRecordStatus")
    }
}