Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 46 additions & 14 deletions ScreenToGif/Capture/BaseCapture.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using ScreenToGif.Model;
Expand Down Expand Up @@ -65,6 +66,11 @@ public abstract class BaseCapture : ICapture

protected BlockingCollection<FrameInfo> BlockingCollection { get; private set; } = new();

/// <summary>
/// If true, multiple frames can be saved in parallel
/// </summary>
protected virtual bool SupportsParallelSaving => false;

#endregion

~BaseCapture()
Expand Down Expand Up @@ -94,22 +100,29 @@ public virtual void Start(int delay, int left, int top, int width, int height, d
BlockingCollection ??= new BlockingCollection<FrameInfo>();

//Spin up a Task to consume the BlockingCollection.
_task = Task.Factory.StartNew(() =>
int NumConsumers = GetConsumerCount();
List<Task> consumers = new(NumConsumers);
for (int i = 0; i < NumConsumers; ++i)
{
try
{
while (true)
Save(BlockingCollection.Take());
}
catch (InvalidOperationException)
consumers.Add(Task.Factory.StartNew(() =>
{
//It means that Take() was called on a completed collection.
}
catch (Exception e)
{
Application.Current.Dispatcher.Invoke(() => OnError?.Invoke(e));
}
});
try
{
while (true)
Save(BlockingCollection.Take());
}
catch (InvalidOperationException)
{
//It means that Take() was called on a completed collection.
}
catch (Exception e)
{
Application.Current.Dispatcher.Invoke(() => OnError?.Invoke(e));
}
}, TaskCreationOptions.LongRunning));
}

_task = Task.WhenAll(consumers);

WasStarted = true;
IsAcceptingFrames = true;
Expand All @@ -121,6 +134,25 @@ public virtual void ResetConfiguration()
public virtual void Save(FrameInfo info)
{ }

/// <summary>
/// Return the amount of consumers that should be used simultaneously,
/// based on system resources.
/// </summary>
/// <returns>Number of consumer tasks to spawn</returns>
protected virtual int GetConsumerCount()
{
if (!SupportsParallelSaving)
{
return 1;
}

const int minCpuCount = 1;
const int maxCpuUtilizationPercentage = 25;

int processorCount = Environment.ProcessorCount;
return Math.Max(processorCount * maxCpuUtilizationPercentage / 100, minCpuCount);
}

public virtual int Capture(FrameInfo frame)
{
return 0;
Expand Down
15 changes: 14 additions & 1 deletion ScreenToGif/Capture/DirectImageCapture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ internal class DirectImageCapture : BaseCapture
/// </summary>
protected internal bool MajorCrashHappened = false;

protected override bool SupportsParallelSaving => true;

private readonly object _projectLock = new object();

#endregion

public override void Start(int delay, int left, int top, int width, int height, double dpi, ProjectInfo project)
Expand Down Expand Up @@ -374,6 +378,7 @@ public override int Capture(FrameInfo frame)
bitmap.UnlockBits(mapDest);

//Set frame details.
frame.Index = FrameCount;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

frame.Index was only set later, after capturing. But because we need it to sort the frame list, we need the index to be set early.

FrameCount++;
frame.Path = $"{Project.FullPath}{FrameCount}.png";
frame.Delay = FrameRate.GetMilliseconds();
Expand Down Expand Up @@ -562,6 +567,7 @@ public override int CaptureWithCursor(FrameInfo frame)
bitmap.UnlockBits(mapDest);

//Set frame details.
frame.Index = FrameCount;
FrameCount++;
frame.Path = $"{Project.FullPath}{FrameCount}.png";
frame.Delay = FrameRate.GetMilliseconds();
Expand Down Expand Up @@ -709,6 +715,7 @@ public override int ManualCapture(FrameInfo frame, bool showCursor = false)
bitmap.UnlockBits(mapDest);

//Set frame details.
frame.Index = FrameCount;
FrameCount++;
frame.Path = $"{Project.FullPath}{FrameCount}.png";
frame.Delay = FrameRate.GetMilliseconds();
Expand Down Expand Up @@ -995,7 +1002,10 @@ public override void Save(FrameInfo frame)
frame.Image?.Dispose();
frame.Image = null;

Project.Frames.Add(frame);
lock (_projectLock)
{
Project.Frames.Add(frame);
}
}

public override async Task Stop()
Expand All @@ -1006,6 +1016,9 @@ public override async Task Stop()
DisposeInternal();

await base.Stop();

// If frames were saved in parallel, they may have been stored out of order, so we sort them here
Project.Frames.Sort((a, b) => a.Index.CompareTo(b.Index));
}

internal void DisposeInternal()
Expand Down
15 changes: 14 additions & 1 deletion ScreenToGif/Capture/ImageCapture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using ScreenToGif.Native.Structs;
using ScreenToGif.Util;
using ScreenToGif.Util.Settings;
using SharpDX.Direct3D11;
using Image = System.Drawing.Image;

namespace ScreenToGif.Capture;
Expand All @@ -21,12 +22,16 @@ internal class ImageCapture : BaseCapture
protected IntPtr CompatibleBitmap;
private IntPtr _oldBitmap;

private readonly object _projectLock = new object();

protected int CursorStep { get; set; }

private CopyPixelOperations PixelOperations { get; set; }

#endregion

protected override bool SupportsParallelSaving => true;

public override void Start(int delay, int left, int top, int width, int height, double scale, ProjectInfo project)
{
base.Start(delay, left, top, width, height, scale, project);
Expand Down Expand Up @@ -63,6 +68,7 @@ public override int Capture(FrameInfo frame)
return FrameCount;

//Set frame details.
frame.Index = FrameCount;
FrameCount++;
frame.Path = $"{Project.FullPath}{FrameCount}.png";
frame.Delay = FrameRate.GetMilliseconds();
Expand Down Expand Up @@ -146,6 +152,7 @@ public override int CaptureWithCursor(FrameInfo frame)
#endregion

//Set frame details.
frame.Index = FrameCount;
FrameCount++;
frame.Path = $"{Project.FullPath}{FrameCount}.png";
frame.Delay = FrameRate.GetMilliseconds();
Expand Down Expand Up @@ -174,7 +181,10 @@ public override void Save(FrameInfo frame)
frame.Image.Dispose();
frame.Image = null;

Project.Frames.Add(frame);
lock(_projectLock)
{
Project.Frames.Add(frame);
}
}

public override async Task Stop()
Expand All @@ -195,5 +205,8 @@ public override async Task Stop()
{
LogWriter.Log(e, "Impossible to stop and clean resources used by the recording.");
}

// If frames were saved in parallel, they may have been stored out of order, so we sort them here
Project.Frames.Sort((a, b) => a.Index.CompareTo(b.Index));
}
}