Compare commits

...

117 commits
1.2.0 ... main

Author SHA1 Message Date
f590f77bca
bump version to 1.11.2
All checks were successful
Upload release / build (push) Successful in 1m45s
2024-10-16 01:08:36 +02:00
ecb03ded2a
add extra room 2024-10-16 01:08:17 +02:00
21b39e80bf
update dependencies 2024-10-16 01:01:59 +02:00
55b94d0021
bump version to 1.11.1
All checks were successful
Upload release / build (push) Successful in 1m54s
2024-10-01 16:55:12 +02:00
4f34191d2f
don't crash when trying to compress an enormous file 2024-10-01 16:55:06 +02:00
7c4bd84486
bump version to 1.11.0
All checks were successful
Upload release / build (push) Successful in 1m46s
2024-09-19 01:32:06 +02:00
e34712976b
magic value into const 2024-09-19 01:32:00 +02:00
dc190ab807
fix audio metadata 2024-09-19 01:29:17 +02:00
21050bb0b7
rework readme flag part and change some flags name 2024-09-19 01:19:00 +02:00
482caad25f
Add NVENC2 2024-09-19 01:12:04 +02:00
5841006f15
add H265 (slow asf) 2024-09-19 01:04:32 +02:00
ee64d06e0a
fix audio track issue 2024-09-19 00:52:24 +02:00
2ef8bda147
Revert "fix packager"
This reverts commit c8538f5d03.
2024-09-18 23:45:32 +02:00
b6d6b84839
bump version to 1.10.2
All checks were successful
Upload release / build (push) Successful in 1m22s
2024-09-18 19:02:46 +02:00
f2b04f0cea
Revert "no need that much room now that we have exact audio bitrate"
we need

This reverts commit b391e05ed3.
2024-09-18 19:02:16 +02:00
c22a9c295d
bump version to 1.10.1
All checks were successful
Upload release / build (push) Successful in 1m22s
2024-09-18 01:24:07 +02:00
b391e05ed3
no need that much room now that we have exact audio bitrate
Some checks failed
Upload release / build (push) Has been cancelled
2024-09-18 01:20:22 +02:00
a74bb33967
compute audio tracks final bitrate 2024-09-18 01:10:28 +02:00
8d34199ae0
clickable badge 2024-09-17 23:55:57 +02:00
b894fd0856
bump version to 1.10.0
All checks were successful
Upload release / build (push) Successful in 1m28s
2024-09-17 23:54:08 +02:00
39d84c9b57
update dependencies 2024-09-17 23:53:56 +02:00
981f95c40d
Merge pull request 'reduce free plan' (#22) from discord-changes into main
Reviewed-on: #22
2024-09-17 23:50:00 +02:00
c8538f5d03
fix packager 2024-09-10 17:44:55 +02:00
2c2f469cc5
update dependencies 2024-09-10 17:40:26 +02:00
7973a02603
Merge pull request 'fix: close ffmpeg by send the quit command in stdin' (#23) from force-close-ffmpeg into main
Reviewed-on: #23
2024-09-10 17:31:58 +02:00
a6fe54fd9c
close ffmpeg by send the quit command in stdin 2024-09-10 17:30:52 +02:00
20052ed7d6
update readme 2024-09-06 10:08:05 +02:00
4223ede10a
reduce free plan 2024-09-06 10:02:22 +02:00
877021ee0d
typos 2024-09-06 10:02:01 +02:00
fce9bce308
add nitro basic 2024-09-06 10:01:02 +02:00
0ed6407315
bump version to 1.9.3
All checks were successful
Upload release / build (push) Successful in 1m39s
2024-09-02 14:27:55 +02:00
af921925af
asar packaging (#21) 2024-09-02 14:27:37 +02:00
cb9de1b856
make the release a draft 2024-09-02 13:24:00 +02:00
1d1c0f78bc
bump version to 1.9.2
All checks were successful
Upload release / build (push) Successful in 1m29s
2024-09-02 13:18:40 +02:00
6fffd19278
add more room for audio bitrate 2024-09-02 13:15:36 +02:00
bfa1f94a43
bump version to 1.9.1
All checks were successful
Upload release / build (push) Successful in 1m51s
2024-09-01 02:28:05 +02:00
ebbca9b6aa
update some dependencies 2024-09-01 02:27:55 +02:00
fc7782a982
Fix Windows notification title 2024-09-01 02:25:14 +02:00
440fcf2334
Share -> Broadcast 2024-09-01 02:14:59 +02:00
d93b0d148b
bump version to 1.9.0
All checks were successful
Upload release / build (push) Successful in 1m23s
2024-08-22 17:47:57 +02:00
0399080d6e
if no compression is needed, optimize for streaming 2024-08-22 17:47:21 +02:00
d4bb073218
update dependencies 2024-08-22 17:39:53 +02:00
b35635daf0
bump version to 1.8.9
All checks were successful
Upload release / build (push) Successful in 1m34s
2024-08-21 19:41:54 +02:00
cdf2e678c3
do a simple copy instead of relying on ffmpeg + add 1 for the video stream when doing the compression 2024-08-21 19:40:16 +02:00
2fe6f6aece
correctly copy all the streams 2024-08-21 19:31:26 +02:00
d9c21876e8
Silently continue when DSR is already closed 2024-08-20 21:00:37 +02:00
0047664616
add badge 2024-08-20 20:59:04 +02:00
d6880ab85c
bump version to 1.8.8
All checks were successful
Upload release / build (push) Successful in 1m10s
2024-08-20 20:53:42 +02:00
0b85415c1d
add automatic build (#7) 2024-08-20 20:52:52 +02:00
04b4138b46
directly get info about number of audio tracks, cleaning up the horrible code in the audio merger and don't try to merge audio streams when there is 2+ 2024-08-20 20:14:38 +02:00
8fb8f24625
force close dsr before updating (#18) 2024-07-11 14:33:56 +02:00
80dca39b8c
bump version to 1.8.7 2024-07-11 13:55:37 +02:00
de983c8802
fix crash when no audio stream 2024-07-11 13:55:29 +02:00
a202996c11
audit fix 2024-07-11 13:55:06 +02:00
65339d4592
bump version to 1.8.6 2024-05-17 22:04:17 +02:00
e0076c7705
fix nvenc reducing more the video bitrate 2024-05-17 22:03:48 +02:00
ede370763f
bump version to 1.8.5 2024-05-17 21:58:25 +02:00
4890ee40a2
fix nvenc 2024-05-17 21:57:52 +02:00
f93673ce68
bump version to 1.8.4 2024-05-17 21:51:09 +02:00
ed6f0a2b49
function 2024-05-17 21:24:27 +02:00
eb84c48b3c
Merge pull request 'kill all subprocesses on closing' (#6) from fix-4 into main
Reviewed-on: #6
2024-05-17 21:24:03 +02:00
ba533ea3b6
typo 2024-05-17 21:23:28 +02:00
e942e807d6
add terminate dep 2024-05-17 21:23:15 +02:00
20bf0c1d67
correctly close the process 2024-05-17 21:22:56 +02:00
dd62f81e35
wip: kill all subprocesses on closing (not working) 2024-05-17 20:10:14 +02:00
05de7dc801
update dependencies 2024-05-17 20:09:51 +02:00
f9d812f9b2
automatic update 2024-05-17 19:47:34 +02:00
e108ae3097
update example 2024-05-17 19:40:27 +02:00
ca9fe8ed36
less work when update 2024-05-17 19:36:08 +02:00
4275cb5528
Add update switch 2024-05-17 19:25:09 +02:00
dfb049f1fb
Add notification (#15) 2024-05-17 19:20:49 +02:00
b577987efd
bump version to 1.8.3 2024-05-12 17:41:02 +02:00
85cabf536c
fix: drag'n'drop ignore file extension case 2024-05-12 17:40:51 +02:00
6c0f8e70d8
bump version to 1.8.2 2024-04-04 12:34:08 +02:00
d4e4bd9ec3
formatting 2024-04-04 12:33:50 +02:00
740b258ce1
fix two pass files location 2024-04-04 12:33:48 +02:00
a3f4c077ef
bump version to 1.8.1 2024-04-04 12:06:14 +02:00
274e67ff45
don't close the app when an error has been raised 2024-04-04 12:05:33 +02:00
3e57b75145
better description 2024-04-04 11:54:54 +02:00
9ce7aeeae6
update dependencies 2024-04-04 11:47:08 +02:00
3be79cfc0f
fix one drive desktop? (#11) 2024-04-04 11:41:02 +02:00
5f8eaf36fb
ask user to create a desktop shortcut 2024-04-01 15:27:12 +02:00
067ca081b7
use installation script, less scary 2024-04-01 15:15:02 +02:00
5a5fe09a93
bump version to 1.8.0 2024-01-16 20:18:58 +01:00
ab170b0cda
fix for copy command, again 2024-01-16 20:05:14 +01:00
d509d31a1b
fix copy command 2024-01-16 19:55:26 +01:00
2c19f71614
update readme 2024-01-16 19:46:21 +01:00
e2df3da0a8
optimization on video streaming 2024-01-13 02:01:42 +01:00
22d8c76bfa
bump version to 1.7.0 2023-12-02 23:56:42 +01:00
9751a5ee59
nvenc support 2023-12-02 23:56:32 +01:00
40654c0581
update dependencies 2023-12-02 23:56:06 +01:00
e244e78b2f
bump version to 1.6.0 2023-11-19 22:27:30 +01:00
1a41e1bd72
Fix compression for one-audio track files 2023-11-19 22:01:18 +01:00
f27f8b01aa
Support for files with only one audio track 2023-11-19 21:43:35 +01:00
99e68b4db1
simplify and ignore error on reinstallation 2023-11-11 17:25:29 +01:00
b363d47200
typo 2023-11-11 14:56:25 +01:00
6c7d2e984c
bump version to 1.5.1 2023-11-11 14:50:01 +01:00
fa7717e2fd
update dependencies 2023-11-11 14:49:37 +01:00
853af9c8f3
bump version to 1.5.0 2023-11-11 14:40:03 +01:00
6e23fb64df
Add script snippet to download/install DSR 2023-11-11 14:39:49 +01:00
61defcc7b0
add nitro flag 2023-11-11 14:03:53 +01:00
df63747376
bump version to 1.4.0 2023-08-24 16:13:38 +02:00
36291047a0
update dependencies 2023-08-24 16:12:52 +02:00
0347eab727
add info to the readme 2023-08-24 16:07:55 +02:00
33a86cecbd
support multiple files at once (#3) 2023-08-24 15:59:46 +02:00
53d19bdb74
format 2023-08-24 15:56:19 +02:00
e6d2376fea
comments 2023-08-24 03:29:46 +02:00
1c42ea43c5
add metadata to compressed video 2023-08-23 23:14:03 +02:00
78ad17e005
give title to audio tracks (#5) 2023-08-23 22:24:31 +02:00
f41a6c8c35
split ffmpeg commands to multiples lines 2023-08-23 21:30:20 +02:00
ef356ef58f
bump version to 1.3.0 2023-08-04 21:02:21 +02:00
d42b8a0345
output stereo sound 2023-08-04 20:53:21 +02:00
01b4cdcc03
fix default audio track 2023-08-04 20:17:16 +02:00
542136dc46
fix logging 2023-08-04 20:00:31 +02:00
3875d3cefe
add return type 2023-08-04 19:32:45 +02:00
823618535f
bump version to 1.2.1 2023-08-01 15:57:08 +02:00
7eafb0b27c
delete twopass files created by ffmpeg if needed 2023-08-01 15:57:01 +02:00
10 changed files with 2163 additions and 1341 deletions

View file

@ -0,0 +1,28 @@
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,8 +1,50 @@
# Discord Video Sharing # 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)
- [x] Try to keep the video under 25mb 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] If already under the limit, the file won't be compressed - [x] If already under the limit, the file won't be compressed
- [x] Merge all audio files into one track, while keeping the original ones - [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
## Package the app for Windows ## Package the app for Windows

51
install.ps1 Normal file
View file

@ -0,0 +1,51 @@
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()
}
}

2892
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

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

View file

@ -1,19 +1,40 @@
import { BrowserWindow, app, dialog, ipcMain } from "electron"; import { app, BrowserWindow, dialog, ipcMain, Notification } from "electron";
import { statSync, unlink } from "fs"; import { statSync, copyFileSync } from "fs";
import { import {
deleteFile,
deleteTwoPassFiles,
execute, execute,
getNewFilename, getNewFilename,
getVideoDuration, getVideoDuration,
getNumberOfAudioTracks,
printAndDevTool, printAndDevTool,
processes,
} from "./utils/misc"; } from "./utils/misc";
import path = require("path"); import path = require("path");
import ffmpegPath = require("ffmpeg-static");
import ffmpeg = require("ffmpeg-static");
const ffmpegPath = `${ffmpeg}`.replace("app.asar", "app.asar.unpacked");
let error = false;
const moviesFilter = { const moviesFilter = {
name: "Videos", name: "Videos",
extensions: ["mp4", "mkv"], 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 */ /** Create a new window */
const createWindow = () => { const createWindow = () => {
const win = new BrowserWindow({ const win = new BrowserWindow({
@ -31,72 +52,193 @@ const createWindow = () => {
return win; return win;
}; };
// For notification on Windows
if (process.platform === "win32") {
app.setAppUserModelId(app.name);
}
/* Ready to create the window */ /* Ready to create the window */
app.whenReady().then(() => { app.whenReady().then(() => {
const win = createWindow(); const win = createWindow();
/** Ask user a file */ /** Ask user files */
const askFile = () => { const askFiles = () => {
return dialog.showOpenDialogSync(win, { return dialog.showOpenDialogSync(win, {
filters: [moviesFilter], filters: [moviesFilter],
properties: ["openFile", "dontAddToRecent"], properties: ["openFile", "dontAddToRecent", "multiSelections"],
}); });
}; };
/** Send confirmation to user */ /** Send confirmation to user */
const confirmation = async (message: string) => { const confirmation = async (message: string) => {
// Send notification
new Notification({
title: "Status",
body: message,
}).show();
// Open dialog
await dialog.showMessageBox(win, { message }); await dialog.showMessageBox(win, { message });
}; };
/** Merge all audios track of a video into one */ /** 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 */
const mergeAudio = async (file: string) => { const mergeAudio = async (file: string) => {
const tmpFile = getNewFilename(file, "TMP_"); const tmpFile = getNewFilename(file, "TMP_");
const outFile = getNewFilename(file, "(merged audio) "); let outFile;
let audioTracks = getNumberOfAudioTracks(file);
switch (audioTracks.length) {
case 2:
// Merge 2 audio // Merge 2 audio
// See: https://trac.ffmpeg.org/wiki/AudioChannelManipulation#a2stereostereo
await execute( 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}"` `"${ffmpegPath}" -y \
).catch((e) => printAndDevTool(win, e)); -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 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( await execute(
`"${ffmpegPath}" -y -i "${tmpFile}" -i "${file}" -map 0 -map 1:a -c:v copy "${outFile}"` `"${ffmpegPath}" -y \
).catch((e) => printAndDevTool(win, e)); -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 file // Delete the temporary video file
unlink(tmpFile, (err) => { deleteFile(tmpFile);
if (err) {
throw err; audioTracks = getNumberOfAudioTracks(outFile);
break;
default:
// Other cases: no merge needed
outFile = getNewFilename(file, "(nomerge) ");
// Do a copy
copyFileSync(file, outFile);
break;
} }
});
const duration = getVideoDuration(outFile); const duration = getVideoDuration(outFile);
const stats = statSync(outFile); const stats = statSync(outFile);
return { title: outFile, size: stats.size / 1024 / 1024, duration }; return {
title: outFile,
size: stats.size / 1024 / 1024,
duration,
audioTracks,
};
}; };
/* Reduce size of a file */ /** Reduce size of a file
const reduceSize = async (file: string, bitrate: number) => { * Returns an empty string in case of failing
const audioBitrate = 400; // keep some room */
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
);
const videoBitrate = bitrate - audioBitrate; const videoBitrate = bitrate - audioBitrate;
let finalFile;
const finalFile = getNewFilename(file, "Compressed - "); if (videoBitrate > 0) {
finalFile = getNewFilename(file, "Compressed - ");
// Trash the output, depends on the platform // Trash the output, depends on the platform
const nul = process.platform === "win32" ? "NUL" : "/dev/null"; const nul = process.platform === "win32" ? "NUL" : "/dev/null";
await execute( // Mapping of tracks for FFMPEG, adding 1 for the video stream
`"${ffmpegPath}" -y -i "${file}" -c:v libx264 -b:v ${videoBitrate}k -pass 1 -an -f mp4 ${nul} && \ const mappingTracks = Array(audioTracks.length + 1)
"${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}"` .fill("-map 0:")
).catch((e) => printAndDevTool(win, e)); .map((str, index) => {
return str + index;
})
.join(" ");
// Delete the old file let codec = "libx264";
unlink(file, (err) => { let hwAcc = "";
if (err) {
throw err; 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));
// Delete the old video file
deleteFile(file);
return finalFile; return finalFile;
}; };
@ -104,11 +246,25 @@ app.whenReady().then(() => {
/* Context bridge */ /* Context bridge */
ipcMain.handle("argv", () => process.argv); ipcMain.handle("argv", () => process.argv);
ipcMain.handle("allowedExtensions", () => moviesFilter); ipcMain.handle("allowedExtensions", () => moviesFilter);
ipcMain.handle("askFile", () => askFile()); ipcMain.handle("getFilename", (_, filepath: string) => getFilename(filepath));
ipcMain.handle("askFiles", () => askFiles());
ipcMain.handle("mergeAudio", (_, file: string) => mergeAudio(file)); ipcMain.handle("mergeAudio", (_, file: string) => mergeAudio(file));
ipcMain.handle("reduceSize", (_, file: string, bitrate: number) => ipcMain.handle(
reduceSize(file, bitrate) "reduceSize",
(_, file: string, bitrate: number, audioTracks: number[]) =>
reduceSize(file, bitrate, audioTracks)
); );
ipcMain.handle("exit", () => app.quit()); ipcMain.handle("moveMetadata", (_, file: string, nbTracks: number) =>
moveMetadata(file, nbTracks)
);
ipcMain.handle("exit", () => (error ? {} : app.quit()));
ipcMain.handle("confirmation", (_, text: string) => confirmation(text)); ipcMain.handle("confirmation", (_, text: string) => confirmation(text));
}); });
app.on("window-all-closed", () => {
processes.forEach((process) => {
process.stdin.write("q");
});
app.quit();
});

View file

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

View file

@ -4,31 +4,68 @@ let internals: {
allowedExtensions: () => Promise<{ allowedExtensions: () => Promise<{
extensions: string[]; extensions: string[];
}>; }>;
askFile: () => Promise<string[] | undefined>; getFilename: (filepath: string) => Promise<string>;
askFiles: () => Promise<string[] | undefined>;
exit: () => Promise<void>; exit: () => Promise<void>;
mergeAudio: ( mergeAudio: (filename: string) => Promise<{
filename: string title: string;
) => Promise<{ title: string; duration: number; size: number }>; duration: number;
reduceSize: (file: string, bitrate: number) => Promise<string>; size: number;
audioTracks: number[];
}>;
reduceSize: (
file: string,
bitrate: number,
audioTracks: number[]
) => Promise<string>;
moveMetadata: (file: string, nbTracks: number) => Promise<string>;
confirmation: (text: string) => Promise<void>; confirmation: (text: string) => Promise<void>;
}; };
/** Search for a file */ /** Search for files */
const getFile = async () => { const getFiles = async () => {
const allowedExtensions = (await internals.allowedExtensions()).extensions; const allowedExtensions = (await internals.allowedExtensions()).extensions;
const argv = await internals.argv(); const argvFiles = (await internals.argv())
if (argv.length === 2) { .slice(1)
const file = argv.pop(); .filter((element) => !element.startsWith("/"));
if (allowedExtensions.some((ext) => file.endsWith(ext))) {
return file;
}
}
const file = await internals.askFile(); if (argvFiles.length > 0) {
if (file === undefined || file.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(); await internals.exit();
} }
return file.join("");
return files;
}
const files = await internals.askFiles();
if (files === undefined || files.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;
}
}; };
/** Either replace the message, or add some info */ /** Either replace the message, or add some info */
@ -62,13 +99,27 @@ const updateMessage = (
/** Main function */ /** Main function */
const main = async () => { const main = async () => {
const maxSizeDiscord = 25; const maxSizeDiscord = await fetchMaxSize();
updateMessage("Récupération du fichier..."); updateMessage("Récupération des fichiers...");
const file = await getFile(); const files = await getFiles();
updateMessage("Mélange des pistes audios vers la piste 1...", true); let processedFiles = "";
let numberOfUncompressableFiles = 0;
// 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
);
const newFile = await internals.mergeAudio(file); const newFile = await internals.mergeAudio(file);
let finalTitle = newFile.title; let finalTitle = newFile.title;
updateMessage(`Taille calculée : ~${Math.round(newFile.size)}Mio`); updateMessage(
`${counter} - Taille calculée : ~${Math.round(newFile.size)}Mio`
);
// Compress video if needed
if (newFile.size > maxSizeDiscord) { if (newFile.size > maxSizeDiscord) {
const targetSize = maxSizeDiscord - 2; // keep some room const targetSize = maxSizeDiscord - 2; // keep some room
@ -80,10 +131,45 @@ const main = async () => {
true, true,
Mode.Append Mode.Append
); );
finalTitle = await internals.reduceSize(newFile.title, bitrate);
// 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
);
} }
updateMessage("Fichier prêt ! :)");
await internals.confirmation(`File ok @ ${finalTitle}!`); // 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++;
}
}
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
);
await internals.exit(); await internals.exit();
}; };
main(); main();

View file

@ -1,7 +1,12 @@
import ffprobe = require("ffprobe-static");
import child_process = require("child_process"); import child_process = require("child_process");
import path = require("path"); import path = require("path");
import { BrowserWindow } from "electron"; 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 */ /** Create a new filename from the OG one */
export const getNewFilename = (ogFile: string, part: string) => { export const getNewFilename = (ogFile: string, part: string) => {
@ -11,26 +16,65 @@ export const getNewFilename = (ogFile: string, part: string) => {
/** Return the duration of a video in second */ /** Return the duration of a video in second */
export const getVideoDuration = (file: string) => { export const getVideoDuration = (file: string) => {
const command = `"${ffprobe.path}" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${file}"`; const command = `"${ffprobePath}" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${file}"`;
const durationString = child_process.execSync(command).toString().trim(); const durationString = child_process.execSync(command).toString().trim();
return parseFloat(durationString); 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 */ /** Print an error to the console and open the dev tool panel */
export const printAndDevTool = (win: BrowserWindow, error: string) => { export const printAndDevTool = (win: BrowserWindow, err: string) => {
console.error(error);
win.webContents.openDevTools(); win.webContents.openDevTools();
win.webContents.send("error", err);
}; };
/** Run a command asynchronously */ /** Run a command asynchronously */
export const execute = (command: string) => { export const execute = (
command: string
): Promise<{ stdout: string; stderr: string }> => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
child_process.exec(command, (error, stdout, stderr) => { const process = child_process.exec(command, (error, stdout, stderr) => {
if (error) { if (error) {
reject(error); reject(error);
} else { } else {
resolve({ stdout, stderr }); 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,6 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "commonjs", "module": "commonjs",
"downlevelIteration": true,
"noImplicitAny": true, "noImplicitAny": true,
"sourceMap": true, "sourceMap": true,
"outDir": "dist", "outDir": "dist",