Skip to content

Commit

Permalink
fix: ffmpeg run with timeout and cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
ckeller81 committed Aug 27, 2023
1 parent 536bd3c commit 6ecd837
Showing 1 changed file with 25 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/Backend2023/Modules/AudioTransformer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,43 @@ public async Task TransformWebAudioStreamToWavFileWithFfmpeg(Stream webAudioStre
};

// Start the process
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using (Process process = new Process())
{
process.StartInfo = psi;
process.Start(); // Handle the output and error streams
process.OutputDataReceived += (sender, e) => _logger.LogInformation(e.Data);
process.ErrorDataReceived += (sender, e) => _logger.LogError(e.Data);
process.OutputDataReceived += LogOutputData;
process.ErrorDataReceived += LogErrorData;

process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await process.WaitForExitAsync();
await process.WaitForExitAsync(cts.Token);

if (cts.IsCancellationRequested)
{
_logger.LogError("Timeout executing ffmpeg after 30sec.");
process.Close();
}

process.CancelOutputRead();
process.CancelErrorRead();
process.OutputDataReceived -= LogOutputData;
process.ErrorDataReceived -= LogErrorData;

_logger.LogInformation("Process exited with code: " + process.ExitCode);
}
}

private void LogOutputData(object sender, DataReceivedEventArgs e)
{
_logger.LogInformation(e.Data);
}

private void LogErrorData(object sender, DataReceivedEventArgs e)
{
_logger.LogError(e.Data);
}

public async Task TransformWebAudioStreamToWavFileOld(Stream webAudioStream, string fileName)
{
webAudioStream.Seek(0, SeekOrigin.Begin);
Expand Down

0 comments on commit 6ecd837

Please sign in to comment.