26 Commits
Author SHA1 Message Date
Stevan Freeborn 1a309345f4 chore(release): 0.4.0 [skip ci] 2025-10-10 21:44:49 +00:00
Stevan Freeborn f6abaefd72 Merge pull request #17 from StevanFreeborn/stevanfreeborn/feat/deal-with-larger-streams
feat: deal with larger streams
2025-10-10 16:44:28 -05:00
Stevan Freeborn 4b56011f3b chore: run dotnet format 2025-10-10 16:42:14 -05:00
Stevan Freeborn a34ffe575b fix: fix error messages and remove unnecessary null check and use input file name for audio output name 2025-10-10 16:38:46 -05:00
Stevan Freeborn 401f03e2f0 fix: add validation that stream is seekable 2025-10-10 16:34:43 -05:00
Stevan Freeborn e611522c7b feat: enable processing of large video files over 2GB
Update audio extraction to use file-based streaming
instead of in-memory buffers to support processing
video files larger than 2GB.

**Changes:**
- Modified `IAudioExtractor.ExtractMp3FromMp4Async()`
  to accept an output audio stream parameter instead
  of creating a MemoryStream internally
- Updated `AudioExtractor` to write directly to the
  provided audio stream, eliminating the need to load
  entire video into memory
- Enhanced `FFMpegService` to detect FileStream inputs
  and use direct file-to-file processing when possible,
  falling back to pipe-based streaming for other stream types
- Refactored `DefaultCommand` to create output directory
  and audio file stream before extraction, enabling direct
  file-based audio extraction
- Updated all unit and integration tests to accommodate the
  new audio stream parameter

This change prevents `OutOfMemoryException` errors when processing
large video files by streaming data directly to disk rather than
buffering in memory. Additionally, it removes the possibility of
overflowing the 2GB size limit that `MemoryStream` has, which
would result in `IOException` errors when trying to write or
copy to it.
2025-10-10 16:23:02 -05:00
Stevan Freeborn 6dcffa6b75 format: remove unnecessary whitespace 2025-10-10 15:40:10 -05:00
Stevan Freeborn f5e33d80cd chore: add debugger config for vscode 2025-10-10 15:38:19 -05:00
Stevan Freeborn ff81c9ca43 chore: identify binary files to git 2025-10-10 15:38:06 -05:00
Stevan Freeborn 3f7d68ffb5 Merge pull request #15 from StevanFreeborn/copilot/fix-escape-markup-console 2025-10-09 19:09:25 -05:00
copilot-swe-agent[bot]andStevanFreeborn 3656dd7463 Fix test naming convention and remove unnecessary comments
Co-authored-by: StevanFreeborn <65925598+StevanFreeborn@users.noreply.github.com>
2025-10-10 00:04:54 +00:00
copilot-swe-agent[bot]andStevanFreeborn 662d899196 Add markup escaping to validation error message
Co-authored-by: StevanFreeborn <65925598+StevanFreeborn@users.noreply.github.com>
2025-10-09 23:46:59 +00:00
copilot-swe-agent[bot]andStevanFreeborn f2fdc53222 Escape markup in file paths for console output
Co-authored-by: StevanFreeborn <65925598+StevanFreeborn@users.noreply.github.com>
2025-10-09 23:44:31 +00:00
copilot-swe-agent[bot] cfe0878bcd Initial plan 2025-10-09 23:37:25 +00:00
Stevan Freeborn 34b1a17f9f chore(release): 0.3.0 [skip ci] 2025-10-09 21:14:51 +00:00
Stevan Freeborn 4277ea1283 Merge pull request #14 from StevanFreeborn/stevanfreeborn/feat/add-output-directory-config-setting
feat: add configurable output directory with validation
2025-10-09 16:14:33 -05:00
Stevan Freeborn 6ebec7c285 fix: use file system abstraction in base directory method. thanks copilot 🤖 2025-10-09 16:14:10 -05:00
Stevan Freeborn 8632f88817 feat: add configurable output directory with validation
- Add support for OutputDirectory configuration setting.
- The command now validates the configured directory path,
  creates it if needed, and falls back to the application
  base directory if invalid. Includes error handling for
  path-related exceptions.
2025-10-09 16:08:56 -05:00
Stevan Freeborn 487183ef1f chore(release): 0.2.0 [skip ci] 2025-08-21 03:18:07 +00:00
Stevan Freeborn 708b97a5c0 Merge pull request #8 from StevanFreeborn/stevanfreeborn/feat/5-display-location-of-shorts
feat: display location of output with link inside panel
2025-08-20 22:17:47 -05:00
Stevan Freeborn 57e95b2ea1 feat: display location of output with link inside panel 2025-08-20 22:17:06 -05:00
Stevan Freeborn 9b5a65fc92 chore(release): 0.1.0 [skip ci] 2025-08-21 02:43:39 +00:00
Stevan Freeborn ecc676bff1 Merge pull request #7 from StevanFreeborn/stevanfreeborn/feat/6-throw-error-if-appsettings-not-present
feat: make sure error is shown to user if appsettings.json file is not present
2025-08-20 21:43:16 -05:00
Stevan Freeborn d560909f16 feat: fallback to static AnsiConsole if exception occurs before registered in DI container 2025-08-20 21:42:19 -05:00
Stevan Freeborn 51f5359202 Merge branch 'main' of github.com:StevanFreeborn/stream-shorts 2025-08-20 16:32:21 -05:00
Stevan Freeborn 022798d11b chore: update gitignore 2025-08-20 16:32:15 -05:00
16 changed files with 227 additions and 68 deletions
+2
View File
@@ -0,0 +1,2 @@
*.mp3 binary
*.mp4 binary
+3
View File
@@ -3,6 +3,9 @@
## ##
## Get latest from `dotnet new gitignore` ## Get latest from `dotnet new gitignore`
# published files
dist/
# dotenv files # dotenv files
.env .env
appsettings*.json appsettings*.json
+27
View File
@@ -0,0 +1,27 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "coreclr",
"request": "launch",
"name": "Launch StreamShorts.Console",
"program": "${workspaceFolder}/src/StreamShorts.Console/bin/Debug/net9.0/win-x64/StreamShorts.Console.dll",
"args": [
"${input:filePath}"
],
"cwd": "${workspaceFolder}/src/StreamShorts.Console",
"stopAtEntry": false,
"console": "integratedTerminal",
"preLaunchTask": "build",
"justMyCode": false
}
],
"inputs": [
{
"id": "filePath",
"type": "promptString",
"description": "Enter the path to the video file",
"default": ""
}
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/StreamShorts.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
+37
View File
@@ -2,6 +2,43 @@
All notable changes to this project will be documented in this file. See [versionize](https://github.com/versionize/versionize) for commit guidelines. All notable changes to this project will be documented in this file. See [versionize](https://github.com/versionize/versionize) for commit guidelines.
<a name="0.4.0"></a>
## [0.4.0](https://www.github.com/StevanFreeborn/stream-shorts/releases/tag/v0.4.0) (2025-10-10)
### Features
* enable processing of large video files over 2GB ([e611522](https://www.github.com/StevanFreeborn/stream-shorts/commit/e611522c7bc724807ea39bdb5e6005b2deb911be))
### Bug Fixes
* add validation that stream is seekable ([401f03e](https://www.github.com/StevanFreeborn/stream-shorts/commit/401f03e2f0149b0f9d68df5d62fc3d5cccd3dc9e))
* fix error messages and remove unnecessary null check and use input file name for audio output name ([a34ffe5](https://www.github.com/StevanFreeborn/stream-shorts/commit/a34ffe575b9e16e24d0b3d15d117d96f11a17d59))
<a name="0.3.0"></a>
## [0.3.0](https://www.github.com/StevanFreeborn/stream-shorts/releases/tag/v0.3.0) (2025-10-09)
### Features
* add configurable output directory with validation ([8632f88](https://www.github.com/StevanFreeborn/stream-shorts/commit/8632f88817c78663c632156a490eb118b802fef6))
### Bug Fixes
* use file system abstraction in base directory method. thanks copilot 🤖 ([6ebec7c](https://www.github.com/StevanFreeborn/stream-shorts/commit/6ebec7c2859200fd6c4374a84786c21dfa143171))
<a name="0.2.0"></a>
## [0.2.0](https://www.github.com/StevanFreeborn/stream-shorts/releases/tag/v0.2.0) (2025-08-21)
### Features
* display location of output with link inside panel ([57e95b2](https://www.github.com/StevanFreeborn/stream-shorts/commit/57e95b2ea19ea97019df70bd7a5414984faaa1c7))
<a name="0.1.0"></a>
## [0.1.0](https://www.github.com/StevanFreeborn/stream-shorts/releases/tag/v0.1.0) (2025-08-21)
### Features
* fallback to static AnsiConsole if exception occurs before registered in DI container ([d560909](https://www.github.com/StevanFreeborn/stream-shorts/commit/d560909f16f0a97b399f8139f94b6f2fe07cf033))
<a name="0.0.0"></a> <a name="0.0.0"></a>
## [0.0.0](https://www.github.com/StevanFreeborn/stream-shorts/releases/tag/v0.0.0) (2025-08-20) ## [0.0.0](https://www.github.com/StevanFreeborn/stream-shorts/releases/tag/v0.0.0) (2025-08-20)
@@ -10,7 +10,9 @@ internal sealed class DefaultCommand(
ITranscriber transcriber, ITranscriber transcriber,
ITranscriptAnalyzer transcriptAnalyzer, ITranscriptAnalyzer transcriptAnalyzer,
IShortsCreator shortsCreator, IShortsCreator shortsCreator,
TimeProvider timeProvider TimeProvider timeProvider,
IConfiguration appConfig,
ILogger<DefaultCommand> logger
) : AsyncCommand<DefaultCommand.Settings> ) : AsyncCommand<DefaultCommand.Settings>
{ {
private readonly JsonSerializerOptions _jsonSerializerOptions = new() private readonly JsonSerializerOptions _jsonSerializerOptions = new()
@@ -26,6 +28,8 @@ internal sealed class DefaultCommand(
private readonly ITranscriptAnalyzer _transcriptAnalyzer = transcriptAnalyzer ?? throw new ArgumentNullException(nameof(transcriptAnalyzer)); private readonly ITranscriptAnalyzer _transcriptAnalyzer = transcriptAnalyzer ?? throw new ArgumentNullException(nameof(transcriptAnalyzer));
private readonly IShortsCreator _shortsCreator = shortsCreator ?? throw new ArgumentNullException(nameof(shortsCreator)); private readonly IShortsCreator _shortsCreator = shortsCreator ?? throw new ArgumentNullException(nameof(shortsCreator));
private readonly TimeProvider _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider)); private readonly TimeProvider _timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
private readonly IConfiguration _appConfig = appConfig ?? throw new ArgumentNullException(nameof(appConfig));
private readonly ILogger<DefaultCommand> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
/// <summary> /// <summary>
/// Represents the settings for the default command. /// Represents the settings for the default command.
@@ -49,7 +53,7 @@ internal sealed class DefaultCommand(
if (_fileSystem.File.Exists(settings.Stream) is false) if (_fileSystem.File.Exists(settings.Stream) is false)
{ {
return ValidationResult.Error($"The specified stream file '{settings.Stream}' does not exist."); return ValidationResult.Error($"The specified stream file '{settings.Stream.EscapeMarkup()}' does not exist.");
} }
var fileExtension = _fileSystem.Path.GetExtension(settings.Stream).ToUpperInvariant(); var fileExtension = _fileSystem.Path.GetExtension(settings.Stream).ToUpperInvariant();
@@ -64,23 +68,29 @@ internal sealed class DefaultCommand(
public override async Task<int> ExecuteAsync(CommandContext context, Settings settings) public override async Task<int> ExecuteAsync(CommandContext context, Settings settings)
{ {
_console.MarkupLine($"[blue]Processing stream:[/] {settings.Stream}"); _console.MarkupLine($"[blue]Processing stream:[/] {settings.Stream.EscapeMarkup()}");
var videoStream = _fileSystem.File.OpenRead(settings.Stream); var videoStream = (FileStream)_fileSystem.File.OpenRead(settings.Stream);
Stream? audioStream = null; var now = _timeProvider.GetUtcNow();
var inputFileName = _fileSystem.Path.GetFileNameWithoutExtension(settings.Stream);
var baseDirectory = ValidateAndGetBaseOutputDirectory();
var artifactsOutputDirectory = $"{now:yyyy_MM_dd_HH_mm_ss}_{inputFileName}";
var outputDirectoryPath = _fileSystem.Path.Combine(baseDirectory, artifactsOutputDirectory);
_fileSystem.Directory.CreateDirectory(outputDirectoryPath);
using var audioStream = new FileStream(
_fileSystem.Path.Combine(outputDirectoryPath, $"{inputFileName}.mp3"),
FileMode.Create,
FileAccess.ReadWrite,
FileShare.ReadWrite,
4096,
FileOptions.Asynchronous
);
await _console.Status() await _console.Status()
.Spinner(Spinner.Known.Dots) .Spinner(Spinner.Known.Dots)
.StartAsync("Extracting audio...", async _ => .StartAsync("Extracting audio...", async _ => await _audioExtractor.ExtractMp3FromMp4Async(videoStream, audioStream));
{
audioStream = await _audioExtractor.ExtractMp3FromMp4Async(videoStream);
});
if (audioStream is null)
{
_console.MarkupLine("[red]Failed[/] to extract audio from the stream.");
return (int)ExitCode.FailedToExtractAudio;
}
_console.MarkupLine($"[blue]Audio extracted[/] [green]successfully![/]"); _console.MarkupLine($"[blue]Audio extracted[/] [green]successfully![/]");
@@ -100,15 +110,6 @@ internal sealed class DefaultCommand(
_console.MarkupLine($"[blue]Transcription completed[/] [green]successfully![/]"); _console.MarkupLine($"[blue]Transcription completed[/] [green]successfully![/]");
var now = _timeProvider.GetUtcNow();
var inputFileName = _fileSystem.Path.GetFileNameWithoutExtension(settings.Stream);
var outputDirectoryPath = _fileSystem.Path.Combine(
AppContext.BaseDirectory,
$"{now:yyyy_MM_dd_HH_mm_ss}_{inputFileName}"
);
_fileSystem.Directory.CreateDirectory(outputDirectoryPath);
await _fileSystem.File.WriteAllTextAsync( await _fileSystem.File.WriteAllTextAsync(
_fileSystem.Path.Combine(outputDirectoryPath, "transcription.txt"), _fileSystem.Path.Combine(outputDirectoryPath, "transcription.txt"),
string.Join(Environment.NewLine, transcriptionSegments) string.Join(Environment.NewLine, transcriptionSegments)
@@ -118,10 +119,7 @@ internal sealed class DefaultCommand(
await _console.Status() await _console.Status()
.Spinner(Spinner.Known.Dots) .Spinner(Spinner.Known.Dots)
.StartAsync("Analyzing transcript...", async _ => .StartAsync("Analyzing transcript...", async _ => analysis = await _transcriptAnalyzer.AnalyzeAsync(transcriptionSegments));
{
analysis = await _transcriptAnalyzer.AnalyzeAsync(transcriptionSegments);
});
if (analysis is null) if (analysis is null)
{ {
@@ -149,14 +147,53 @@ internal sealed class DefaultCommand(
} }
}); });
_console.MarkupLine($"[blue]Shorts created[/] [green]successfully![/]"); var directoryUri = new Uri(outputDirectoryPath).AbsoluteUri;
var panel = new Panel($"[blue link={directoryUri}]{artifactsOutputDirectory.EscapeMarkup()}[/]")
{
Header = new PanelHeader($"[blue]Shorts created[/] [green]successfully![/]")
};
return 0; _console.Write(panel);
return (int)ExitCode.SuccessFullyProcessedStream;
}
private string ValidateAndGetBaseOutputDirectory()
{
var baseDirectory = _appConfig.GetValue<string>("OutputDirectory");
if (string.IsNullOrWhiteSpace(baseDirectory))
{
return AppContext.BaseDirectory;
}
try
{
var fullPath = _fileSystem.Path.GetFullPath(baseDirectory);
if (_fileSystem.Directory.Exists(fullPath) is false)
{
_fileSystem.Directory.CreateDirectory(fullPath);
}
return fullPath;
}
catch (Exception ex) when (
ex is ArgumentException
or NotSupportedException
or PathTooLongException
or DirectoryNotFoundException
or UnauthorizedAccessException
)
{
_logger.LogWarning(ex, "The configured output directory '{BaseDirectory}' is invalid. Defaulting to application base directory.", baseDirectory);
return AppContext.BaseDirectory;
}
} }
private enum ExitCode private enum ExitCode
{ {
FailedToExtractAudio,
FailedToAnalyzeTranscript, FailedToAnalyzeTranscript,
SuccessFullyProcessedStream,
} }
} }
@@ -18,9 +18,9 @@ internal static class HostBuilderExtensions
app.Configure(static c => app.Configure(static c =>
c.SetExceptionHandler(static (ex, resolver) => c.SetExceptionHandler(static (ex, resolver) =>
{ {
var console = resolver?.Resolve(typeof(IAnsiConsole)) as IAnsiConsole; var console = resolver?.Resolve(typeof(IAnsiConsole)) as IAnsiConsole ?? AnsiConsole.Console;
console?.MarkupLine($"[red]An error occurred while executing the command:[/]"); console.MarkupLine($"[red]An error occurred while executing the command:[/]");
console?.WriteException(ex, ExceptionFormats.ShortenEverything); console.WriteException(ex, ExceptionFormats.ShortenEverything);
}) })
); );
+1 -1
View File
@@ -25,7 +25,7 @@ try
services.AddSingleton(TimeProvider.System); services.AddSingleton(TimeProvider.System);
services.AddSingleton<IAudioExtractor, AudioExtractor>(); services.AddSingleton<IAudioExtractor, AudioExtractor>();
services.AddSingleton<ITranscriber, WhisperTranscriber>(); services.AddSingleton<ITranscriber, WhisperTranscriber>();
services.AddSingleton<ITranscriptAnalyzer, GeminiAnalyzer>(sp => services.AddSingleton<ITranscriptAnalyzer, GeminiAnalyzer>(static sp =>
{ {
const string modelOptionName = "Model"; const string modelOptionName = "Model";
const string keyOptionName = "ApiKey"; const string keyOptionName = "ApiKey";
@@ -4,7 +4,7 @@
<AssemblyTitle>StreamShorts.Console</AssemblyTitle> <AssemblyTitle>StreamShorts.Console</AssemblyTitle>
<Product>StreamShorts.Console</Product> <Product>StreamShorts.Console</Product>
<Description>A command-line interface for StreamShorts</Description> <Description>A command-line interface for StreamShorts</Description>
<Version>0.0.0</Version> <Version>0.4.0</Version>
<Authors>Stevan Freeborn</Authors> <Authors>Stevan Freeborn</Authors>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<PublishSingleFile>true</PublishSingleFile> <PublishSingleFile>true</PublishSingleFile>
@@ -25,42 +25,41 @@ public sealed class AudioExtractor : IAudioExtractor
_videoService = videoService ?? throw new ArgumentNullException(nameof(videoService), $"{nameof(videoService)} cannot be null"); _videoService = videoService ?? throw new ArgumentNullException(nameof(videoService), $"{nameof(videoService)} cannot be null");
} }
public async Task<Stream> ExtractMp3FromMp4Async(Stream video) public async Task<Stream> ExtractMp3FromMp4Async(Stream video, Stream audio)
{ {
if (video is null) if (video is null)
{ {
throw new ArgumentNullException(nameof(video), "Video stream cannot be null"); throw new ArgumentNullException(nameof(video), "Video stream cannot be null");
} }
if (video.CanRead is false) if (IsVideoStreamUsable(video) is false)
{ {
throw new ArgumentException("Video stream must be readable", nameof(video)); throw new ArgumentException("Stream must be readable and seekable", nameof(video));
} }
if (video.CanSeek is false) if (audio is null)
{ {
throw new ArgumentException("Video stream must be seekable", nameof(video)); throw new ArgumentNullException(nameof(audio), "Audio stream cannot be null");
}
if (IsAudioStreamUsable(audio) is false)
{
throw new ArgumentException("Stream must be writable and seekable", nameof(audio));
} }
var originalPosition = video.Position; var originalPosition = video.Position;
try try
{ {
var mp3Stream = new MemoryStream(); var wasExtracted = await _videoService.ExtractAudioFromVideoAsync(video, audio).ConfigureAwait(false);
using var mp4Stream = new MemoryStream();
await video.CopyToAsync(mp4Stream).ConfigureAwait(false);
mp4Stream.Position = 0;
var wasExtracted = await _videoService.ExtractAudioFromVideoAsync(mp4Stream, mp3Stream).ConfigureAwait(false);
if (wasExtracted is false) if (wasExtracted is false)
{ {
throw new FailedAudioExtractionException("Failed to extract audio from the video stream."); throw new FailedAudioExtractionException("Failed to extract audio from the video stream.");
} }
mp3Stream.Position = 0; audio.Position = 0;
return mp3Stream; return audio;
} }
catch (Exception e) when (e is not FailedAudioExtractionException) catch (Exception e) when (e is not FailedAudioExtractionException)
{ {
@@ -71,4 +70,14 @@ public sealed class AudioExtractor : IAudioExtractor
video.Position = originalPosition; video.Position = originalPosition;
} }
} }
private static bool IsVideoStreamUsable(Stream stream)
{
return stream.CanRead && stream.CanSeek;
}
private static bool IsAudioStreamUsable(Stream stream)
{
return stream.CanWrite && stream.CanSeek;
}
} }
@@ -9,11 +9,15 @@ public interface IAudioExtractor
/// Extracts MP3 audio from an MP4 video stream. /// Extracts MP3 audio from an MP4 video stream.
/// </summary> /// </summary>
/// <param name="video">The input video stream.</param> /// <param name="video">The input video stream.</param>
/// <param name="audio">The output audio stream where the extracted MP3 will be written.</param>
/// <returns>A stream containing the extracted MP3 audio.</returns> /// <returns>A stream containing the extracted MP3 audio.</returns>
/// <exception cref="ArgumentNullException">Thrown when the video stream is null.</exception> /// <exception cref="ArgumentNullException">Thrown when the video stream is null.</exception>
/// <exception cref="ArgumentException">Thrown when the video stream is not readable.</exception> /// <exception cref="ArgumentException">Thrown when the video stream is not readable.</exception>
/// <exception cref="ArgumentException">Thrown when the video stream is not seekable.</exception> /// <exception cref="ArgumentException">Thrown when the video stream is not seekable.</exception>
/// <exception cref="ArgumentNullException">Thrown when the audio stream is null.</exception>
/// <exception cref="ArgumentException">Thrown when the audio stream is not writable.</exception>
/// <exception cref="ArgumentException">Thrown when the audio stream is not seekable.</exception>
/// <exception cref="FailedAudioExtractionException">Thrown when the audio extraction fails.</exception> /// <exception cref="FailedAudioExtractionException">Thrown when the audio extraction fails.</exception>
/// <remarks>The method will preserve the passed video stream's data and position.</remarks> /// <remarks>The method will preserve the passed video stream's data and position.</remarks>
Task<Stream> ExtractMp3FromMp4Async(Stream video); Task<Stream> ExtractMp3FromMp4Async(Stream video, Stream audio);
} }
@@ -12,14 +12,17 @@ internal sealed class FFMpegService : IVideoService
{ {
public async Task<bool> ExtractAudioFromVideoAsync(Stream video, Stream audio) public async Task<bool> ExtractAudioFromVideoAsync(Stream video, Stream audio)
{ {
return await FFMpegArguments var inputArguments = video is FileStream videoFileStream
.FromPipeInput(new StreamPipeSource(video)) ? FFMpegArguments.FromFileInput(videoFileStream.Name)
.OutputToPipe( : FFMpegArguments.FromPipeInput(new StreamPipeSource(video));
new StreamPipeSink(audio),
static o => o.DisableChannel(Channel.Video).ForceFormat("mp3") Action<FFMpegArgumentOptions> arguments = static o => o.DisableChannel(Channel.Video).ForceFormat("mp3");
)
.ProcessAsynchronously() var processor = audio is FileStream audioFileStream
.ConfigureAwait(false); ? inputArguments.OutputToFile(audioFileStream.Name, addArguments: arguments)
: inputArguments.OutputToPipe(new StreamPipeSink(audio), addArguments: arguments);
return await processor.ProcessAsynchronously().ConfigureAwait(false);
} }
public async Task CreateClipFromVideoAsync( public async Task CreateClipFromVideoAsync(
@@ -1,4 +1,3 @@
using NAudio.Wave; using NAudio.Wave;
namespace StreamShorts.Library.Media; namespace StreamShorts.Library.Media;
@@ -0,0 +1,19 @@
namespace StreamShorts.Console.Tests.Unit.Commands;
using Spectre.Console;
public class DefaultCommandTests
{
[Theory]
[InlineData("file[with]brackets.mp4", "file[[with]]brackets.mp4")]
[InlineData("normal-file.mp4", "normal-file.mp4")]
[InlineData("file_with_underscores.mp4", "file_with_underscores.mp4")]
[InlineData("file with spaces.mp4", "file with spaces.mp4")]
[InlineData("[brackets].mp4", "[[brackets]].mp4")]
public void EscapeMarkup_WhenCalledWithVariousInputs_ItShouldProperlyEscapeSquareBrackets(string input, string expected)
{
var result = input.EscapeMarkup();
result.Should().Be(expected);
}
}
@@ -9,13 +9,15 @@ public class AudioExtractorTests
{ {
using var testVideo = TestData.GetTestVideo(); using var testVideo = TestData.GetTestVideo();
using var extractedAudio = TestData.GetExtractedAudio(); using var extractedAudio = TestData.GetExtractedAudio();
using var audioStream = new MemoryStream();
var result = await _sut.ExtractMp3FromMp4Async(testVideo); var result = await _sut.ExtractMp3FromMp4Async(testVideo, audioStream);
var audioBytes = await ConvertStreamToBytesAsync(extractedAudio); var audioBytes = await ConvertStreamToBytesAsync(extractedAudio);
var resultBytes = await ConvertStreamToBytesAsync(result); var resultBytes = await ConvertStreamToBytesAsync(result);
resultBytes.Should().Equal(audioBytes); resultBytes.Should().Equal(audioBytes);
result.Should().BeSameAs(audioStream);
} }
private static async Task<byte[]> ConvertStreamToBytesAsync(Stream stream) private static async Task<byte[]> ConvertStreamToBytesAsync(Stream stream)
@@ -25,7 +25,7 @@ public class AudioExtractorTests
[Fact] [Fact]
public async Task ExtractMp3FromMp4Async_WhenVideoIsNull_ItShouldThrow() public async Task ExtractMp3FromMp4Async_WhenVideoIsNull_ItShouldThrow()
{ {
var action = async () => await _sut.ExtractMp3FromMp4Async(null!); var action = async () => await _sut.ExtractMp3FromMp4Async(null!, new MemoryStream());
await action.Should().ThrowAsync<ArgumentNullException>(); await action.Should().ThrowAsync<ArgumentNullException>();
} }
@@ -36,7 +36,7 @@ public class AudioExtractorTests
var mockStream = new Mock<Stream>(); var mockStream = new Mock<Stream>();
mockStream.Setup(s => s.CanRead).Returns(false); mockStream.Setup(s => s.CanRead).Returns(false);
var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object); var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object, new MemoryStream());
await action.Should().ThrowAsync<ArgumentException>(); await action.Should().ThrowAsync<ArgumentException>();
} }
@@ -48,7 +48,7 @@ public class AudioExtractorTests
mockStream.Setup(s => s.CanRead).Returns(true); mockStream.Setup(s => s.CanRead).Returns(true);
mockStream.Setup(s => s.CanSeek).Returns(false); mockStream.Setup(s => s.CanSeek).Returns(false);
var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object); var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object, new MemoryStream());
await action.Should().ThrowAsync<ArgumentException>(); await action.Should().ThrowAsync<ArgumentException>();
} }
@@ -69,7 +69,7 @@ public class AudioExtractorTests
) )
.ThrowsAsync(new Exception()); .ThrowsAsync(new Exception());
var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object); var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object, new MemoryStream());
await action.Should().ThrowAsync<FailedAudioExtractionException>(); await action.Should().ThrowAsync<FailedAudioExtractionException>();
} }
@@ -90,7 +90,7 @@ public class AudioExtractorTests
) )
.ReturnsAsync(false); .ReturnsAsync(false);
var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object); var action = async () => await _sut.ExtractMp3FromMp4Async(mockStream.Object, new MemoryStream());
await action.Should().ThrowAsync<FailedAudioExtractionException>(); await action.Should().ThrowAsync<FailedAudioExtractionException>();
} }
@@ -111,7 +111,7 @@ public class AudioExtractorTests
) )
.ReturnsAsync(true); .ReturnsAsync(true);
var result = await _sut.ExtractMp3FromMp4Async(mockStream.Object); var result = await _sut.ExtractMp3FromMp4Async(mockStream.Object, new MemoryStream());
result.Should().BeAssignableTo<Stream>(); result.Should().BeAssignableTo<Stream>();
result.Should().BeOfType<MemoryStream>(); result.Should().BeOfType<MemoryStream>();
@@ -137,7 +137,7 @@ public class AudioExtractorTests
) )
.ReturnsAsync(true); .ReturnsAsync(true);
await _sut.ExtractMp3FromMp4Async(stream); await _sut.ExtractMp3FromMp4Async(stream, new MemoryStream());
stream.Position.Should().Be(positionToRead); stream.Position.Should().Be(positionToRead);
} }