This commit is contained in:
Obi1 2024-09-05 22:18:54 +02:00
commit 3d905ef4b6
8 changed files with 478 additions and 0 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
/2dxAutoClip-NET/bin
/2dxAutoClip-NET/obj

25
2dxAutoClip-NET.sln Normal file
View file

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33530.505
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "2dxAutoClip-NET", "2dxAutoClip-NET\2dxAutoClip-NET.csproj", "{E6835B21-4D90-4E98-89C0-ACA2C64DFD10}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E6835B21-4D90-4E98-89C0-ACA2C64DFD10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E6835B21-4D90-4E98-89C0-ACA2C64DFD10}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E6835B21-4D90-4E98-89C0-ACA2C64DFD10}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E6835B21-4D90-4E98-89C0-ACA2C64DFD10}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B95C6D19-B182-42D2-B53E-963236D0D444}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E6835B21-4D90-4E98-89C0-ACA2C64DFD10}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>_2dxAutoClip_NET</RootNamespace>
<AssemblyName>2dxAutoClip-NET</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Win32.Registry, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Win32.Registry.4.7.0\lib\net461\Microsoft.Win32.Registry.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="NAudio, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.2.2.1\lib\net472\NAudio.dll</HintPath>
</Reference>
<Reference Include="NAudio.Asio, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.Asio.2.2.1\lib\netstandard2.0\NAudio.Asio.dll</HintPath>
</Reference>
<Reference Include="NAudio.Core, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.Core.2.2.1\lib\netstandard2.0\NAudio.Core.dll</HintPath>
</Reference>
<Reference Include="NAudio.Midi, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.Midi.2.2.1\lib\netstandard2.0\NAudio.Midi.dll</HintPath>
</Reference>
<Reference Include="NAudio.Wasapi, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.Wasapi.2.2.1\lib\netstandard2.0\NAudio.Wasapi.dll</HintPath>
</Reference>
<Reference Include="NAudio.WinForms, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.WinForms.2.2.1\lib\net472\NAudio.WinForms.dll</HintPath>
</Reference>
<Reference Include="NAudio.WinMM, Version=2.2.1.0, Culture=neutral, PublicKeyToken=e279aa5131008a41, processorArchitecture=MSIL">
<HintPath>..\packages\NAudio.WinMM.2.2.1\lib\netstandard2.0\NAudio.WinMM.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Security.AccessControl, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.AccessControl.4.7.0\lib\net461\System.Security.AccessControl.dll</HintPath>
</Reference>
<Reference Include="System.Security.Principal.Windows, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Principal.Windows.4.7.0\lib\net461\System.Security.Principal.Windows.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ffmpegAPI.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>

156
2dxAutoClip-NET/Program.cs Normal file
View file

@ -0,0 +1,156 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Threading;
namespace _2dxAutoClip_NET
{
internal class Program //get .NET'd stinky
{
private static readonly string websocketAddress = "localhost";
private static readonly int websocketPort = 10573;
public static ffmpegAPI _ffmpeg = new ffmpegAPI();
static async Task Main(string[] args)
{
Process[] spiceProcesses = Process.GetProcessesByName("spice64");
if (spiceProcesses.Length > 0)
{
Console.WriteLine("Found spice64.exe running, proceeding to connect to TickerHookWS...");
await Connect2Websocket();
}
else
{
Console.WriteLine("spice64.exe is not running.");
}
}
public static string GetPathFile()
{
string wanted_path = $"{File.ReadAllText($@"{Environment.CurrentDirectory}\conf\path.txt")}"; //@"E:\autorecording"
if (Directory.Exists(wanted_path.Replace(@"\path.txt", "")))
{
return wanted_path;
}
else
{
return $@"C:\Users\{Environment.UserName}\Videos";
}
}
public static async Task Connect2Websocket()
{
int maxretry = 5;
int attempt = 0;
while (attempt < maxretry)
{
attempt++;
Console.WriteLine($"Attempt: {attempt} of {maxretry}");
bool succ = await ConnectWebSocket();
if (succ)
{
break;
}
else if (attempt < maxretry)
{
Console.WriteLine($"Retrying in 10 seconds... {maxretry - attempt} attempts remaining.");
await Task.Delay(10000);
}
else if (attempt == maxretry)
{
Console.WriteLine("Failed to connect after 5 attempts..");
}
}
}
public static async Task<bool> ConnectWebSocket()
{
var tickerUri = new Uri($"ws://{websocketAddress}:{websocketPort}");
var reconnecting = false;
var lastMessage = string.Empty;
var consecutiveMessageCount = 0;
var isRecording = false;
var currentSongName = string.Empty;
var shouldCheckForMusicSelect = false;
var clientWebSocket = new ClientWebSocket();
try
{
await clientWebSocket.ConnectAsync(tickerUri, CancellationToken.None);
Console.WriteLine("Connected to TickerHook WebSocket.");
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to TickerHook WebSocket: {ex.Message}");
return false; // Indicate connection failure
}
var buffer = new byte[1024];
while (clientWebSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult result;
try
{
result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
catch (Exception ex)
{
Console.WriteLine($"Error receiving message: {ex.Message}");
reconnecting = true;
break;
}
var message = Encoding.UTF8.GetString(buffer, 0, result.Count).Trim().ToUpper();
Console.WriteLine($"Received message: {message}");
if (message == lastMessage && !message.Contains("SELECT FROM"))
{
consecutiveMessageCount++;
}
else
{
consecutiveMessageCount = 1;
lastMessage = message;
}
if (consecutiveMessageCount >= 2 && !message.Contains("SELECT FROM") && !isRecording)
{
currentSongName = message;
Console.WriteLine("Starting recording...");
_ffmpeg.StartRecording(currentSongName);
isRecording = true;
}
if (isRecording)
{
if (shouldCheckForMusicSelect && message.Contains("MUSIC SELECT!!"))
{
Console.WriteLine("Stopping recording...");
_ffmpeg.StopRecording(currentSongName);
isRecording = false;
shouldCheckForMusicSelect = false;
}
else if (message.EndsWith("CLEAR!") || message.EndsWith("FAILED.."))
{
shouldCheckForMusicSelect = true;
}
}
}
return !reconnecting;
}
}
}

View file

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("2dxAutoClip-NET")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2dxAutoClip-NET")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e6835b21-4d90-4e98-89c0-aca2c64dfd10")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View file

@ -0,0 +1,153 @@
using NAudio.CoreAudioApi;
using NAudio.Wave;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace _2dxAutoClip_NET
{
internal class ffmpegAPI
{
public ffmpegAPI() { }
private static Process _ffmpegProcess;
private static string _ffmpegFolderPath = File.ReadAllText($@"{Environment.CurrentDirectory}\conf\ffmpeg.exe");
private static WasapiCapture _waveSource;
private static WaveFileWriter _writer = null;
private static string _audioFilePath = null;
private static string _videoFilePath = null;
public void StartRecording(string songName)
{
Task.Run(() => StartAudioRecording(songName));
StartFfmpegRecording(songName);
}
public void StartAudioRecording(string songName)
{
try
{
var date = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
_audioFilePath = $"{_ffmpegFolderPath}\\{songName}_{date}.wav";
var outputFolder = Path.GetDirectoryName(_audioFilePath);
Directory.CreateDirectory(outputFolder);
_waveSource = new WasapiLoopbackCapture();
_writer = new WaveFileWriter(_audioFilePath, _waveSource.WaveFormat);
_waveSource.DataAvailable += (sender, args) =>
{
_writer.Write(args.Buffer, 0, args.BytesRecorded);
};
_waveSource.RecordingStopped += (sender, args) =>
{
_writer.Dispose();
_writer = null;
_waveSource.Dispose();
_waveSource = null;
};
_waveSource.StartRecording();
Console.WriteLine("WASAPI Audio recording started.");
}
catch (Exception ex)
{
Console.WriteLine($"Error starting audio recording: {ex.Message}");
}
}
public void StartFfmpegRecording(string songName)
{
var date = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
_videoFilePath = $"{_ffmpegFolderPath}\\{songName}_{date}.mkv";
var ffmpegArguments = $"-framerate 60 " +
$"-filter_complex \"ddagrab=0,hwdownload,format=bgra\" " +
$"-c:v libx264 -movflags +faststart -crf 20 -y \"{_videoFilePath}\"";
_ffmpegProcess = new Process();
_ffmpegProcess.StartInfo.FileName = "ffmpeg";
_ffmpegProcess.StartInfo.Arguments = ffmpegArguments;
_ffmpegProcess.StartInfo.UseShellExecute = false;
_ffmpegProcess.StartInfo.RedirectStandardOutput = false;
_ffmpegProcess.StartInfo.RedirectStandardError = true;
_ffmpegProcess.StartInfo.CreateNoWindow = true;
_ffmpegProcess.ErrorDataReceived += (_, args) => Console.WriteLine(args.Data);
_ffmpegProcess.Start();
_ffmpegProcess.BeginErrorReadLine();
}
public void StopRecording(string songName)
{
StopFfmpegRecording();
StopAudioRecording();
CombineAudioAndVideo(_videoFilePath, _audioFilePath, songName);
}
public void StopAudioRecording()
{
if (_waveSource == null) return;
_waveSource.StopRecording();
_waveSource.Dispose();
_waveSource = null;
if (_writer != null)
{
_writer.Dispose();
_writer = null;
}
Console.WriteLine("Audio recording stopped.");
}
public void StopFfmpegRecording()
{
if (_ffmpegProcess != null && _ffmpegProcess.HasExited) return;
_ffmpegProcess?.Kill();
_ffmpegProcess?.WaitForExit();
_ffmpegProcess?.Dispose();
_ffmpegProcess = null;
Console.WriteLine("FFMPEG process stopped.");
}
public void CombineAudioAndVideo(string videoFilePath, string audioFilePath, string songName)
{
var combinedOutputFilePath = $"{_ffmpegFolderPath}\\{songName}_combined_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.mp4";
var ffmpegArgs =
$"-y -i \"{videoFilePath}\" -i \"{audioFilePath}\" -c:v copy -c:a aac -strict experimental \"{combinedOutputFilePath}\"";
var processInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = ffmpegArgs,
RedirectStandardOutput = false,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
var process = Process.Start(processInfo);
if (process == null)
{
Console.WriteLine("FFmpeg failed to start.");
return;
}
var error = process.StandardError.ReadToEnd();
process.WaitForExit();
Console.WriteLine("FFmpeg Error: " + error);
Console.WriteLine(File.Exists(combinedOutputFilePath)
? "Audio and video have been successfully combined."
: "Failed to combine audio and video. Check the logs for errors.");
File.Delete(videoFilePath);
File.Delete(audioFilePath);
}
}
}

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Win32.Registry" version="4.7.0" targetFramework="net48" />
<package id="NAudio" version="2.2.1" targetFramework="net48" />
<package id="NAudio.Asio" version="2.2.1" targetFramework="net48" />
<package id="NAudio.Core" version="2.2.1" targetFramework="net48" />
<package id="NAudio.Midi" version="2.2.1" targetFramework="net48" />
<package id="NAudio.Wasapi" version="2.2.1" targetFramework="net48" />
<package id="NAudio.WinForms" version="2.2.1" targetFramework="net48" />
<package id="NAudio.WinMM" version="2.2.1" targetFramework="net48" />
<package id="System.Security.AccessControl" version="4.7.0" targetFramework="net48" />
<package id="System.Security.Principal.Windows" version="4.7.0" targetFramework="net48" />
</packages>