Compare commits

..

No commits in common. "main" and "1.2.0" have entirely different histories.
main ... 1.2.0

10 changed files with 1340 additions and 2162 deletions

View file

@ -1,28 +0,0 @@
name: Upload release
on:
push:
tags:
- "*"
jobs:
build:
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: |
npm install --platform=win32 &&
apt-get update &&
apt-get install -y zip
- name: Build the app
run: npm run make -- --platform=win32
- name: Create release
uses: akkuman/gitea-release-action@v1
with:
token: ${{ secrets.TOKEN }}
files: out/make/zip/win32/x64/dsr-win32-x64-${{ github.ref_name }}.zip
draft: true

View file

@ -1,50 +1,8 @@
# Discord Video Sharing [![status-badge](https://git.mylloon.fr/Anri/dsr/badges/workflows/release.yml/badge.svg)](https://git.mylloon.fr/Anri/dsr/actions?workflow=release.yml)
# Discord Video Sharing
Tool for sharing video to Discord.
> This tool was primarily made for video captured by NVidia Shadowplay.
## Download/Install/Update
2 choices :
- Manually head to [the release page](https://git.mylloon.fr/Anri/dsr/releases/latest).
- Download it via PowerShell:
```powershell
irm https://git.mylloon.fr/Anri/dsr/raw/branch/main/install.ps1 | iex
```
## Available flags
You can add thoses flags in the `Target` field of your Windows shortcut.
| | |
| ------------- | ----------------------------------------------------- |
| `/nitro` | Increase the file limit to 500Mo |
| `/nitrobasic` | Increase the file limit to 50Mo |
| | |
| `/nvenc_h264` | Enable NVenc with H.264 encoder (NVidia GPU required) |
| `/nvenc_h265` | Enable NVenc with H.265 encoder (NVidia GPU required) |
| `/h265` | Enable the H.265 CPU encoder (slow compression) |
> NVenc support is experimental, but faster than CPU counterparts.
## More info
- [x] KISS interface
- [x] Support drag&drop into the icon
- [x] Keep the video under discord limitation
- [x] Defaults to H.264 CPU encoder
- [x] Try to keep the video under 25mb
- [x] If already under the limit, the file won't be compressed
- [x] NVenc support
- [x] Nitro suppport
- [x] Merge 2 audio files into one track when recorded with system audio and microphone
split up, while keeping the original ones (with conveniant metadata)
- [x] Works also with file with only one or more than 2 audio track, by doing
nothing
- [x] Support multiples files at once
- [x] Always optimize for video streaming
- [x] Merge all audio files into one track, while keeping the original ones
## Package the app for Windows

View file

@ -1,51 +0,0 @@
param (
[switch]$Force
)
# Enable TLSv1.2 for compatibility with older windows versions
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
$path = "$env:LOCALAPPDATA\DSR"
$update = Test-Path -Path $path\*
# Download
$releases = "https://git.mylloon.fr/api/v1/repos/Anri/dsr/releases/latest"
$link = (Invoke-WebRequest $releases | ConvertFrom-Json)[0].assets.browser_download_url
$archive = "$env:TEMP\dsr.zip"
Invoke-WebRequest -Uri $link -OutFile $archive
Remove-Item "$path" -Recurse -ErrorAction SilentlyContinue
# Close running DSR
Stop-Process -Name "DSR" -Force -ErrorAction SilentlyContinue
# Installation
Expand-Archive -Path $archive -DestinationPath "$path" -Force
Move-Item -Path "$path\dsr-win32-x64\*" -Destination "$path" -Force
Remove-Item "$path\dsr-win32-x64"
# Ask user to add a shortcut to the desktop
if (-not $update -Or $Force) {
# Add shortcut
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$env:APPDATA\Microsoft\Windows\Start Menu\Programs\DSR.lnk")
$Shortcut.TargetPath = "$path\dsr.exe"
$Shortcut.Save()
# Add new app to registry
REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\dsr" /f /v DisplayName /t REG_SZ /d "DSR"
REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\dsr" /f /v InstallLocation /t REG_SZ /d "$path"
if ($Host.UI.PromptForChoice(
"***********************",
"Add a desktop shortcut?",
@(
[System.Management.Automation.Host.ChoiceDescription]::new("&Yes", "Add a shortcut to your desktop.")
[System.Management.Automation.Host.ChoiceDescription]::new("&No", "Skip the shortcut creation.")
), 1) -eq 0) {
$WshShell = New-Object -comObject WScript.Shell
$Desktop = [Environment]::GetFolderPath("Desktop")
$Shortcut = $WshShell.CreateShortcut("$Desktop\DSR.lnk")
$Shortcut.TargetPath = "$path\dsr.exe"
$Shortcut.Save()
}
}

2890
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "dsr",
"version": "1.11.2",
"version": "1.2.0",
"description": "Discord Video Sharing",
"main": "./dist/main.js",
"scripts": {
@ -18,23 +18,20 @@
"author": "Mylloon",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@electron-forge/maker-zip": "^7.5",
"ffmpeg-static": "^5.2",
"ffprobe-static": "^3.1",
"typescript": "^5.6"
"@electron-forge/maker-zip": "^6.2.1",
"ffmpeg-static": "^5.1.0",
"ffprobe-static": "^3.1.0",
"typescript": "^5.1.6"
},
"devDependencies": {
"@electron-forge/cli": "^7.5",
"@types/ffprobe-static": "^2.0",
"electron": "^33.0"
"@electron-forge/cli": "^6.2.1",
"@types/ffprobe-static": "^2.0.1",
"electron": "^25.3.2"
},
"config": {
"forge": {
"packagerConfig": {
"icon": "./image/icon.ico",
"asar": {
"unpack": "**/node_modules/*-static/**"
}
"icon": "./image/icon.ico"
},
"makers": [
{

View file

@ -1,40 +1,19 @@
import { app, BrowserWindow, dialog, ipcMain, Notification } from "electron";
import { statSync, copyFileSync } from "fs";
import { BrowserWindow, app, dialog, ipcMain } from "electron";
import { statSync, unlink } from "fs";
import {
deleteFile,
deleteTwoPassFiles,
execute,
getNewFilename,
getVideoDuration,
getNumberOfAudioTracks,
printAndDevTool,
processes,
} from "./utils/misc";
import path = require("path");
import ffmpeg = require("ffmpeg-static");
const ffmpegPath = `${ffmpeg}`.replace("app.asar", "app.asar.unpacked");
let error = false;
import ffmpegPath = require("ffmpeg-static");
const moviesFilter = {
name: "Videos",
extensions: ["mp4", "mkv"],
};
const metadataAudioSize = 3;
const metadataAudio = `-metadata:s:a:0 title="System sounds and microphone" \
-metadata:s:a:1 title="System sounds" \
-metadata:s:a:2 title="Microphone"`;
const shareOpt = "-movflags +faststart";
/** Register a new error */
const registerError = (win: BrowserWindow, err: string) => {
error = true;
printAndDevTool(win, err);
};
/** Create a new window */
const createWindow = () => {
const win = new BrowserWindow({
@ -52,193 +31,72 @@ const createWindow = () => {
return win;
};
// For notification on Windows
if (process.platform === "win32") {
app.setAppUserModelId(app.name);
}
/* Ready to create the window */
app.whenReady().then(() => {
const win = createWindow();
/** Ask user files */
const askFiles = () => {
/** Ask user a file */
const askFile = () => {
return dialog.showOpenDialogSync(win, {
filters: [moviesFilter],
properties: ["openFile", "dontAddToRecent", "multiSelections"],
properties: ["openFile", "dontAddToRecent"],
});
};
/** Send confirmation to user */
const confirmation = async (message: string) => {
// Send notification
new Notification({
title: "Status",
body: message,
}).show();
// Open dialog
await dialog.showMessageBox(win, { message });
};
/** Get filename of a path */
const getFilename = (filepath: string) => path.parse(filepath).base;
/** Merge all audios track of a video into one
* In case video doesn't have exactly two audio streams, silently pass */
/** Merge all audios track of a video into one */
const mergeAudio = async (file: string) => {
const tmpFile = getNewFilename(file, "TMP_");
let outFile;
const outFile = getNewFilename(file, "(merged audio) ");
let audioTracks = getNumberOfAudioTracks(file);
// Merge 2 audio
await execute(
`"${ffmpegPath}" -y -i "${file}" -filter_complex "[0:a]amerge=inputs=2[a]" -ac 1 -map 0:v -map "[a]" -c:v copy "${tmpFile}"`
).catch((e) => printAndDevTool(win, e));
switch (audioTracks.length) {
case 2:
// Merge 2 audio
// See: https://trac.ffmpeg.org/wiki/AudioChannelManipulation#a2stereostereo
await execute(
`"${ffmpegPath}" -y \
-i "${file}" \
-filter_complex "[0:a]amerge=inputs=2[a]" -ac 2 -map 0:v -map "[a]" \
-c:v copy \
"${tmpFile}"`
);
// Add merged audio as first position to original video
await execute(
`"${ffmpegPath}" -y -i "${tmpFile}" -i "${file}" -map 0 -map 1:a -c:v copy "${outFile}"`
).catch((e) => printAndDevTool(win, e));
outFile = getNewFilename(file, "(merged audio) ");
// Add merged audio as first position to original video and make it default
// About disposition: https://ffmpeg.org/ffmpeg.html#Main-options
// Also rename all tracks accordingly to what they are
await execute(
`"${ffmpegPath}" -y \
-i "${tmpFile}" -i "${file}" \
-map 0 -map 1:a -c:v copy \
-disposition:a 0 -disposition:a:0 default \
${metadataAudio} \
"${outFile}"`
).catch((e) => registerError(win, e));
// Delete the temporary video file
deleteFile(tmpFile);
audioTracks = getNumberOfAudioTracks(outFile);
break;
default:
// Other cases: no merge needed
outFile = getNewFilename(file, "(nomerge) ");
// Do a copy
copyFileSync(file, outFile);
break;
}
// Delete the temporary file
unlink(tmpFile, (err) => {
if (err) {
throw err;
}
});
const duration = getVideoDuration(outFile);
const stats = statSync(outFile);
return {
title: outFile,
size: stats.size / 1024 / 1024,
duration,
audioTracks,
};
return { title: outFile, size: stats.size / 1024 / 1024, duration };
};
/** Reduce size of a file
* Returns an empty string in case of failing
*/
const reduceSize = async (
file: string,
bitrate: number,
audioTracks: number[]
) => {
const audioBitrate = Math.ceil(
audioTracks.reduce((sum, current) => current + sum, 50) // initial value > 0 for extra room
);
/* Reduce size of a file */
const reduceSize = async (file: string, bitrate: number) => {
const audioBitrate = 400; // keep some room
const videoBitrate = bitrate - audioBitrate;
let finalFile;
if (videoBitrate > 0) {
finalFile = getNewFilename(file, "Compressed - ");
const finalFile = getNewFilename(file, "Compressed - ");
// Trash the output, depends on the platform
const nul = process.platform === "win32" ? "NUL" : "/dev/null";
// Trash the output, depends on the platform
const nul = process.platform === "win32" ? "NUL" : "/dev/null";
// Mapping of tracks for FFMPEG, adding 1 for the video stream
const mappingTracks = Array(audioTracks.length + 1)
.fill("-map 0:")
.map((str, index) => {
return str + index;
})
.join(" ");
let codec = "libx264";
let hwAcc = "";
const argv = process.argv;
if (argv.includes("/nvenc_h264")) {
// Use NVenc H.264
codec = "h264_nvenc";
hwAcc = "-hwaccel cuda";
}
if (argv.includes("/nvenc_h265")) {
// Use NVenc H.265
codec = "hevc_nvenc";
hwAcc = "-hwaccel cuda";
}
if (argv.includes("/h265")) {
// Use H.265 encoder
codec = "libx265";
}
// Compress the video
// Add metadata to audio's track
await execute(
`"${ffmpegPath}" -y ${hwAcc} \
-i "${file}" \
-c:v ${codec} -b:v ${videoBitrate}k -pass 1 -an -f mp4 \
${nul} \
&& \
"${ffmpegPath}" -y ${hwAcc} \
-i "${file}" \
-c:v ${codec} -b:v ${videoBitrate}k -pass 2 -c:a copy \
${mappingTracks} -f mp4 \
-profile:v main \
${audioTracks.length === metadataAudioSize ? metadataAudio : ""} \
${shareOpt} \
"${finalFile}"`
).catch((e) => registerError(win, e));
// Delete the 2 pass temporary files
deleteTwoPassFiles(process.cwd());
} else {
finalFile = "";
}
// Delete the old video file
deleteFile(file);
return finalFile;
};
/** Move metadata at the begenning of the file */
const moveMetadata = async (file: string, nbTracks: number) => {
const finalFile = getNewFilename(file, "Broadcastable - ");
// Optimize for streaming
await execute(
`"${ffmpegPath}" -y \
-i "${file}" \
-map 0 -codec copy \
${shareOpt} \
${nbTracks === metadataAudioSize ? metadataAudio : ""} \
"${finalFile}"`
).catch((e) => registerError(win, e));
`"${ffmpegPath}" -y -i "${file}" -c:v libx264 -b:v ${videoBitrate}k -pass 1 -an -f mp4 ${nul} && \
"${ffmpegPath}" -y -i "${file}" -c:v libx264 -b:v ${videoBitrate}k -pass 2 -c:a copy -map 0:0 -map 0:1 -map 0:2 -map 0:3 -f mp4 "${finalFile}"`
).catch((e) => printAndDevTool(win, e));
// Delete the old video file
deleteFile(file);
// Delete the old file
unlink(file, (err) => {
if (err) {
throw err;
}
});
return finalFile;
};
@ -246,25 +104,11 @@ app.whenReady().then(() => {
/* Context bridge */
ipcMain.handle("argv", () => process.argv);
ipcMain.handle("allowedExtensions", () => moviesFilter);
ipcMain.handle("getFilename", (_, filepath: string) => getFilename(filepath));
ipcMain.handle("askFiles", () => askFiles());
ipcMain.handle("askFile", () => askFile());
ipcMain.handle("mergeAudio", (_, file: string) => mergeAudio(file));
ipcMain.handle(
"reduceSize",
(_, file: string, bitrate: number, audioTracks: number[]) =>
reduceSize(file, bitrate, audioTracks)
ipcMain.handle("reduceSize", (_, file: string, bitrate: number) =>
reduceSize(file, bitrate)
);
ipcMain.handle("moveMetadata", (_, file: string, nbTracks: number) =>
moveMetadata(file, nbTracks)
);
ipcMain.handle("exit", () => (error ? {} : app.quit()));
ipcMain.handle("exit", () => app.quit());
ipcMain.handle("confirmation", (_, text: string) => confirmation(text));
});
app.on("window-all-closed", () => {
processes.forEach((process) => {
process.stdin.write("q");
});
app.quit();
});

View file

@ -1,22 +1,13 @@
import { contextBridge, ipcRenderer } from "electron";
/* Log errors */
ipcRenderer.on("error", (_, err) => {
console.error(err);
});
/* Context bridge */
contextBridge.exposeInMainWorld("internals", {
argv: () => ipcRenderer.invoke("argv"),
allowedExtensions: () => ipcRenderer.invoke("allowedExtensions"),
getFilename: (filepath: string) =>
ipcRenderer.invoke("getFilename", filepath),
askFiles: () => ipcRenderer.invoke("askFiles"),
askFile: () => ipcRenderer.invoke("askFile"),
mergeAudio: (file: string) => ipcRenderer.invoke("mergeAudio", file),
reduceSize: (file: string, bitrate: number, audioTracks: number[]) =>
ipcRenderer.invoke("reduceSize", file, bitrate, audioTracks),
moveMetadata: (file: string, nbTracks: number) =>
ipcRenderer.invoke("moveMetadata", file, nbTracks),
reduceSize: (file: string, bitrate: number) =>
ipcRenderer.invoke("reduceSize", file, bitrate),
exit: () => ipcRenderer.invoke("exit"),
confirmation: (text: string) => ipcRenderer.invoke("confirmation", text),
});

View file

@ -4,68 +4,31 @@ let internals: {
allowedExtensions: () => Promise<{
extensions: string[];
}>;
getFilename: (filepath: string) => Promise<string>;
askFiles: () => Promise<string[] | undefined>;
askFile: () => Promise<string[] | undefined>;
exit: () => Promise<void>;
mergeAudio: (filename: string) => Promise<{
title: string;
duration: number;
size: number;
audioTracks: number[];
}>;
reduceSize: (
file: string,
bitrate: number,
audioTracks: number[]
) => Promise<string>;
moveMetadata: (file: string, nbTracks: number) => Promise<string>;
mergeAudio: (
filename: string
) => Promise<{ title: string; duration: number; size: number }>;
reduceSize: (file: string, bitrate: number) => Promise<string>;
confirmation: (text: string) => Promise<void>;
};
/** Search for files */
const getFiles = async () => {
/** Search for a file */
const getFile = async () => {
const allowedExtensions = (await internals.allowedExtensions()).extensions;
const argvFiles = (await internals.argv())
.slice(1)
.filter((element) => !element.startsWith("/"));
if (argvFiles.length > 0) {
const files = argvFiles;
// Exit if a file isn't supported in the list
if (
files.filter((file) =>
allowedExtensions.some((ext) =>
file.toLowerCase().endsWith(ext.toLowerCase())
)
).length !== files.length
) {
await internals.exit();
const argv = await internals.argv();
if (argv.length === 2) {
const file = argv.pop();
if (allowedExtensions.some((ext) => file.endsWith(ext))) {
return file;
}
return files;
}
const files = await internals.askFiles();
if (files === undefined || files.length === 0) {
const file = await internals.askFile();
if (file === undefined || file.length === 0) {
await internals.exit();
}
return files;
};
/** Returns maximum allowed size for files in MB */
const fetchMaxSize = async () => {
const argv = await internals.argv();
if (argv.includes("/nitrobasic")) {
// Nitro Basic user
return 50;
} else if (argv.includes("/nitro")) {
// Nitro user
return 500;
} else {
// Free user
return 10;
}
return file.join("");
};
/** Either replace the message, or add some info */
@ -99,77 +62,28 @@ const updateMessage = (
/** Main function */
const main = async () => {
const maxSizeDiscord = await fetchMaxSize();
updateMessage("Récupération des fichiers...");
const files = await getFiles();
let processedFiles = "";
let numberOfUncompressableFiles = 0;
const maxSizeDiscord = 25;
updateMessage("Récupération du fichier...");
const file = await getFile();
updateMessage("Mélange des pistes audios vers la piste 1...", true);
const newFile = await internals.mergeAudio(file);
let finalTitle = newFile.title;
updateMessage(`Taille calculée : ~${Math.round(newFile.size)}Mio`);
if (newFile.size > maxSizeDiscord) {
const targetSize = maxSizeDiscord - 2; // keep some room
// https://trac.ffmpeg.org/wiki/Encode/H.264#twopass
const bitrate = Math.floor((targetSize * 8388.608) / newFile.duration);
// Iterate over all the retrieved files
for (const [idx, file] of files.entries()) {
const counter = `${idx + 1}/${files.length}`;
const filename = await internals.getFilename(file);
updateMessage(
`${counter} - Mélange des pistes audios de ${filename}...`,
true
`\nFichier trop lourd, compression en cours... (bitrate total = ${bitrate}kbps)`,
true,
Mode.Append
);
const newFile = await internals.mergeAudio(file);
let finalTitle = newFile.title;
updateMessage(
`${counter} - Taille calculée : ~${Math.round(newFile.size)}Mio`
);
// Compress video if needed
if (newFile.size > maxSizeDiscord) {
const targetSize = maxSizeDiscord - 2; // keep some room
// https://trac.ffmpeg.org/wiki/Encode/H.264#twopass
const bitrate = Math.floor((targetSize * 8388.608) / newFile.duration);
updateMessage(
`\nFichier trop lourd, compression en cours... (bitrate total = ${bitrate}kbps)`,
true,
Mode.Append
);
// Compress the video and change the title to the new one
finalTitle = await internals.reduceSize(
newFile.title,
bitrate,
newFile.audioTracks
);
} else {
updateMessage(`\nPréparation pour le partage...`, true, Mode.Append);
// Move the metadata to make it playable before everything is downloaded
finalTitle = await internals.moveMetadata(
newFile.title,
newFile.audioTracks.length
);
}
// Append title to the list of processed files
if (finalTitle.length > 0) {
processedFiles += `\n- ${finalTitle}`;
updateMessage(`Fichier ${counter} traités.`);
} else {
processedFiles += `\n- ${file} [incompressable]`;
updateMessage(`Fichier ${counter} trop large pour être compressé.`);
numberOfUncompressableFiles++;
}
finalTitle = await internals.reduceSize(newFile.title, bitrate);
}
let errorMessage = "";
if (numberOfUncompressableFiles > 0) {
errorMessage += `\nNombre de fichier incompressable : ${numberOfUncompressableFiles}.`;
}
// Send confirmation to the user that we're done
await internals.confirmation(
`${files.length} fichiers traités : ${processedFiles}` + errorMessage
);
updateMessage("Fichier prêt ! :)");
await internals.confirmation(`File ok @ ${finalTitle}!`);
await internals.exit();
};
main();

View file

@ -1,12 +1,7 @@
import ffprobe = require("ffprobe-static");
import child_process = require("child_process");
import path = require("path");
import { BrowserWindow } from "electron";
import { existsSync, unlink } from "fs";
import ffprobe = require("ffprobe-static");
const ffprobePath = ffprobe.path.replace("app.asar", "app.asar.unpacked");
export const processes: child_process.ChildProcess[] = [];
/** Create a new filename from the OG one */
export const getNewFilename = (ogFile: string, part: string) => {
@ -16,65 +11,26 @@ export const getNewFilename = (ogFile: string, part: string) => {
/** Return the duration of a video in second */
export const getVideoDuration = (file: string) => {
const command = `"${ffprobePath}" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${file}"`;
const command = `"${ffprobe.path}" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${file}"`;
const durationString = child_process.execSync(command).toString().trim();
return parseFloat(durationString);
};
/** Return the number of audio tracks */
export const getNumberOfAudioTracks = (file: string): number[] => {
const command = `"${ffprobePath}" -v error -show_entries stream=bit_rate -select_streams a -of json "${file}"`;
const result = child_process.execSync(command, { encoding: "utf8" });
return JSON.parse(result).streams.map(
(v: { bit_rate: string }) => Number(v.bit_rate) / 1000
);
};
/** Print an error to the console and open the dev tool panel */
export const printAndDevTool = (win: BrowserWindow, err: string) => {
export const printAndDevTool = (win: BrowserWindow, error: string) => {
console.error(error);
win.webContents.openDevTools();
win.webContents.send("error", err);
};
/** Run a command asynchronously */
export const execute = (
command: string
): Promise<{ stdout: string; stderr: string }> => {
export const execute = (command: string) => {
return new Promise((resolve, reject) => {
const process = child_process.exec(command, (error, stdout, stderr) => {
child_process.exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve({ stdout, stderr });
}
});
processes.push(process);
process.on("exit", () => {
processes.splice(processes.indexOf(process), 1);
});
});
};
/** Delete a file */
export const deleteFile = (file: string) => {
unlink(file, (err) => {
if (err) {
throw err;
}
});
};
/** Delete the 2pass files generated by ffmpeg */
export const deleteTwoPassFiles = (directory: string) => {
const logFile = path.join(directory, "ffmpeg2pass-0.log");
if (existsSync(logFile)) {
deleteFile(logFile);
}
const mbtreeFile = path.join(directory, "ffmpeg2pass-0.log.mbtree");
if (existsSync(mbtreeFile)) {
deleteFile(mbtreeFile);
}
};

View file

@ -1,7 +1,6 @@
{
"compilerOptions": {
"module": "commonjs",
"downlevelIteration": true,
"noImplicitAny": true,
"sourceMap": true,
"outDir": "dist",