Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce allocation when reading PNG chunks #286

Merged
merged 1 commit into from
May 7, 2021
Merged
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
21 changes: 19 additions & 2 deletions MetadataExtractor/Formats/Png/PngChunkReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
// Miscellaneous information: bKGD, hIST, pHYs, sPLT
// Time information: tIME
//
// CHUNK READING
//
// Only chunk data for types specified in desiredChunkTypes is extracted.
// For empty chunk type list NO data is copied from source stream.
// For null chunk type list ALL data is copied from source stream.
//

// network byte order
reader = reader.WithByteOrder(isMotorolaByteOrder: true);
Expand All @@ -68,7 +74,17 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
throw new PngProcessingException("PNG chunk length exceeds maximum");
var chunkType = new PngChunkType(reader.GetBytes(4));
var willStoreChunk = desiredChunkTypes == null || desiredChunkTypes.Contains(chunkType);
var chunkData = reader.GetBytes(chunkDataLength);

byte[]? chunkData;
if (willStoreChunk)
{
chunkData = reader.GetBytes(chunkDataLength);
}
else
{
chunkData = null;
reader.Skip(chunkDataLength);
}

// Skip the CRC bytes at the end of the chunk
// TODO consider verifying the CRC value to determine if we're processing bad data
Expand All @@ -85,7 +101,8 @@ public IEnumerable<PngChunk> Extract(SequentialReader reader, ICollection<PngChu
if (chunkType.Equals(PngChunkType.IEND))
seenImageTrailer = true;

if (willStoreChunk)
// chunkData will be null if we aren't interested in this chunk
if (chunkData is not null)
chunks.Add(new PngChunk(chunkType, chunkData));

seenChunkTypes.Add(chunkType);
Expand Down