diff --git a/docs/ios27/CAMERA.md b/docs/ios27/CAMERA.md index 28ed21eb1..21f1fca97 100644 --- a/docs/ios27/CAMERA.md +++ b/docs/ios27/CAMERA.md @@ -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_` 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 diff --git a/tools/arch-size.allow b/tools/arch-size.allow index 519b1a40c..16064b6f9 100644 --- a/tools/arch-size.allow +++ b/tools/arch-size.allow @@ -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 diff --git a/tools/ios27/metal/mk-bundle27.sh b/tools/ios27/metal/mk-bundle27.sh index 9ddfd09d4..7ff7f39d0 100755 --- a/tools/ios27/metal/mk-bundle27.sh +++ b/tools/ios27/metal/mk-bundle27.sh @@ -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 \ diff --git a/tools/ios27/metal2/DrawNote.h b/tools/ios27/metal2/DrawNote.h new file mode 100644 index 000000000..9dd346a04 --- /dev/null +++ b/tools/ios27/metal2/DrawNote.h @@ -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 x [surface ID] ... | s SAMPLER ... | +// fb B: FLOATS | vb +: FLOATS | vbytes ...`. 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 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 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 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 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)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 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"]; } @@ -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)sampler; + NBSampler *sampler=[NBSampler new];sampler.handle=handle; + if(sweetDrawNoteOn())sweetDrawNoteSummary(sampler,sweetDrawNoteSampler(d)); + return (id)sampler; } - (id)newDepthStencilStateWithDescriptor:(MTLDepthStencilDescriptor *)d { auto face=[](MTLStencilDescriptor *s)->NmbStencil { diff --git a/tools/ios27/metal2/YCbCrProbe.h b/tools/ios27/metal2/YCbCrProbe.h new file mode 100644 index 000000000..edd724852 --- /dev/null +++ b/tools/ios27/metal2/YCbCrProbe.h @@ -0,0 +1,224 @@ +// 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): what a converted two-plane YCbCr texture over an IOSurface (formats 500 to 510, the window +// server's texture over the camera preview's pictures) reads on this process's GPU, beside what the surface holds as this +// process's processor reads it. Off unless SWEET_MTL2_YCCPROBE=1 (mtl2-env). At the 1st, 3rd, 10th, 30th, ... binding of such a +// texture over a surface at least 256 texels wide (16 probes a process at most), passes of its own (YCbCrProbe.metal, on a queue +// of its own, off the caller's thread) read an 8 x 8 grid of the texture in a compute function (read(), a linear and a nearest +// sample) and draw it, sampled in half precision from fragment slot 3 (linear, then nearest), into a 16 x 16 RGBA8 target. Said: +// `native-metal: ycbcr probe N (bind B, ENCODER stage S slot I): fmt F over surface ID seed X WxH: read ...; sample ...; nearest ...; +// cpu Y M, K of 64 lit; frag ...; frag nearest ...; point 0 read ...; status T`. The colors are 0 to 255; a point is lit above 24 +// (luma from the colors as BT.601 weights). Reading only: nothing is written and the surface is held only while the probe runs. +// Run on phone 1 on 24 November (D1-D5): every one of these reads the picture the surface holds. +#if __has_include("YCbCrProbe.inc") +#include "YCbCrProbe.inc" // sweet_ycc_probe_metallib[]: YCbCrProbe.metal, built by the bundle's script +#define SWEET_YCC_PROBE 1 +#endif +static bool sweetYCbCrProbeOn() { + static int on=-1; + if(on<0){const char *e=getenv("SWEET_MTL2_YCCPROBE");on=(e && e[0]=='1')?1:0;} + return on==1; +} +#ifdef SWEET_YCC_PROBE +// The probe's colors, said: mean of each channel (0..255), and how many of the 64 points are lit. +static void sweetYCbCrProbeSum(const float *c,char *out,size_t size) { + double r=0,g=0,b=0,a=0;unsigned lit=0; + for(unsigned k=0;k<64;k++) { + const float *p=c+4*k;r+=p[0];g+=p[1];b+=p[2];a+=p[3]; + lit+=(0.299*p[0]+0.587*p[1]+0.114*p[2])*255.0>24.0; + } + snprintf(out,size,"%.0f %.0f %.0f a %.2f, %u of 64 lit",r*255/64,g*255/64,b*255/64,a/64,lit); +} +static void sweetYCbCrProbeRun(id texture,IOSurfaceRef surface,unsigned probe,unsigned bind,const char *where,uint64_t format) { + static id pipeline;static id drawing;static id queue;static id sampler,point;static bool failed; + id device=(id)gDeviceObject; + char said[900]; + if(!pipeline && !failed) { + NSError *error=nil; + dispatch_data_t data=dispatch_data_create(sweet_ycc_probe_metallib,sizeof sweet_ycc_probe_metallib,nullptr,DISPATCH_DATA_DESTRUCTOR_DEFAULT); + id library=[device newLibraryWithData:data error:&error]; + id function=library?[library newFunctionWithName:@"sweet_ycc_probe"]:nil; + pipeline=function?[device newComputePipelineStateWithFunction:function error:&error]:nil; + if(library) { + MTLRenderPipelineDescriptor *pd=[MTLRenderPipelineDescriptor new]; + pd.vertexFunction=[library newFunctionWithName:@"sweet_ycc_probe_vert"];pd.fragmentFunction=[library newFunctionWithName:@"sweet_ycc_probe_frag"]; + pd.colorAttachments[0].pixelFormat=MTLPixelFormatRGBA8Unorm; + NSError *drawError=nil; + drawing=(pd.vertexFunction && pd.fragmentFunction)?[device newRenderPipelineStateWithDescriptor:pd error:&drawError]:nil; + if(!drawing){snprintf(said,sizeof said,"native-metal: ycbcr probe: no render pipeline: %s",drawError?drawError.localizedDescription.UTF8String:"no function");sm2_logs(said);} + } + MTLSamplerDescriptor *sd=[MTLSamplerDescriptor new]; + sd.minFilter=MTLSamplerMinMagFilterLinear;sd.magFilter=MTLSamplerMinMagFilterLinear;sd.mipFilter=MTLSamplerMipFilterNotMipmapped; + sd.sAddressMode=MTLSamplerAddressModeClampToEdge;sd.tAddressMode=MTLSamplerAddressModeClampToEdge; + sampler=[device newSamplerStateWithDescriptor:sd]; + sd.minFilter=MTLSamplerMinMagFilterNearest;sd.magFilter=MTLSamplerMinMagFilterNearest; + point=[device newSamplerStateWithDescriptor:sd]; + queue=[device newCommandQueue]; + if(!pipeline || !sampler || !point || !queue) { + failed=true; + snprintf(said,sizeof said,"native-metal: ycbcr probe: not made (library %s, pipeline %s, sampler %s, queue %s): %s",library?"yes":"no", + pipeline?"yes":"no",sampler?"yes":"no",queue?"yes":"no",error?error.localizedDescription.UTF8String:"no error"); + sm2_logs(said); + } + } + if(failed)return; + id out=[device newBufferWithLength:192*4*sizeof(float) options:MTLResourceStorageModeShared]; + if(!out)return; + id commands=[queue commandBuffer]; + id encoder=[commands computeCommandEncoder]; + [encoder setComputePipelineState:pipeline]; + [encoder setTexture:texture atIndex:0]; + [encoder setSamplerState:sampler atIndex:0]; + [encoder setSamplerState:point atIndex:1]; + [encoder setBuffer:out offset:0 atIndex:0]; + [encoder dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)]; + [encoder endEncoding]; + [commands commit]; + [commands waitUntilCompleted]; + const long status=(long)commands.status; + + char frag[96]="not drawn",fragNearest[96]="not drawn"; + for(int pass=0;pass<2 && drawing;pass++) { + char *into=pass?fragNearest:frag; + MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:16 height:16 mipmapped:NO]; + td.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead;td.storageMode=MTLStorageModeShared; + id target=[device newTextureWithDescriptor:td]; + if(target) { + MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture=target;pass.colorAttachments[0].loadAction=MTLLoadActionClear; + pass.colorAttachments[0].clearColor=MTLClearColorMake(1,0,1,1);pass.colorAttachments[0].storeAction=MTLStoreActionStore; + id drawn=[queue commandBuffer]; + id re=[drawn renderCommandEncoderWithDescriptor:pass]; + [re setRenderPipelineState:drawing];[re setFragmentTexture:texture atIndex:3];[re setFragmentSamplerState:pass?point:sampler atIndex:0]; + [re drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];[re endEncoding]; + [drawn commit];[drawn waitUntilCompleted]; + uint8_t px[16*16*4]={}; + [target getBytes:px bytesPerRow:16*4 fromRegion:MTLRegionMake2D(0,0,16,16) mipmapLevel:0]; + unsigned long r=0,g=0,b=0,al=0;unsigned lit=0,magenta=0; + for(unsigned k=0;k<256;k++){const uint8_t *q=px+4*k;r+=q[0];g+=q[1];b+=q[2];al+=q[3];lit+=(299*q[0]+587*q[1]+114*q[2])/1000>24;magenta+=q[0]==255&&q[1]==0&&q[2]==255;} + snprintf(into,96,"%lu %lu %lu a %lu, %u of 256 lit, %u untouched, status %ld",r/256,g/256,b/256,al/256,lit,magenta,(long)drawn.status); + } + } + char read[96],sample[96],nearest[96],cpu[96]="not read"; + sweetYCbCrProbeSum((const float *)out.contents,read,sizeof read); + sweetYCbCrProbeSum((const float *)out.contents+256,sample,sizeof sample); + sweetYCbCrProbeSum((const float *)out.contents+512,nearest,sizeof nearest); + if(IOSurfaceGetPlaneCount(surface)==2 && IOSurfaceGetBytesPerElementOfPlane(surface,0)==1 && IOSurfaceLock(surface,kIOSurfaceLockReadOnly,nullptr)==0) { + const uint8_t *l=(const uint8_t *)IOSurfaceGetBaseAddressOfPlane(surface,0); + const size_t w=IOSurfaceGetWidthOfPlane(surface,0),h=IOSurfaceGetHeightOfPlane(surface,0),lr=IOSurfaceGetBytesPerRowOfPlane(surface,0); + if(l && w && h) { + sys_dcache_flush((void *)l,lr*h); + unsigned long sum=0;unsigned lit=0; + for(unsigned y=0;y<8;y++)for(unsigned x=0;x<8;x++){const unsigned v=l[(h*(2*y+1)/16)*lr+w*(2*x+1)/16];sum+=v;lit+=v>24;} + snprintf(cpu,sizeof cpu,"Y %lu, %u of 64 lit",sum/64,lit); + } + IOSurfaceUnlock(surface,kIOSurfaceLockReadOnly,nullptr); + } + const float *first=(const float *)out.contents; + snprintf(said,sizeof said,"native-metal: ycbcr probe %u (bind %u, %s): fmt %llu over surface %u seed %u %zux%zu: read %s; sample %s; nearest %s; cpu %s; " + "frag %s; frag nearest %s; point 0 read %.3f %.3f %.3f %.3f; status %ld%s%s",probe,bind,where,(unsigned long long)format,IOSurfaceGetID(surface),IOSurfaceGetSeed(surface), + IOSurfaceGetWidth(surface),IOSurfaceGetHeight(surface),read,sample,nearest,cpu,frag,fragNearest,first[0],first[1],first[2],first[3],status, + commands.error?": ":"",commands.error?commands.error.localizedDescription.UTF8String:""); + sm2_logs(said); +} +#endif +// From the encoders' texture binding: count the binding, and at the probe points start a probe of this texture off this thread. +static void sweetYCbCrProbe(id texture,IOSurfaceRef surface,const char *encoder,uint32_t stage,NSUInteger index,uint64_t format) { +#ifdef SWEET_YCC_PROBE + if(!sweetYCbCrProbeOn() || !gDeviceObject || !texture || !surface || format<500 || format>510 || IOSurfaceGetWidth(surface)<256)return; + static std::atomic binds{0},probes{0}; + static const unsigned at[]={1,3,10,30,60,100,200,300,450,600,900,1200,1800,2400,3600,4800}; + const unsigned bind=binds.fetch_add(1)+1; + bool due=false;for(unsigned a:at)due=due || a==bind; + if(!due)return; + const unsigned probe=probes.fetch_add(1)+1; + if(probe>16)return; + static dispatch_queue_t lane=dispatch_queue_create("scion.ycbcr-probe",DISPATCH_QUEUE_SERIAL); + char where[80];snprintf(where,sizeof where,"%s stage %u slot %lu",encoder,stage,(unsigned long)index); + std::string at_=where; + CFRetain(surface); + dispatch_async(lane,^{ + @autoreleasepool {sweetYCbCrProbeRun(texture,surface,probe,bind,at_.c_str(),format);} + CFRelease(surface); + }); +#else + (void)texture;(void)surface;(void)encoder;(void)stage;(void)index;(void)format; +#endif +} +// The flattening (SWEET_MTL2_YCCFLAT=1, a test of the camera preview's display side): a render encoder's fragment binding of a converted +// two-plane YCbCr texture over a surface is given instead a BGRA8 texture of the same size holding what the texture reads (the kernel +// sweet_ycc_flatten). The copy is encoded in a command buffer of the caller's own queue, committed just before the caller's (so the queue +// orders it first and nothing waits on the caller's thread). If the window server's draw shows the picture then, its pipeline's sampling +// of the two-plane texture is what loses it. One flat texture per surface (16 at most), written again for every command buffer that binds it. +static bool sweetYCbCrFlatOn() { + static int on=-1; + if(on<0){const char *e=getenv("SWEET_MTL2_YCCFLAT");on=(e && e[0]=='1')?1:0;} + return on==1; +} +#ifdef SWEET_YCC_PROBE +static std::mutex gFlatLock;static id gFlatPipeline;static NSMutableDictionary *gFlats;static bool gFlatFailed; +static char gFlatPendingKey; +#endif +static id sweetYCbCrFlat(id texture,IOSurfaceRef surface,uint64_t format,id commandBuffer) { +#ifdef SWEET_YCC_PROBE + if(!sweetYCbCrFlatOn() || !gDeviceObject || !texture || !surface || !commandBuffer || format<500 || format>510)return nil; + std::lock_guard hold(gFlatLock); + id device=(id)gDeviceObject; + if(!gFlatPipeline && !gFlatFailed) { + NSError *error=nil; + dispatch_data_t data=dispatch_data_create(sweet_ycc_probe_metallib,sizeof sweet_ycc_probe_metallib,nullptr,DISPATCH_DATA_DESTRUCTOR_DEFAULT); + id library=[device newLibraryWithData:data error:&error]; + id function=library?[library newFunctionWithName:@"sweet_ycc_flatten"]:nil; + gFlatPipeline=function?[device newComputePipelineStateWithFunction:function error:&error]:nil; + gFlats=[NSMutableDictionary dictionary];gFlatFailed=!gFlatPipeline; + char said[300];snprintf(said,sizeof said,"native-metal: ycbcr flat: %s%s",gFlatPipeline?"on":"not made: ", + gFlatPipeline?"":(error?error.localizedDescription.UTF8String:"no function")); + sm2_logs(said); + } + if(gFlatFailed)return nil; + NSNumber *key=@(IOSurfaceGetID(surface)); + id flat=gFlats[key]; + if(!flat || flat.width!=texture.width || flat.height!=texture.height) { + if(gFlats.count>=16)[gFlats removeAllObjects]; + MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm width:texture.width height:texture.height mipmapped:NO]; + td.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite;td.storageMode=MTLStorageModePrivate; + flat=[device newTextureWithDescriptor:td]; + if(!flat)return nil; + gFlats[key]=flat; + } + NSMutableArray *pending=objc_getAssociatedObject(commandBuffer,&gFlatPendingKey); + if(!pending){pending=[NSMutableArray array];objc_setAssociatedObject(commandBuffer,&gFlatPendingKey,pending,OBJC_ASSOCIATION_RETAIN_NONATOMIC);} + for(NSArray *pair in pending)if(pair[1]==flat)return flat; + [pending addObject:@[texture,flat]]; + return flat; +#else + (void)texture;(void)surface;(void)format;(void)commandBuffer;return nil; +#endif +} +#ifdef SWEET_YCC_PROBE +// Wrapped at load: a command buffer's commit first commits, on its own queue, the copies of the flat textures it binds. +__attribute__((constructor)) static void sweetYCbCrFlatInstall() { + Class cls=NSClassFromString(@"NBCommandBuffer");const SEL commit=@selector(commit); + Method m=cls?class_getInstanceMethod(cls,commit):nullptr; + if(!m)return; + typedef void (*F)(id,SEL);const F old=(F)method_getImplementation(m); + method_setImplementation(m,imp_implementationWithBlock(^(id self) { + NSMutableArray *pending=objc_getAssociatedObject(self,&gFlatPendingKey); + if(pending.count && gFlatPipeline) { + NSArray *pairs=[pending copy];[pending removeAllObjects]; + id copies=[[(id)self commandQueue] commandBuffer]; + id encoder=[copies computeCommandEncoder]; + [encoder setComputePipelineState:gFlatPipeline]; + for(NSArray *pair in pairs) { + id picture=pair[0]; + [encoder setTexture:picture atIndex:0];[encoder setTexture:pair[1] atIndex:1]; + [encoder dispatchThreadgroups:MTLSizeMake((picture.width+15)/16,(picture.height+15)/16,1) threadsPerThreadgroup:MTLSizeMake(16,16,1)]; + } + [encoder endEncoding];[copies commit]; + static std::atomic said{0}; + if(said.fetch_add(1)<6){char line[160];snprintf(line,sizeof line,"native-metal: ycbcr flat: %lu copies committed before a command buffer",(unsigned long)pairs.count);sm2_logs(line);} + } + old(self,commit); + })); +} +#endif diff --git a/tools/ios27/metal2/YCbCrProbe.metal b/tools/ios27/metal2/YCbCrProbe.metal new file mode 100644 index 000000000..663d158f6 --- /dev/null +++ b/tools/ios27/metal2/YCbCrProbe.metal @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT-0 +// The camera's preview (docs/ios27/CAMERA.md, "The display side"): what a two-plane YCbCr texture over an IOSurface reads on +// this process's GPU. One thread for each point of an 8 x 8 grid (the middle of each cell), each writing three colors: the +// texel as read() gives it, then samples at the texel's middle through a linear and a nearest sampler. Built by tools/ios27/metal/mk-bundle27.sh +// into YCbCrProbe.inc; used by YCbCrProbe.h. +#include +using namespace metal; + +kernel void sweet_ycc_probe(texture2d picture [[texture(0)]], sampler filter [[sampler(0)]], + sampler point [[sampler(1)]], device float4 *out [[buffer(0)]], uint2 cell [[thread_position_in_grid]]) { + if (cell.x >= 8 || cell.y >= 8) + return; + const uint w = picture.get_width(), h = picture.get_height(); + const uint2 at = uint2(w * (2 * cell.x + 1) / 16, h * (2 * cell.y + 1) / 16); + out[cell.y * 8 + cell.x] = picture.read(at); + out[64 + cell.y * 8 + cell.x] = picture.sample(filter, (float2(at) + 0.5f) / float2(w, h)); + out[128 + cell.y * 8 + cell.x] = picture.sample(point, (float2(at) + 0.5f) / float2(w, h)); +} + +// The same texture sampled where the window server samples it: a fragment function, in half precision, from slot 3, drawing a +// 16 x 16 target (one triangle over it; each pixel samples the texture at the matching place). +vertex float4 sweet_ycc_probe_vert(uint v [[vertex_id]]) { + const float2 p = float2((v << 1) & 2, v & 2); + return float4(p * 2.0f - 1.0f, 0.0f, 1.0f); +} + +fragment half4 sweet_ycc_probe_frag(float4 at [[position]], texture2d picture [[texture(3)]], sampler filter [[sampler(0)]]) { + return picture.sample(filter, at.xy / 16.0f); +} + +// The flattening (YCbCrProbe.h, SWEET_MTL2_YCCFLAT=1): every texel of a converted two-plane texture as read() gives it, written into +// a texture of 8-bit colors of the same size (alpha 1). +kernel void sweet_ycc_flatten(texture2d picture [[texture(0)]], texture2d flat [[texture(1)]], + uint2 at [[thread_position_in_grid]]) { + if (at.x >= picture.get_width() || at.y >= picture.get_height()) + return; + flat.write(float4(picture.read(at).rgb, 1.0f), at); +}