-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·323 lines (272 loc) · 10.6 KB
/
index.js
File metadata and controls
executable file
·323 lines (272 loc) · 10.6 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import express from 'express';
import { Client, StageChannel } from 'discord.js-selfbot-v13';
import { streamLivestreamVideo, getInputMetadata, inputHasAudio, Streamer } from '@dank074/discord-video-stream';
import PCancelable from "p-cancelable";
//API
const app = express();
app.use(express.json());
const port = process.env.PORT || 3123;
app.listen(port, () => {
logMessage("API server is listening", `Port: ${port}`);
});
// Discord Login
const streamer = new Streamer(new Client());
streamer.client.login(process.env.DISCORD_TOKEN);
streamer.client.on('ready', () => {
logMessage("Bot is ready", `Bot Tag: ${streamer.client.user.tag}`);
});
let command = new PCancelable((resolve, reject, onCancel) => {
onCancel(() => {
console.log('Promise was canceled');
});
setTimeout(() => {
resolve('Done');
}, 1000);
});
let isPlayTimeoutActive = false;
app.post('/play', async (req, res) => {
const { guildId, channelId, stream, qualities, user } = req.body;
logMessage("Endpoint: /play", `
Server / Channel ID: ${guildId} / ${channelId}
User: ${user.name} (ID: ${user.id})
Stream Name: ${stream.name}
Stream URL: ${stream.url}
Qualities: ${JSON.stringify(qualities, null, 2)}
`);
if (!guildId || !channelId || !stream.url) {
const errorMessage = 'Missing required parameters: guildId, channelId, streamUrl';
logMessage("Response: 400 Bad Request", errorMessage);
return res.status(400).send(errorMessage);
}
if (isPlayTimeoutActive) {
const message = 'Play command is in cooldown. Please try again in a few seconds.';
logMessage("Response: 429 Too Many Requests", message);
return res.status(429).send(message);
}
isPlayTimeoutActive = true;
setTimeout(() => {
isPlayTimeoutActive = false;
}, 5000);
const guild = streamer.client.guilds.cache.get(guildId);
const channel = guild?.channels.cache.get(channelId);
if (!guild || !channel || channel.type !== 'GUILD_VOICE') {
const message = !guild
? 'Guild not found.'
: 'Voice channel not found or invalid.';
logMessage("Response: 404 Not Found", message);
return res.status(404).send(message);
}
let streamOptions, includeAudio;
try {
let metadata = await getInputMetadata(stream.url);
let videoStream = metadata.streams.find(stream => stream.codec_type === 'video');
if (!videoStream) {
throw new Error('No video stream found in the metadata');
}
streamOptions = generateStreamOptions(qualities, videoStream);
includeAudio = inputHasAudio(metadata);
} catch (e) {
const message = 'Error encountered while fetching metadata or generating stream options';
logMessage("Response: 500 Internal Server Error", `${message}\nError details: ${e}`);
return res.status(500).send(message);
}
try {
const currentVoiceState = streamer.client.user.voice;
if (currentVoiceState && currentVoiceState.channelId !== channelId) {
logMessage("Action: Joining voice channel", `
Server ID: ${guildId}
Target Channel ID: ${channelId}
`);
await streamer.joinVoice(guildId, channelId);
}
if (!streamer.voiceConnection) {
const botUserId = streamer.client.user.id;
const message = `Desync: Please kick detached Stream Bot instance with User ID ${botUserId} and try again.`;
logMessage("Response: 409 Conflict", message);
return res.status(409).json({ message, botUserId });
}
if (currentVoiceState && currentVoiceState.streaming) {
await endExistingStream(streamer, command);
}
const streamUdpConn = await streamer.createStream(streamOptions);
logMessage("Starting video stream", `
Stream URL: ${stream.url}
Stream Options: ${JSON.stringify(streamUdpConn._mediaConnection._streamOptions, null, 2)}
`);
startStream(stream.url, streamUdpConn, includeAudio);
await new Promise(resolve => setTimeout(resolve, 2000));
return res.status(200).send('Streaming started successfully.');
} catch (streamError) {
logMessage("Error while streaming", `${streamError}`);
return res.status(500).send('Failed to start streaming.');
}
});
app.post('/disconnect', async (req, res) => {
const { user } = req.body;
try {
await endExistingStream(streamer, command);
streamer.leaveVoice();
const successMessage = `Successfully disconnected and stopped the stream.`;
logMessage("Endpoint: /disconnect", `
${successMessage}
User: ${user.name} (ID: ${user.id})
`);
return res.status(200).send(successMessage);
} catch (error) {
const errorMessage = 'Failed to disconnect.';
logMessage("Endpoint: /disconnect - Error", `
${errorMessage}
User: ${user.name} (ID: ${user.id}) - Error details: ${error}
`);
return res.status(500).send(errorMessage);
}
});
function endExistingStream(streamer, command) {
return new Promise((resolve, reject) => {
try {
command.cancel();
streamer.stopStream();
setTimeout(() => {
resolve();
}, 1000);
} catch (error) {
reject(error);
}
});
}
async function startStream(streamUrl, udpConn, includeAudio) {
udpConn.mediaConnection.setSpeaking(true);
udpConn.mediaConnection.setVideoStatus(true);
try {
command = streamLivestreamVideo(streamUrl, udpConn, includeAudio);
const res = await command;
logMessage("Finished playing video", `Result: ${res}`);
} catch (e) {
if (command.isCanceled) {
logMessage("Stream was cancelled", "");
} else {
logMessage("Error during streaming", `Error details: ${e}`);
}
} finally {
udpConn.mediaConnection.setSpeaking(false);
udpConn.mediaConnection.setVideoStatus(false);
}
}
// Generate settings with priority: environment variable > api parameters > default value
function generateStreamOptions(qualities, videoStream) {
const height = process.env.HEIGHT ? parseInt(process.env.HEIGHT, 10)
: qualities?.height ? qualities.height
: videoStream.height;
const width = process.env.WIDTH ? parseInt(process.env.WIDTH, 10)
: qualities?.width ? qualities.width
: videoStream.width;
const fps = (() => {
const envFps = process.env.FPS ? parseInt(process.env.FPS, 10) : null;
const qualityFps = qualities?.fps || null;
const parsedFps = envFps ?? qualityFps ?? parseFps(videoStream.avg_frame_rate);
const maxFps = parseInt(process.env.MAX_FPS, 10);
return maxFps && parsedFps > maxFps ? maxFps : parsedFps;
})();
const { bitrateKbps: generatedBitrateKbps, maxBitrateKbps: generatedMaxBitrateKbps } = generateBitrateFromResolutionAndFramerate(height, width, fps);
const bitrateKbps = process.env.BITRATE_KBPS
? parseInt(process.env.BITRATE_KBPS, 10)
: qualities?.bitrateKbps
? qualities.bitrateKbps
: generatedBitrateKbps;
const maxBitrateKbps = process.env.MAX_BITRATE_KBPS
? parseInt(process.env.MAX_BITRATE_KBPS, 10)
: qualities?.maxBitrateKbps
? qualities.maxBitrateKbps
: generatedMaxBitrateKbps;
let videoCodec;
if (videoStream.codec_name === 'vp8' || videoStream.codec_name === 'vp9') {
videoCodec = 'VP8';
} else {
videoCodec = 'H264';
}
const h26xPreset = process.env.H26X_PRESET
? process.env.H26X_PRESET
: qualities?.h26xPreset
? qualities.h26xPreset
: "superfast";
const rtcpSenderReportEnabled = getBooleanSetting(
process.env.RTCP_SENDER,
qualities?.rtcpSenderReportEnabled,
false
);
const forceChacha20Encryption = getBooleanSetting(
process.env.FORCE_CHACHA,
qualities?.forceChacha20Encryption,
false
);
const hardwareAcceleratedDecoding = getBooleanSetting(
process.env.HARDWARE_ACCELERATION,
qualities?.hardwareAcceleratedDecoding,
true
);
const minimizeLatency = getBooleanSetting(
process.env.MINIMIZE_LATENCY,
qualities?.minimizeLatency,
true
);
return {
width,
height,
fps,
bitrateKbps,
maxBitrateKbps,
h26xPreset,
videoCodec,
hardwareAcceleratedDecoding,
rtcpSenderReportEnabled,
minimizeLatency,
forceChacha20Encryption
};
}
function parseFps(avgFrameRate) {
const [numerator, denominator] = avgFrameRate.split('/').map(Number);
return denominator ? Math.floor(numerator / denominator) : Math.floor(numerator);
}
function getBooleanSetting(envVar, qualityVar, defaultValue) {
const envValue = envVar === 'true' ? true : envVar === 'false' ? false : undefined;
const qualityValue = qualityVar === 'true' ? true : qualityVar === 'false' ? false : undefined;
return envValue ?? qualityValue ?? defaultValue;
}
function generateBitrateFromResolutionAndFramerate(height, width, framerate) {
let bitrateKbps;
let maxBitrateKbps;
if (height >= 2160) {
bitrateKbps = framerate >= 50 ? 20000 : 18000;
maxBitrateKbps = framerate >= 50 ? 25000 : 23000;
} else if (height >= 1440) {
bitrateKbps = framerate >= 50 ? 14000 : 12000;
maxBitrateKbps = framerate >= 50 ? 16000 : 14000;
} else if (height >= 1080) {
bitrateKbps = framerate >= 50 ? 10000 : 8000;
maxBitrateKbps = framerate >= 50 ? 12000 : 10000;
} else if (height >= 720) {
bitrateKbps = framerate >= 50 ? 7000 : 5000;
maxBitrateKbps = framerate >= 50 ? 9000 : 7000;
} else {
bitrateKbps = 6000;
maxBitrateKbps = 8000;
}
if (framerate < 30) {
bitrateKbps *= 0.85;
maxBitrateKbps *= 0.85;
}
return {
bitrateKbps: Math.round(bitrateKbps),
maxBitrateKbps: Math.round(maxBitrateKbps),
};
}
// worked on this only to realize I should just use a logger package TODO
function logMessage(action, details = '') {
const timestamp = new Date().toISOString();
const formattedDetails = details
.trim()
.split('\n')
.map(line => `\t${line.trim()}`)
.join('\n');
console.log(`[${timestamp}] ${action}:${formattedDetails ? `\n${formattedDetails}` : ''}`);
}