-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathobs-proxy.js
234 lines (206 loc) · 7.16 KB
/
obs-proxy.js
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
config = {
worker_id: process.env.WORKER_ID || require("os").hostname(),
roomname: process.env.WS_ROOM || 'default',
ws_path: (process.env.HTTP_PATH || "").replace(/\/$/g, '') + '/socket.io',
ws_namespace: process.env.WS_NAMESPACE || '/',
ws_host: process.env.WS_HOST || 'http://localhost:3000',
obs_address: process.env.OBS_ADDRESS || 'localhost:4444',
obs_password: process.env.OBS_PASSWORD,
screenshot_format: process.env.SCREENSHOTF || 'jpg',
screenshot_width: parseInt(process.env.SCREENSHOTW || 200),
screenshot_quality: parseInt(process.env.SCREENSHOTQ || 75),
}
const io = require('socket.io-client')
const OBSWebSocket = require('obs-websocket-js');
const control = io(config.ws_host + config.ws_namespace, {path: config.ws_path});
const obs = new OBSWebSocket();
var media_playing = [];
var current_preview = null;
const EventEmitter = require('events');
const WsCommand = new EventEmitter();
const sendUpdate = async function(event) {
if ( obs._connected != true) {
return send_room({
'id': config.worker_id,
'status': 'connection_error',
}, 'obs');
}
const [stats, scene_list, preview_scene, streaming_stats, media] = await Promise.all([
obs.send('GetStats'),
obs.send('GetSceneList'),
obs.send('GetPreviewScene').catch(err => { return {}; }),
obs.send('GetStreamingStatus'),
getMediaPlaying(),
]);
current_preview = preview_scene.name || null;
const screenshot = await getSouceScreenshot(preview_scene.name);
return send_room({
'id': config.worker_id,
'scenes': scene_list.scenes.map(scene => scene.name),
'currentScene': scene_list.currentScene,
'previewScene': preview_scene.name || null,
'previewScreenshot': screenshot || '',
'recording': streaming_stats.recording,
'streaming': streaming_stats.streaming,
'status': stats.status,
'media': media,
'stats': {
'cpu-usage': stats.stats['cpu-usage'],
'memory-usage': stats.stats['memory-usage'],
'free-disk-space': stats.stats['free-disk-space'],
'render-missed-frames': stats.stats['render-missed-frames'],
},
}, 'obs');
};
const sendMediaUpdate = async function(event) {
if ( obs._connected != true) { return; }
if ( media_playing.length > 0 ) {
const media = await getMediaPlaying();
return send_room({
'id': config.worker_id,
'media': media,
}, 'obs-media');
}
}
const sendScreenshot = async function(scene) {
const screenshot = await getSouceScreenshot(scene);
return send_room({
'id': config.worker_id,
'previewScreenshot': screenshot,
}, 'obs-preview');
}
const getMediaPlaying = async function(event) {
var sources = [];
for (var source of media_playing) {
const [duration, time] = await Promise.all([
obs.send('GetMediaDuration', { 'sourceName': source}),
obs.send('GetMediaTime', { 'sourceName': source}),
]);
sources.push({ source: source, duration: duration.mediaDuration / 1000, time: time.timestamp / 1000 });
}
return sources;
}
const getSouceScreenshot = async function(scene) {
const screenshot = await obs.send('TakeSourceScreenshot', {
'sourceName': scene,
'embedPictureFormat': config.screenshot_format,
'compressionQuality': config.screenshot_quality,
'width': config.screenshot_width,
'height': Math.floor(config.screenshot_width * 9/16),
}).catch(err => { return ''; } )
return screenshot.img;
}
const obsConnect = function(){
obs.connect({ address: config.obs_address, password: config.obs_password })
.catch(err => {
console.log('obs: Error Connecting:', err.error);
});
}
// event functions
const media_playing_add = function(data){
console.log(`obs: ${data.updateType}: '${data.sourceName}'`);
if (media_playing.indexOf(data.sourceName) == -1) {
media_playing.push(data.sourceName);
}
sendUpdate();
}
const media_playing_del = function(data){
console.log(`obs: ${data.updateType}: '${data.sourceName}'`);
if (media_playing.indexOf(data.sourceName) != -1) {
media_playing.splice(media_playing.indexOf(data.sourceName), 1);
}
sendUpdate();
}
const updateMedia = async function(){
const mediasources = await obs.send('GetMediaSourcesList')
.then( d => { return d.mediaSources || []; })
.catch(err => { return []; });
for (source of mediasources){
if (source.mediaState == 'playing' || source.mediaState == 'paused') {
if (media_playing.indexOf(source.sourceName) == -1) {
media_playing.push(source.sourceName);
}
}
}
}
/**
* OBS Events
*/
obs.on('ConnectionOpened', () => {
console.log('obs: connected.');
media_playing = [];
updateMedia();
sendUpdate();
});
obs.on('ConnectionClosed', () => {
console.error('OBS disconnected.');
sendUpdate();
setTimeout(() => {
obsConnect();
}, 1000);
});
obs.on('error', err => {
console.error('socket error:', err);
});
obs.on('SwitchScenes', data => {
console.log(`obs: switched scene to '${data.sceneName}'`);
var source_names = data.sources.map(source => source.name);
media_playing = media_playing.filter(source => source_names.indexOf(source) != -1);
sendUpdate();
});
obs.on('PreviewSceneChanged', data => {
console.log(`obs: switched preview to '${data.sceneName}'`);
current_preview = data.sceneName;
sendUpdate();
});
// player controls
obs.on('MediaPlaying', data => media_playing_add(data));
obs.on('MediaStopped', data => media_playing_del(data));
// media events
obs.on('MediaStarted', data => media_playing_add(data));
obs.on('MediaEnded', data => media_playing_del(data)); // fires only on playlist end
obsConnect()
setInterval(() => {
sendUpdate();
}, 5000);
setInterval(() => {
sendMediaUpdate();
}, 1000);
/**
* Socket.io Events
*/
control.on('connect', function(){
console.log('ws: connect');
control.emit('register', {type: 'worker', room: config.roomname, id: config.worker_id});
});
control.on('register', function(){
console.log('ws: registered!');
});
control.on('disconnect', function(){
console.log('ws: disconnect');
});
control.on('room', function(data){
if (data.command && data.command in WsCommand._events) {
if (data.id && data.id != config.worker_id )
return
WsCommand.emit(data.command, data.command, data.data);
} else {
if ( !data.id || data.id == config.worker_id )
console.log('ws: unknown room message:', data);
}
});
function send_room(data, type=null) {
control.emit('room', {'type': type, 'source': config.worker_id, 'data': data})
}
/*
* WebSocket Commands
*/
WsCommand.on('discover', function(event, data) {
console.log('ws: answering discover.');
sendUpdate();
console.log(config);
});
WsCommand.on('send', function(event, data) {
console.log('ws: received command:', data.command, data.args);
obs.send(data.command, data.args);
});