Parallelize capture saving to disk for ImageCapture #1409
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds additional capture consumer tasks, which are hinted to run in parallel. These tasks speed up the encoding and saving process, which was previously a bottleneck causing large memory usage and long waiting times at the end of recording. The degree of parallelization is set conservatively to avoid overwhelming the CPU on weaker systems. It is currently hardcoded at 25% of cpu cores (16 cores => 4 tasks, 12 cores => 3 tasks, 8 cores => 2 tasks, <8 cores => 1 task, ...)
This change is implemented for ImageCapture and DirectImageCapture, other capture methods are unchanged.
Performance
Before this change, recording 2 minutes of 1080p 60hz would spike my RAM usage up to 30GB and take over a minute of "Stopping..." before proceeding to the editor.
After this change, I can record 4k 60hz with RAM usage below 800MB and the editor immediately opens after stopping recording.
Safety
Capture()andSave()already run async with a blocking collection, which made it easier to implement this change. However, when saving multiple frames in parallel, multiple frames may try to append toProject.Framesat the same time. I've put a lock around that line to avoid race conditions corrupting the list. Also, a later frame may finish before an earlier one, so frames may be saved out of order. Therefore, I've added a post-process sorting step to ensure a correct order ofProject.Frames.