Skip to content
Draft
Show file tree
Hide file tree
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
34 changes: 34 additions & 0 deletions docs/ios27/CAMERA.md
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,40 @@ the tests). On phone 1 (all **measured**, M2M-SCALER.md "The phone test"):
Without it the source node's preview output leads nowhere, scaler or not (the boot with `m2m=0` showed the same).
- The shutter still fails at once with -16808 (BWUBNode); the scaler changes nothing there.

### The display side: the picture reaches backboardd's GPU, CoreAnimation's draw of it is lost (24 November)

Phone 1, kernel built from main 72c0b593 and the fork 4285c9c8 (`cam_trace=1 cam_metal=1`), root as found plus a StarbiteMetal
with the diagnostics below (`YCbCrProbe.h`, `DrawNote.h`, all off unless set in `/var/local/mtl2-env`). Seven boots, D1 to D7.

- **Measured: the texture is right.** backboardd makes a `YCBCR8_420_2P` (500) texture over each of the image queue sink's
surfaces and binds it in its main pass (render encoder, fragment slot 3). The probe (`SWEET_MTL2_YCCPROBE=1`) reads it on
backboardd's own GPU: with the front camera, `read()`, a linear and a nearest sample in a compute function, and linear and
nearest half-precision samples from fragment slot 3, all give RGB about 59 60 59 with 40 of 64 points lit, where the
processor reads luma 59 with 40 of 64 lit. The 4:2:0 conversion, the surface's bytes as backboardd's GPU sees them, and
sampling in either stage are right.
- **Measured: replacing the texture changes nothing.** With `SWEET_MTL2_YCCFLAT=1` every fragment binding of such a texture
gets a BGRA8 copy of it instead (made by a compute pass on the caller's queue, committed just before the caller's command
buffer). The viewfinder is still black. So the black does not come from the two-plane texture.
- **Measured: which draws show the camera** (pass log `SWEET_MTL2_PASSLOG`, draw notes `SWEET_MTL2_DRAWNOTE=1`). The first frame
draws it with `TimgA3Xhf_Ixrg` straight into the framebuffer. Every later frame draws it with `TimgA3S1Xhfu_Ixrg` (four draws)
into color 1, the pass's memoryless `RGBA16Float` attachment (load and store don't care), with the framebuffer's color 0
masked off. `TimgBbcmA3Xhf_Isup` (twice) and `TbdsA3Xhf_Isup_Isrc` then write color 0. Samplers are clamped and normalized
(nearest for the first draw, linear for the rest); texture coordinates are normalized (v from 178/1702). The camera's control
blur also samples it (`TimgA2Xhfu_Ixrg` into 22 x 22 and 208 x 144, `downsample_4_frag_lph`). No refusal from backboardd while
the viewfinder was up.
- **Inferred, not verified: where it is lost.** In the `S1` path the picture only reaches the screen through color 1, a
memoryless attachment read back by a later draw of the same pass (framebuffer fetch). That is the next place to measure:
what metal2vulkan does with that attachment and that fetch on PanVK (its rasterization-order and interlock features), and
whether the pass is split into instances there. With the bridge's telemetry on (`touch /var/local/mtl2-telemetry`) through a
camera session: no `new_instance_<reason>` count (the pass is not split), no degradation notice and no refusal from backboardd.
So the next measurement is inside PanVK: how it keeps the memoryless color and serves its fetch.
- **Also measured:** with the camera open, backboardd runs at 495 to 498 of its 514 MiB GPU cap. The kernel refused it a
24 MiB buffer after the photo (D5), and 13 times with the BGRA8 copies on (D7), where `mtl2.log` also has `OutOfMemory(Device)`
refusals of textures and of two command buffers. Each converted 828 x 1702 texture keeps an `RGBA16Float` image of about
11 MiB. Such refusals reach the console only while the process's console line budget lasts.
- **Also seen once, not explained:** both boots of D6, where the BGRA8 copy waited on the caller's thread for its own command
buffer, stopped backboardd after its first textures (SpringBoard never drawn); D7, without the wait, booted normally.

### SpringBoard's main-display layout (18 November)

`camera_sbtrace.c` on phone 1 (dylib `-16`, `-17`) shows that SpringBoard does publish its layout: the home screen, the lock
Expand Down
2 changes: 1 addition & 1 deletion tools/arch-size.allow
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ tools/ios27/fullroot/pipeline/cache/aot/fp16_stub.py 1424
tools/ios27/fullroot/pipeline/cache/aot/rewrite-grow.py 1047
tools/ios27/lse/lse-rewrite.py 826
tools/ios27/mesa-ios/starbite-drm/starbite_drm.c 985
tools/ios27/metal2/NativeBridgeMetalFrontend.mm 2767
tools/ios27/metal2/NativeBridgeMetalFrontend.mm 2777
tools/ios27/metal2/bridge/NativeMetalObjects.rs 2440
tools/mesa/air/air_intrinsics.c 2716
tools/mesa/air/air_metal.c 7072
Expand Down
5 changes: 5 additions & 0 deletions tools/ios27/metal/mk-bundle27.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ if [ -z "${NOPATCH:-}" ]; then
xcrun -sdk iphoneos metallib $W/src27/turn.air -o $W/src27/turn.metallib || exit 1
{ echo "static const unsigned char sweet_turn_metallib[] = {"; xxd -i < $W/src27/turn.metallib; echo "};"; } > $M2/TurnShaders.inc
fi
# YCbCrProbe.h includes YCbCrProbe.inc: tools/ios27/metal2/YCbCrProbe.metal (the GPU's read of a two-plane YCbCr texture, the camera
# preview's display side; used only with SWEET_MTL2_YCCPROBE=1) compiled the same way
xcrun -sdk iphoneos metal -mios-version-min=16.0 -c $M2/YCbCrProbe.metal -o $W/src27/ycc-probe.air || exit 1
xcrun -sdk iphoneos metallib $W/src27/ycc-probe.air -o $W/src27/ycc-probe.metallib || exit 1
{ echo "static const unsigned char sweet_ycc_probe_metallib[] = {"; xxd -i < $W/src27/ycc-probe.metallib; echo "};"; } > $M2/YCbCrProbe.inc
$CC -x objective-c++ -std=c++17 -fobjc-arc -O2 -g -Wall -Wno-deprecated-declarations -Wno-unused-function -bundle \
-o "$B/StarbiteMetal" $M2/HotMetal2.mm $M2/NativeBridgeMetalFrontend.mm -x none "$BRIDGE" \
-Wl,-dead_strip -lc++ -framework Foundation -framework Metal -framework IOSurface -framework IOKit \
Expand Down
165 changes: 165 additions & 0 deletions tools/ios27/metal2/DrawNote.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// SPDX-License-Identifier: MIT-0
// The camera's preview (docs/ios27/CAMERA.md, "The display side"), part of NativeBridgeMetalFrontend.mm (included there; a file
// of its own for the size rule): the whole state of a draw that samples a converted two-plane YCbCr texture (formats 500 to 510)
// in its fragment function, said once for each pipeline (24 lines a process at most). Off unless SWEET_MTL2_DRAWNOTE=1
// (mtl2-env). Said: `native-metal: draw note N: PIPELINE | t<slot> <format> <w>x<h> [surface ID] ... | s<slot> SAMPLER ... |
// fb<slot> <bytes> B: FLOATS | vb<slot> +<offset>: FLOATS | vbytes<slot> ...`. A pipeline is its fragment function's name, its
// color attachments (format, blending on or off with the factors and operations, write mask) and its sample count; a sampler its
// filters (min, mag, mip), address modes (s, t), whether its coordinates are normalized, and its level clamps. Reading only.
static int gDrawNote=-1;
static bool sweetDrawNoteOn() {
if(gDrawNote<0){const char *e=getenv("SWEET_MTL2_DRAWNOTE");gDrawNote=(e && e[0]=='1')?1:0;}
return gDrawNote==1;
}
static char gDrawNoteKey;
static NSMutableDictionary *sweetDrawNotes(id encoder) {
NSMutableDictionary *d=objc_getAssociatedObject(encoder,&gDrawNoteKey);
if(!d){d=[NSMutableDictionary dictionary];objc_setAssociatedObject(encoder,&gDrawNoteKey,d,OBJC_ASSOCIATION_RETAIN_NONATOMIC);}
return d;
}
static char gDrawNoteSummaryKey;
static void sweetDrawNoteSummary(id object,NSString *summary) {
if(sweetDrawNoteOn() && object)objc_setAssociatedObject(object,&gDrawNoteSummaryKey,summary,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
static NSString *sweetDrawNoteSummaryOf(id object) {return object?objc_getAssociatedObject(object,&gDrawNoteSummaryKey):nil;}
static NSString *sweetDrawNoteSampler(MTLSamplerDescriptor *d) {
return [NSString stringWithFormat:@"min %lu mag %lu mip %lu addr %lu,%lu norm %d lod %.1f-%.1f aniso %lu cmp %lu",(unsigned long)d.minFilter,
(unsigned long)d.magFilter,(unsigned long)d.mipFilter,(unsigned long)d.sAddressMode,(unsigned long)d.tAddressMode,(int)d.normalizedCoordinates,
d.lodMinClamp,d.lodMaxClamp,(unsigned long)d.maxAnisotropy,(unsigned long)d.compareFunction];
}
static NSString *sweetDrawNotePipeline(MTLRenderPipelineDescriptor *d) {
NSMutableString *s=[NSMutableString stringWithFormat:@"frag %@ vert %@ samples %lu",d.fragmentFunction.name,d.vertexFunction.name,(unsigned long)d.rasterSampleCount];
for(unsigned i=0;i<8;i++) {
MTLRenderPipelineColorAttachmentDescriptor *a=d.colorAttachments[i];
if(a.pixelFormat==MTLPixelFormatInvalid)continue;
[s appendFormat:@" c%u f%lu mask %lu",i,(unsigned long)a.pixelFormat,(unsigned long)a.writeMask];
if(a.blendingEnabled)[s appendFormat:@" blend rgb %lu*%lu op%lu a %lu*%lu op%lu",(unsigned long)a.sourceRGBBlendFactor,(unsigned long)a.destinationRGBBlendFactor,
(unsigned long)a.rgbBlendOperation,(unsigned long)a.sourceAlphaBlendFactor,(unsigned long)a.destinationAlphaBlendFactor,(unsigned long)a.alphaBlendOperation];
else [s appendString:@" noblend"];
}
return s;
}
static NSString *sweetDrawNoteFloats(const void *bytes,size_t length) {
NSMutableString *s=[NSMutableString string];const float *f=(const float *)bytes;
for(size_t k=0;k<length/4 && k<24;k++)[s appendFormat:@"%s%.4g",k?" ":"",f[k]];
return s;
}
// From the encoders' binding calls: what each slot holds now (stage 1 vertex, 2 fragment).
static void sweetDrawNoteTexture(id encoder,uint32_t stage,NSUInteger index,id<MTLTexture> t) {
if(!sweetDrawNoteOn() || stage!=2)return;
NSString *key=[NSString stringWithFormat:@"t%lu",(unsigned long)index];
if(!t){[sweetDrawNotes(encoder) removeObjectForKey:key];return;}
IOSurfaceRef surface=t.iosurface;
sweetDrawNotes(encoder)[key]=[NSString stringWithFormat:@"%lu %lux%lu%@",(unsigned long)t.pixelFormat,(unsigned long)t.width,(unsigned long)t.height,
surface?[NSString stringWithFormat:@" surface %u",IOSurfaceGetID(surface)]:@""];
}
static void sweetDrawNoteSamplerBound(id encoder,uint32_t stage,NSUInteger index,id sampler) {
if(!sweetDrawNoteOn() || stage!=2)return;
NSString *key=[NSString stringWithFormat:@"s%lu",(unsigned long)index];
NSString *v=sweetDrawNoteSummaryOf(sampler);
if(v)sweetDrawNotes(encoder)[key]=v;else [sweetDrawNotes(encoder) removeObjectForKey:key];
}
static void sweetDrawNoteBuffer(id encoder,uint32_t stage,NSUInteger index,id<MTLBuffer> buffer,NSUInteger offset) {
if(!sweetDrawNoteOn() || stage!=1)return;
NSString *key=[NSString stringWithFormat:@"vb%lu",(unsigned long)index];
if(buffer)sweetDrawNotes(encoder)[key]=@[buffer,@(offset)];else [sweetDrawNotes(encoder) removeObjectForKey:key];
}
static void sweetDrawNoteBufferOffset(id encoder,uint32_t stage,NSUInteger index,NSUInteger offset) {
if(!sweetDrawNoteOn() || stage!=1)return;
NSString *key=[NSString stringWithFormat:@"vb%lu",(unsigned long)index];
NSArray *was=sweetDrawNotes(encoder)[key];
if([was isKindOfClass:[NSArray class]] && was.count==2)sweetDrawNotes(encoder)[key]=@[was[0],@(offset)];
}
static void sweetDrawNoteBytes(id encoder,uint32_t stage,NSUInteger index,const void *bytes,NSUInteger length) {
if(!sweetDrawNoteOn() || !bytes)return;
NSString *key=[NSString stringWithFormat:@"%@%lu",stage==2?@"fb":@"vbytes",(unsigned long)index];
sweetDrawNotes(encoder)[key]=[NSString stringWithFormat:@"%lu B: %@",(unsigned long)length,sweetDrawNoteFloats(bytes,length)];
}
static void sweetDrawNotePipelineBound(id encoder,id pipeline) {
if(!sweetDrawNoteOn())return;
NSString *v=sweetDrawNoteSummaryOf(pipeline);
sweetDrawNotes(encoder)[@"p"]=v?v:@"(unknown pipeline)";
}
// At a draw: when a fragment slot holds a texture of formats 500 to 510, say the state (once a pipeline, 24 a process).
static void sweetDrawNoteDraw(id encoder,const char *how,NSUInteger count) {
if(!sweetDrawNoteOn())return;
NSMutableDictionary *d=objc_getAssociatedObject(encoder,&gDrawNoteKey);
if(!d)return;
bool ycc=false;
for(NSString *key in d) {
if(![key hasPrefix:@"t"])continue;
const long f=[(NSString *)d[key] integerValue];ycc=ycc || (f>=500 && f<=510);
}
if(!ycc)return;
static std::mutex lock;static NSMutableSet *said;static unsigned lines;
NSString *pipeline=d[@"p"]?:@"(no pipeline)";
{
std::lock_guard<std::mutex> hold(lock);
if(!said)said=[NSMutableSet set];
if(lines>=24 || [said containsObject:pipeline])return;
[said addObject:pipeline];lines++;
}
NSMutableString *s=[NSMutableString stringWithFormat:@"native-metal: draw note %u: %s %lu | %@ |",lines,how,(unsigned long)count,pipeline];
for(NSString *key in [d.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
if([key isEqualToString:@"p"])continue;
id v=d[key];
if([v isKindOfClass:[NSArray class]]) {
id<MTLBuffer> b=((NSArray *)v)[0];const NSUInteger off=[((NSArray *)v)[1] unsignedIntegerValue];
const uint8_t *c=(const uint8_t *)b.contents;
if(c && off+16<=b.length)[s appendFormat:@" %@ +%lu: %@ |",key,(unsigned long)off,sweetDrawNoteFloats(c+off,MIN((NSUInteger)96,b.length-off))];
else [s appendFormat:@" %@ +%lu: (no contents) |",key,(unsigned long)off];
} else [s appendFormat:@" %@ %@ |",key,v];
}
const char *line=s.UTF8String;
for(size_t at=0,n=strlen(line);at<n;at+=900) { // the console takes long lines in pieces
char piece[920];snprintf(piece,sizeof piece,"%s%.900s",at?"native-metal: draw note ... ":"",line+at);sm2_logs(piece);
}
}
// The pipeline side, wrapped at load (the frontend's own methods, always; the wrappers do nothing more unless the note is on):
// a pipeline made keeps its summary, a pipeline set is noted on the encoder.
__attribute__((constructor)) static void sweetDrawNoteInstall() {
Class methods=NSClassFromString(@"NBDeviceMethods"),encoder=NSClassFromString(@"NBRenderEncoder");
const SEL make=@selector(newRenderPipelineStateWithDescriptor:options:reflection:error:),set=@selector(setRenderPipelineState:);
if(Method m=methods?class_getInstanceMethod(methods,make):nullptr) {
typedef id (*Make)(id,SEL,MTLRenderPipelineDescriptor *,MTLPipelineOption,MTLAutoreleasedRenderPipelineReflection *,NSError **);
const Make old=(Make)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^id(id self,MTLRenderPipelineDescriptor *d,MTLPipelineOption o,MTLAutoreleasedRenderPipelineReflection *r,NSError **e) {
id state=old(self,make,d,o,r,e);
if(state && sweetDrawNoteOn())sweetDrawNoteSummary(state,sweetDrawNotePipeline(d));
return state;
}));
}
Class base=NSClassFromString(@"NBEncoder");
if(Method m=base?class_getInstanceMethod(base,@selector(sampler:index:stage:)):nullptr) {
typedef void (*F)(id,SEL,id,NSUInteger,uint32_t);const F old=(F)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,id x,NSUInteger i,uint32_t st){old(self,@selector(sampler:index:stage:),x,i,st);sweetDrawNoteSamplerBound(self,st,i,x);}));
}
if(Method m=base?class_getInstanceMethod(base,@selector(bytes:length:index:stage:)):nullptr) {
typedef void (*F)(id,SEL,const void *,NSUInteger,NSUInteger,uint32_t);const F old=(F)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,const void *p,NSUInteger n,NSUInteger i,uint32_t st){old(self,@selector(bytes:length:index:stage:),p,n,i,st);sweetDrawNoteBytes(self,st,i,p,n);}));
}
if(Method m=base?class_getInstanceMethod(base,@selector(buffer:offset:index:stage:)):nullptr) {
typedef void (*F)(id,SEL,id,NSUInteger,NSUInteger,uint32_t);const F old=(F)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,id b,NSUInteger o,NSUInteger i,uint32_t st){old(self,@selector(buffer:offset:index:stage:),b,o,i,st);sweetDrawNoteBuffer(self,st,i,b,o);}));
}
if(Method m=base?class_getInstanceMethod(base,@selector(offset:index:stage:)):nullptr) {
typedef void (*F)(id,SEL,NSUInteger,NSUInteger,uint32_t);const F old=(F)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,NSUInteger o,NSUInteger i,uint32_t st){old(self,@selector(offset:index:stage:),o,i,st);sweetDrawNoteBufferOffset(self,st,i,o);}));
}
const SEL draw=@selector(drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:);
if(Method m=encoder?class_getInstanceMethod(encoder,draw):nullptr) {
typedef void (*F)(id,SEL,MTLPrimitiveType,NSUInteger,NSUInteger,NSUInteger,NSUInteger);const F old=(F)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,MTLPrimitiveType t,NSUInteger s,NSUInteger n,NSUInteger i,NSUInteger b){sweetDrawNoteDraw(self,"draw",n);old(self,draw,t,s,n,i,b);}));
}
const SEL indexed=@selector(drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:baseVertex:baseInstance:);
if(Method m=encoder?class_getInstanceMethod(encoder,indexed):nullptr) {
typedef void (*F)(id,SEL,MTLPrimitiveType,NSUInteger,MTLIndexType,id,NSUInteger,NSUInteger,NSInteger,NSUInteger);const F old=(F)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,MTLPrimitiveType t,NSUInteger n,MTLIndexType k,id b,NSUInteger o,NSUInteger i,NSInteger v,NSUInteger bi){
sweetDrawNoteDraw(self,"indexed",n);old(self,indexed,t,n,k,b,o,i,v,bi);}));
}
if(Method m=encoder?class_getInstanceMethod(encoder,set):nullptr) {
typedef void (*Set)(id,SEL,id);
const Set old=(Set)method_getImplementation(m);
method_setImplementation(m,imp_implementationWithBlock(^(id self,id state){old(self,set,state);sweetDrawNotePipelineBound(self,state);}));
}
}
14 changes: 12 additions & 2 deletions tools/ios27/metal2/NativeBridgeMetalFrontend.mm
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ static void noteFormat(uint32_t format,bool made) {
if(gFormatCount<8)gFormats[gFormatCount++]=format;
}
#include "YCbCrTrace.h"
#include "YCbCrProbe.h"
#include "DrawNote.h"
static NSError *nbError(NSString *why) {
return [NSError errorWithDomain:@"org.blu-sharky.native-metal" code:-1 userInfo:@{NSLocalizedDescriptionKey:why?:@"refused"}];
}
Expand Down Expand Up @@ -928,12 +930,18 @@ - (void)texture:(id<MTLTexture>)texture index:(NSUInteger)index stage:(uint32_t)
if(_refused)return;
if(texture && ![(id)texture isKindOfClass:[NBTexture class]]){[_commandBuffer refuse:@"foreign texture"];return;}
if(texture)[_commandBuffer.resourceOwners addObject:texture];
sweetDrawNoteTexture(self,stage,index,texture);
if(texture && [(NBTexture *)texture surface]) {
NBTexture *t=(NBTexture *)texture;
[_commandBuffer.surfaces addObject:t];
const MTLTextureUsage u=t.usage;
if(!u || (u&MTLTextureUsageShaderWrite))[_commandBuffer.writtenSurfaces addObject:t];
if(sweetYCbCrFormat(t.descriptor.format))sweetYCbCrBound(object_getClassName(self),stage,index,t.descriptor.format,t.surface,t.surfacePlane);
if(sweetYCbCrFormat(t.descriptor.format)) {
sweetYCbCrBound(object_getClassName(self),stage,index,t.descriptor.format,t.surface,t.surfacePlane);
sweetYCbCrProbe(texture,t.surface,object_getClassName(self),stage,index,t.descriptor.format);
}
if(stage==2 && sweetYCbCrFormat(t.descriptor.format))
if(id<MTLTexture> flat=sweetYCbCrFlat(texture,t.surface,t.descriptor.format,_commandBuffer)){texture=flat;[_commandBuffer.resourceOwners addObject:flat];}
}
[self check:nmb_encoder_set_texture(_handle,stage,texture?[(NBTexture *)texture handle]:nullptr,(uint32_t)index) what:"setTexture"];
}
Expand Down Expand Up @@ -2380,7 +2388,9 @@ - (NSUInteger)requiredLinearTextureBytesPerRowForDescriptor:(MTLTextureDescripto
(uint64_t)d.borderColor,(uint64_t)d.normalizedCoordinates,d.maxAnisotropy,(uint64_t)d.compareFunction,(uint64_t)d.lodAverage,d.lodMinClamp,d.lodMaxClamp};
NmbSampler *handle=nmb_sampler_new(gDevice,&s);
if(!handle){NBLOG(@"native-metal: sampler refused: %@",lastError());return nil;}
NBSampler *sampler=[NBSampler new];sampler.handle=handle;return (id<MTLSamplerState>)sampler;
NBSampler *sampler=[NBSampler new];sampler.handle=handle;
if(sweetDrawNoteOn())sweetDrawNoteSummary(sampler,sweetDrawNoteSampler(d));
return (id<MTLSamplerState>)sampler;
}
- (id<MTLDepthStencilState>)newDepthStencilStateWithDescriptor:(MTLDepthStencilDescriptor *)d {
auto face=[](MTLStencilDescriptor *s)->NmbStencil {
Expand Down
Loading
Loading