PanelColorizerBridge.mm
iosApp/PanelColorizerBridge.mm
1#import "PanelColorizerBridge.h"2#import <ImageIO/ImageIO.h>3#import <UIKit/UIKit.h>4#import <onnxruntime.h>56NSData *YokanDecodePanel(NSData *data, int maxSide, int *width, int *height) {7 @autoreleasepool {8 CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nullptr);9 if (!source) return nil;10 NSDictionary *options = @{11 (NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,12 (NSString *)kCGImageSourceThumbnailMaxPixelSize: @(maxSide),13 (NSString *)kCGImageSourceCreateThumbnailWithTransform: @YES,14 (NSString *)kCGImageSourceShouldCacheImmediately: @YES,15 };16 CGImageRef image = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options);17 CFRelease(source);18 if (!image) return nil;19 *width = (int)CGImageGetWidth(image); *height = (int)CGImageGetHeight(image);20 if (*width <= 0 || *height <= 0 || *width > maxSide || *height > maxSide) { CGImageRelease(image); return nil; }21 NSMutableData *pixels = [NSMutableData dataWithLength:(NSUInteger)(*width) * (*height) * 4];22 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();23 CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, *width, *height, 8, *width * 4, colorSpace,24 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);25 CGColorSpaceRelease(colorSpace);26 if (!context) { CGImageRelease(image); return nil; }27 CGContextSetRGBFillColor(context, 1, 1, 1, 1);28 CGContextFillRect(context, CGRectMake(0, 0, *width, *height));29 CGContextDrawImage(context, CGRectMake(0, 0, *width, *height), image);30 CGContextRelease(context); CGImageRelease(image);31 return pixels;32 }33}3435NSData *YokanDecodePanelFullPage(NSData *data, int *width, int *height, int *failureCode) {36 @autoreleasepool {37 *failureCode = 1;38 CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nullptr);39 if (!source) return nil;40 if (CGImageSourceGetStatus(source) != kCGImageStatusComplete ||41 CGImageSourceGetStatusAtIndex(source, 0) != kCGImageStatusComplete) {42 CFRelease(source);43 return nil;44 }45 NSDictionary *properties = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source, 0, nullptr));46 NSNumber *sourceWidth = properties[(NSString *)kCGImagePropertyPixelWidth];47 NSNumber *sourceHeight = properties[(NSString *)kCGImagePropertyPixelHeight];48 NSDictionary *tiffProperties = properties[(NSString *)kCGImagePropertyTIFFDictionary];49 NSNumber *orientationValue = properties[(NSString *)kCGImagePropertyOrientation] ?:50 tiffProperties[(NSString *)kCGImagePropertyTIFFOrientation];51 uint64_t rawWidth = sourceWidth.unsignedLongLongValue;52 uint64_t rawHeight = sourceHeight.unsignedLongLongValue;53 if (!sourceWidth || !sourceHeight || rawWidth == 0 || rawHeight == 0 || rawWidth > 4096 || rawHeight > 4096 ||54 rawWidth * rawHeight > 8000000ULL) {55 if (sourceWidth && sourceHeight && rawWidth > 0 && rawHeight > 0) *failureCode = 2;56 CFRelease(source);57 return nil;58 }59 NSUInteger orientation = orientationValue ? orientationValue.unsignedIntegerValue : 1;60 if (orientation < 1 || orientation > 8) {61 CFRelease(source);62 return nil;63 }64 // ImageIO's transformed thumbnail preserves full resolution here: the validated source is65 // already within maxPixelSize. Its transform applies EXIF orientation before rasterization.66 NSDictionary *options = @{67 (NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,68 (NSString *)kCGImageSourceThumbnailMaxPixelSize: @4096,69 (NSString *)kCGImageSourceCreateThumbnailWithTransform: @YES,70 (NSString *)kCGImageSourceShouldCacheImmediately: @YES,71 };72 CGImageRef image = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef)options);73 CFRelease(source);74 if (!image) return nil;75 size_t decodedWidth = CGImageGetWidth(image);76 size_t decodedHeight = CGImageGetHeight(image);77 if (decodedWidth == 0 || decodedHeight == 0 || decodedWidth > 4096 || decodedHeight > 4096 ||78 (uint64_t)decodedWidth * (uint64_t)decodedHeight > 8000000ULL) {79 *failureCode = 2;80 CGImageRelease(image);81 return nil;82 }83 *width = (int)decodedWidth;84 *height = (int)decodedHeight;85 NSMutableData *pixels = [NSMutableData dataWithLength:(NSUInteger)decodedWidth * decodedHeight * 4];86 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();87 CGContextRef context = CGBitmapContextCreate(pixels.mutableBytes, *width, *height, 8, *width * 4, colorSpace,88 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);89 CGColorSpaceRelease(colorSpace);90 if (!context) { CGImageRelease(image); return nil; }91 CGContextDrawImage(context, CGRectMake(0, 0, *width, *height), image);92 // CGBitmapContext stores premultiplied RGBA; expose straight RGBA to Kotlin/ARGB.93 uint8_t *rgba = (uint8_t *)pixels.mutableBytes;94 NSUInteger pixelCount = (NSUInteger)decodedWidth * decodedHeight;95 for (NSUInteger i = 0; i < pixelCount; i++) {96 uint8_t alpha = rgba[i * 4 + 3];97 if (alpha == 0) {98 rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = 0;99 } else if (alpha < 255) {100 for (NSUInteger channel = 0; channel < 3; channel++) {101 rgba[i * 4 + channel] = (uint8_t)MIN(255, (rgba[i * 4 + channel] * 255 + alpha / 2) / alpha);102 }103 }104 }105 CGContextRelease(context);106 CGImageRelease(image);107 *failureCode = 0;108 return pixels;109 }110}111112NSData *YokanEncodePanel(const uint32_t *argb, int width, int height) {113 @autoreleasepool {114 if (width <= 0 || height <= 0 || width > 4096 || height > 4096 ||115 (uint64_t)width * (uint64_t)height > 8000000ULL) return nil;116 NSMutableData *data = [NSMutableData dataWithLength:(NSUInteger)width * height * 4];117 uint8_t *pixels = (uint8_t *)data.mutableBytes;118 for (int i = 0; i < width * height; i++) {119 uint8_t alpha = (argb[i] >> 24) & 255;120 pixels[i * 4 + 2] = ((argb[i] & 255) * alpha + 127) / 255;121 pixels[i * 4 + 3] = alpha;122 pixels[i * 4] = (((argb[i] >> 16) & 255) * alpha + 127) / 255;123 pixels[i * 4 + 1] = (((argb[i] >> 8) & 255) * alpha + 127) / 255;124 }125 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();126 CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * 4, colorSpace,127 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);128 CGColorSpaceRelease(colorSpace);129 if (!context) return nil;130 CGImageRef image = CGBitmapContextCreateImage(context);131 NSData *png = image ? UIImagePNGRepresentation([UIImage imageWithCGImage:image]) : nil;132 if (image) CGImageRelease(image);133 CGContextRelease(context);134 return png;135 }136}137138BOOL YokanInferPanel(NSString *modelPath, const float *input, float *output, int width, int height) {139 @autoreleasepool {140 if (width <= 0 || height <= 0 || width % 32 != 0 || height % 32 != 0) return NO;141 NSError *error = nil;142 ORTEnv *env = [[ORTEnv alloc] initWithLoggingLevel:ORTLoggingLevelWarning error:&error];143 ORTSessionOptions *options = [[ORTSessionOptions alloc] initWithError:&error];144 if (!env || !options || ![options setIntraOpNumThreads:1 error:&error] ||145 ![options setGraphOptimizationLevel:ORTGraphOptimizationLevelNone error:&error] ||146 ![options addConfigEntryWithKey:@"session.disable_prepacking" value:@"1" error:&error]) return NO;147 ORTSession *session = [[ORTSession alloc] initWithEnv:env modelPath:modelPath sessionOptions:options error:&error];148 if (!session) return NO;149 NSMutableData *inputData = [NSMutableData dataWithBytes:input length:5 * width * height * sizeof(float)];150 NSMutableData *outputData = [NSMutableData dataWithLength:3 * width * height * sizeof(float)];151 ORTValue *inputTensor = [[ORTValue alloc] initWithTensorData:inputData elementType:ORTTensorElementDataTypeFloat152 shape:@[@1, @5, @(height), @(width)] error:&error];153 ORTValue *outputTensor = [[ORTValue alloc] initWithTensorData:outputData elementType:ORTTensorElementDataTypeFloat154 shape:@[@1, @3, @(height), @(width)] error:&error];155 if (!inputTensor || !outputTensor) return NO;156 BOOL success = [session runWithInputs:@{@"input":inputTensor} outputs:@{@"rgb":outputTensor} runOptions:nil error:&error];157 if (success) memcpy(output, outputData.bytes, outputData.length);158 return success;159 // ARC + the autorelease pool release tensors, session, weights, and temporary buffers each job.160 }161}162