chore: Extract to convertMTLTextureToSkImage

This commit is contained in:
Marc Rousavy 2023-07-03 12:41:26 +02:00
parent 820db3ca9e
commit 82eaf9594f
3 changed files with 52 additions and 40 deletions

View File

@ -11,6 +11,8 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h> #import <AVFoundation/AVFoundation.h>
#import <MetalKit/MetalKit.h>
#import <include/gpu/GrRecordingContext.h> #import <include/gpu/GrRecordingContext.h>
#import "SkImage.h" #import "SkImage.h"
@ -26,6 +28,10 @@ public:
Convert a CMSampleBuffer to an SkImage. Format has to be RGB. Convert a CMSampleBuffer to an SkImage. Format has to be RGB.
*/ */
static sk_sp<SkImage> convertCMSampleBufferToSkImage(GrRecordingContext* context, CMSampleBufferRef sampleBuffer); static sk_sp<SkImage> convertCMSampleBufferToSkImage(GrRecordingContext* context, CMSampleBufferRef sampleBuffer);
/**
Convert a MTLTexture to an SkImage. Format has to be RGB.
*/
static sk_sp<SkImage> convertMTLTextureToSkImage(GrRecordingContext* context, id<MTLTexture> mtlTexture);
/** /**
Creates a Center Crop Transformation Rect so that the source rect fills (aspectRatio: cover) the destination rect. Creates a Center Crop Transformation Rect so that the source rect fills (aspectRatio: cover) the destination rect.
The return value should be passed as a sourceRect to a canvas->draw...Rect(..) function, destinationRect should stay the same. The return value should be passed as a sourceRect to a canvas->draw...Rect(..) function, destinationRect should stay the same.

View File

@ -86,6 +86,20 @@ sk_sp<SkImage> SkImageHelpers::convertCMSampleBufferToSkImage(GrRecordingContext
return image; return image;
} }
sk_sp<SkImage> SkImageHelpers::convertMTLTextureToSkImage(GrRecordingContext* context, id<MTLTexture> texture) {
// Convert the rendered MTLTexture to an SkImage
GrMtlTextureInfo textureInfo;
textureInfo.fTexture.retain((__bridge void*)texture);
GrBackendTexture backendTexture(texture.width, texture.height, GrMipmapped::kNo, textureInfo);
auto image = SkImages::AdoptTextureFrom(context,
backendTexture,
kTopLeft_GrSurfaceOrigin,
kBGRA_8888_SkColorType,
kOpaque_SkAlphaType,
SkColorSpace::MakeSRGB());
return image;
}
SkRect SkImageHelpers::createCenterCropRect(SkRect sourceRect, SkRect destinationRect) { SkRect SkImageHelpers::createCenterCropRect(SkRect sourceRect, SkRect destinationRect) {
SkSize src; SkSize src;
if (destinationRect.width() / destinationRect.height() > sourceRect.width() / sourceRect.height()) { if (destinationRect.width() / destinationRect.height() > sourceRect.width() / sourceRect.height()) {

View File

@ -23,7 +23,7 @@ SkiaMetalCanvasProvider::SkiaMetalCanvasProvider(): std::enable_shared_from_this
_layerContext.layer.pixelFormat = MTLPixelFormatBGRA8Unorm; _layerContext.layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
// Set up DisplayLink // Set up DisplayLink
_layerContext.displayLink = [[VisionDisplayLink alloc] init]; _layerContext.displayLink = [[VisionDisplayLink alloc] init];
_isValid = true; _isValid = true;
} }
@ -65,16 +65,16 @@ void SkiaMetalCanvasProvider::render() {
if (_width == -1 && _height == -1) { if (_width == -1 && _height == -1) {
return; return;
} }
if (!_hasNewFrame) { if (!_hasNewFrame) {
// No new Frame has arrived in the meantime. // No new Frame has arrived in the meantime.
// We don't need to re-draw the texture to the screen if nothing has changed, abort. // We don't need to re-draw the texture to the screen if nothing has changed, abort.
return; return;
} }
@autoreleasepool { @autoreleasepool {
auto context = _layerContext.skiaContext.get(); auto context = _layerContext.skiaContext.get();
// Create a Skia Surface from the CAMetalLayer (use to draw to the View) // Create a Skia Surface from the CAMetalLayer (use to draw to the View)
GrMTLHandle drawableHandle; GrMTLHandle drawableHandle;
auto surface = SkSurface::MakeFromCAMetalLayer(context, auto surface = SkSurface::MakeFromCAMetalLayer(context,
@ -88,17 +88,17 @@ void SkiaMetalCanvasProvider::render() {
if (surface == nullptr || surface->getCanvas() == nullptr) { if (surface == nullptr || surface->getCanvas() == nullptr) {
throw std::runtime_error("Skia surface could not be created from parameters."); throw std::runtime_error("Skia surface could not be created from parameters.");
} }
auto canvas = surface->getCanvas(); auto canvas = surface->getCanvas();
// Lock the Mutex so we can operate on the Texture atomically without // Lock the Mutex so we can operate on the Texture atomically without
// renderFrameToCanvas() overwriting in between from a different thread // renderFrameToCanvas() overwriting in between from a different thread
std::unique_lock lock(_textureMutex); std::unique_lock lock(_textureMutex);
// Get the texture // Get the texture
auto texture = _offscreenContext.texture; auto texture = _offscreenContext.texture;
if (texture == nil) return; if (texture == nil) return;
// Calculate Center Crop (aspectRatio: cover) transform // Calculate Center Crop (aspectRatio: cover) transform
auto sourceRect = SkRect::MakeXYWH(0, 0, texture.width, texture.height); auto sourceRect = SkRect::MakeXYWH(0, 0, texture.width, texture.height);
auto destinationRect = SkRect::MakeXYWH(0, 0, surface->width(), surface->height()); auto destinationRect = SkRect::MakeXYWH(0, 0, surface->width(), surface->height());
@ -109,40 +109,32 @@ void SkiaMetalCanvasProvider::render() {
// The Canvas is equal to the View size, where-as the Frame has a different size (e.g. 4k) // The Canvas is equal to the View size, where-as the Frame has a different size (e.g. 4k)
// We scale the Canvas to the exact dimensions of the Frame so that the user can use the Frame as a coordinate system // We scale the Canvas to the exact dimensions of the Frame so that the user can use the Frame as a coordinate system
canvas->save(); canvas->save();
auto scaleW = static_cast<double>(surface->width()) / texture.width; auto scaleW = static_cast<double>(surface->width()) / texture.width;
auto scaleH = static_cast<double>(surface->height()) / texture.height; auto scaleH = static_cast<double>(surface->height()) / texture.height;
auto scale = MAX(scaleW, scaleH); auto scale = MAX(scaleW, scaleH);
canvas->scale(scale, scale); canvas->scale(scale, scale);
canvas->translate(offsetX, offsetY); canvas->translate(offsetX, offsetY);
// Convert the rendered MTLTexture to an SkImage // Convert the rendered MTLTexture to an SkImage
GrMtlTextureInfo textureInfo; auto image = SkImageHelpers::convertMTLTextureToSkImage(context, texture);
textureInfo.fTexture.retain((__bridge void*)texture);
GrBackendTexture backendTexture(texture.width, texture.height, GrMipmapped::kNo, textureInfo);
auto image = SkImage::MakeFromTexture(context,
backendTexture,
kTopLeft_GrSurfaceOrigin,
kBGRA_8888_SkColorType,
kOpaque_SkAlphaType,
SkColorSpace::MakeSRGB());
// Draw the Texture (Frame) to the Canvas // Draw the Texture (Frame) to the Canvas
canvas->drawImage(image, 0, 0); canvas->drawImage(image, 0, 0);
// Restore the scale & transform // Restore the scale & transform
canvas->restore(); canvas->restore();
surface->flushAndSubmit(); surface->flushAndSubmit();
// Pass the drawable into the Metal Command Buffer and submit it to the GPU // Pass the drawable into the Metal Command Buffer and submit it to the GPU
id<CAMetalDrawable> drawable = (__bridge id<CAMetalDrawable>)drawableHandle; id<CAMetalDrawable> drawable = (__bridge id<CAMetalDrawable>)drawableHandle;
id<MTLCommandBuffer> commandBuffer([_layerContext.commandQueue commandBuffer]); id<MTLCommandBuffer> commandBuffer([_layerContext.commandQueue commandBuffer]);
[commandBuffer presentDrawable:drawable]; [commandBuffer presentDrawable:drawable];
[commandBuffer commit]; [commandBuffer commit];
_hasNewFrame = false; _hasNewFrame = false;
lock.unlock(); lock.unlock();
} }
} }
@ -170,14 +162,14 @@ void SkiaMetalCanvasProvider::renderFrameToCanvas(CMSampleBufferRef sampleBuffer
if (pixelBuffer == nil) { if (pixelBuffer == nil) {
throw std::runtime_error("drawFrame: Pixel Buffer is corrupt/empty."); throw std::runtime_error("drawFrame: Pixel Buffer is corrupt/empty.");
} }
// Lock Mutex to block the runLoop from overwriting the _currentDrawable // Lock Mutex to block the runLoop from overwriting the _currentDrawable
std::unique_lock lock(_textureMutex); std::unique_lock lock(_textureMutex);
// Get the Metal Texture we use for in-memory drawing // Get the Metal Texture we use for in-memory drawing
auto texture = getTexture(CVPixelBufferGetWidth(pixelBuffer), auto texture = getTexture(CVPixelBufferGetWidth(pixelBuffer),
CVPixelBufferGetHeight(pixelBuffer)); CVPixelBufferGetHeight(pixelBuffer));
// Get & Lock the writeable Texture from the Metal Drawable // Get & Lock the writeable Texture from the Metal Drawable
GrMtlTextureInfo fbInfo; GrMtlTextureInfo fbInfo;
fbInfo.fTexture.retain((__bridge void*)texture); fbInfo.fTexture.retain((__bridge void*)texture);
@ -185,9 +177,9 @@ void SkiaMetalCanvasProvider::renderFrameToCanvas(CMSampleBufferRef sampleBuffer
texture.height, texture.height,
1, 1,
fbInfo); fbInfo);
auto context = _offscreenContext.skiaContext.get(); auto context = _offscreenContext.skiaContext.get();
// Create a Skia Surface from the writable Texture // Create a Skia Surface from the writable Texture
auto surface = SkSurface::MakeFromBackendRenderTarget(context, auto surface = SkSurface::MakeFromBackendRenderTarget(context,
backendRT, backendRT,
@ -195,35 +187,35 @@ void SkiaMetalCanvasProvider::renderFrameToCanvas(CMSampleBufferRef sampleBuffer
kBGRA_8888_SkColorType, kBGRA_8888_SkColorType,
nullptr, nullptr,
nullptr); nullptr);
if (surface == nullptr || surface->getCanvas() == nullptr) { if (surface == nullptr || surface->getCanvas() == nullptr) {
throw std::runtime_error("Skia surface could not be created from parameters."); throw std::runtime_error("Skia surface could not be created from parameters.");
} }
// Lock the Frame's PixelBuffer for the duration of the Frame Processor so the user can safely do operations on it // Lock the Frame's PixelBuffer for the duration of the Frame Processor so the user can safely do operations on it
CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
// Converts the CMSampleBuffer to an SkImage - RGB. // Converts the CMSampleBuffer to an SkImage - RGB.
auto image = SkImageHelpers::convertCMSampleBufferToSkImage(context, sampleBuffer); auto image = SkImageHelpers::convertCMSampleBufferToSkImage(context, sampleBuffer);
auto canvas = surface->getCanvas(); auto canvas = surface->getCanvas();
// Clear everything so we keep it at a clean state // Clear everything so we keep it at a clean state
canvas->clear(SkColors::kBlack); canvas->clear(SkColors::kBlack);
// Draw the Image into the Frame (aspectRatio: cover) // Draw the Image into the Frame (aspectRatio: cover)
// The Frame Processor might draw the Frame again (through render()) to pass a custom paint/shader, // The Frame Processor might draw the Frame again (through render()) to pass a custom paint/shader,
// but that'll just overwrite the existing one - no need to worry. // but that'll just overwrite the existing one - no need to worry.
canvas->drawImage(image, 0, 0); canvas->drawImage(image, 0, 0);
// Call the JS Frame Processor. // Call the JS Frame Processor.
drawCallback(canvas); drawCallback(canvas);
// Flush all appended operations on the canvas and commit it to the SkSurface // Flush all appended operations on the canvas and commit it to the SkSurface
surface->flushAndSubmit(); surface->flushAndSubmit();
_hasNewFrame = true; _hasNewFrame = true;
lock.unlock(); lock.unlock();
CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly); CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
} }