Skip to content

Commit

Permalink
perf(heif): remove unnecessary array copy
Browse files Browse the repository at this point in the history
  • Loading branch information
gotson committed Oct 3, 2023
1 parent bc729dc commit 3a20f16
Showing 1 changed file with 6 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import java.io.IOException;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;

import static com.github.gotson.nightmonkeys.common.imageio.IIOUtil.byteArrayFromStream;
import static com.github.gotson.nightmonkeys.heif.lib.panama.heif_h.C_INT;
Expand All @@ -29,6 +31,8 @@
public class Heif {
private static final Logger LOGGER = LoggerFactory.getLogger(Heif.class);

private static final ValueLayout.OfInt pixelLayout = C_INT.withOrder(ByteOrder.BIG_ENDIAN);

public static boolean isLibVersionSupported() {
// heif_get_version_number_minor() does not return the correct value
int versionBcd = heif_h.heif_get_version_number();
Expand Down Expand Up @@ -116,7 +120,7 @@ public static void decode(final ImageInputStream stream, BasicInfo info, final W

var imageIds = arena.allocateArray(C_INT, info.frameCount());
heif_h.heif_context_get_list_of_top_level_image_IDs(heifContext, imageIds, info.frameCount());
var imageId = imageIds.get(C_INT, imageIndex * 4L);
var imageId = imageIds.get(C_INT, imageIndex * C_INT.byteSize());

var handlePtr = arena.allocate(C_POINTER);
checkError(heif_h.heif_context_get_image_handle(arena, heifContext, imageId, handlePtr));
Expand All @@ -128,13 +132,7 @@ public static void decode(final ImageInputStream stream, BasicInfo info, final W
checkError(heif_h.heif_decode_image(arena, handle, imagePtr, heif_colorspace_RGB(), heif_chroma_interleaved_RGBA(), MemorySegment.NULL));
var image = imagePtr.get(C_POINTER, 0);


var pixels = heif_h.heif_image_get_plane_readonly(image, heif_channel_interleaved(), MemorySegment.NULL);

var imageSizeBytes = width * height * 4;
var pixelsBuffer = pixels.asSlice(0, imageSizeBytes).asByteBuffer().asIntBuffer();
var pixelsArray = new int[width * height];
pixelsBuffer.get(pixelsArray);
var pixelsRaster = new int[Math.min(width, raster.getWidth()) * Math.min(height, raster.getHeight())];

var sourceRegion = param != null ? param.getSourceRegion() : null;
Expand All @@ -149,9 +147,8 @@ public static void decode(final ImageInputStream stream, BasicInfo info, final W
if (offset >= pixelsRaster.length) break;
for (int col = sourceRegion.x + ssOffX; col < sourceRegion.x + sourceRegion.width; col += ssX) {
if (offset >= pixelsRaster.length) break;
int pixel = pixelsArray[(row * width) + col];
int pixel = pixels.get(pixelLayout, (((long) row * width) + col) * pixelLayout.byteSize());
pixelsRaster[offset++] = pixel;

}
}

Expand Down

0 comments on commit 3a20f16

Please sign in to comment.