diff --git a/docs/ios27/CAMERA.md b/docs/ios27/CAMERA.md index 28ed21eb1..daf1dbe18 100644 --- a/docs/ios27/CAMERA.md +++ b/docs/ios27/CAMERA.md @@ -583,6 +583,73 @@ 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. + +### The display side, part two: not the memoryless attachment; the picture reaches backboardd's framebuffer (24 November, evening) + +Phone 1, the same kernel and line as above (`cam_trace=1 cam_metal=1`), root as handed back plus a StarbiteMetal with +`FetchProbe.h` / `FetchProbe.metal` and more draw-note modes (all off unless set in `/var/local/mtl2-env`). Boots F1 to F5. + +- **Measured: framebuffer fetch through a memoryless color attachment works on PanVK** (`SWEET_MTL2_FBPROBE=1`, F1). In + backboardd, on its own queue, 64 x 64 passes of the camera layer's shape: color 0 BGRA8 stored, color 1 a memoryless + `RGBA16Float` (load and store don't care), color 2 a memoryless `R32Float`. A draw that writes only color 1 (color 0 masked off) + and then a draw that reads color 1 by `[[color(1)]]` and writes color 0 leave exactly the value written (B G R 191 128 64). The + same with color 1 private and stored, with only colors 0 and 1, with color 1 cleared by the load action, and a read of color 0 + itself, all right; a pixel no draw wrote reads 0. metal2vulkan reads such attachments as input attachments with + `VK_EXT_rasterization_order_attachment_access` (on this PanVK for v6 through `mesa26-panvk-ios.patch`), and PanVK lowers the + read to `LD_TILE` from the tile buffer; the Bifrost scheduler orders it after earlier fragments (the clause waits on the + eldest-colour slot). No render-pass split, input-attachment copy or barrier is involved. +- **Measured: on steady frames the main pass's color 1 holds nothing** (`SWEET_MTL2_FBPROBE=2`, F3): with color 1 of the 828 x 1702 + main pass made a stored private texture for the camera session, 20 reads of it over 60 s gave 0 0 0 0 everywhere. The draws that + write color 1 (`TimgA3S1Xhfu_Ixrg` and the other `S1` functions) belong to the flip animation's blur, not to steady frames. + QuartzCore's functions are specialized with `fc_framebuffer_fetch=1`; their `_Isup` input is a sampled backdrop texture + (`RGBA16Float` 192 x 192 at slots 3 and 4), not color 1 (`SWEET_MTL2_DRAWNOTE=2`). +- **Measured: the steady preview draw is direct, and it puts the picture into the framebuffer** (`SWEET_MTL2_FBPROBE=3`, F5). + `TimgA3Xhf_Ixrg` samples the format 500 texture over the sink's surfaces into color 0 (x 0 to 828, y from 178, v from 0.1046), + at least once a second. The processor's read of that pass's color 0 surface when its command buffer completed gave, over the + viewfinder, RGB means 16 to 21 with 10 to 17 of 64 points lit, where the image queue sink's sample 300 had luma mean 21 with 109 + of 256 above black (front camera, a dim room). At the same moment the screen (the kernel's `shot`) is exactly 0 over the + viewfinder. Skipping CoreAnimation's `luma_boost_lph` (a diagnostic, `SWEET_MTL2_SKIPLUMA=1`) did not change the black. +- **Measured: backboardd hands the preview to the display as a layer of its own.** The kernel's framebuffer said + `SWEET FB: layer 2 surface 284 at 0,0 828x1702 (swap 512)`: surface 284 is one of the sink's `420f` surfaces. SwapEnd in the + fork's `iokit/Kernel/arm/SweetFramebuffer.cpp` copies layer 0 and blends upper layers as premultiplied BGRA (made for the + pointer); a two-plane `420f` layer is not converted there (read in the code, not measured). +- **So the black viewfinder is not in the Metal layer.** The next piece is the display path: what SwapEnd gets for the preview's + layer (its rectangles, and which surface layer 0 is then) and a YCbCr layer in SwapEnd (colour conversion into the panel), or a + display that tells QuartzCore truthfully which layer formats it scans out. The black app-switcher cards were not looked at. + ### 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..084b7d667 100755 --- a/tools/ios27/metal/mk-bundle27.sh +++ b/tools/ios27/metal/mk-bundle27.sh @@ -23,6 +23,16 @@ 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 +# FetchProbe.h includes FetchProbe.inc: tools/ios27/metal2/FetchProbe.metal (framebuffer fetch through a memoryless color attachment, +# the shape of the camera layer's draw; used only with SWEET_MTL2_FBPROBE=1) compiled the same way +xcrun -sdk iphoneos metal -mios-version-min=16.0 -c $M2/FetchProbe.metal -o $W/src27/fetch-probe.air || exit 1 +xcrun -sdk iphoneos metallib $W/src27/fetch-probe.air -o $W/src27/fetch-probe.metallib || exit 1 +{ echo "static const unsigned char sweet_fetch_probe_metallib[] = {"; xxd -i < $W/src27/fetch-probe.metallib; echo "};"; } > $M2/FetchProbe.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..96baee7cf --- /dev/null +++ b/tools/ios27/metal2/DrawNote.h @@ -0,0 +1,246 @@ +// 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. +// SWEET_MTL2_DRAWNOTE=2: also every draw of the passes FetchProbe.h marks (`fb draw`), with QuartzCore's fc_framebuffer_fetch constant; +// =3: the state of CoreAnimation's luma boost draws (`luma note`); SWEET_MTL2_FBPROBE=3: the steady camera draw and color 0 after it. +#include "FetchProbe.h" // the framebuffer-fetch probes, which the draw-note modes 2 and 3 serve +#include +static int gDrawNote=-1; +static bool sweetDrawNoteOn() { + if(gDrawNote<0){const char *e=getenv("SWEET_MTL2_DRAWNOTE");gDrawNote=(e && e[0]>='1' && e[0]<='3')?e[0]-'0':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]; + // SWEET_MTL2_DRAWNOTE=2: the fragment function's framebuffer-fetch constants (QuartzCore's fc_framebuffer_fetch) too + if(gDrawNote>=2 && [(id)d.fragmentFunction respondsToSelector:@selector(constantsText)]) { + typedef std::string (*Text)(id,SEL); // the frontend's NBFunction keeps them as text (name:type:hex, filled when the note is on) + const std::string text=((Text)objc_msgSend)((id)d.fragmentFunction,@selector(constantsText)); + NSString *k=@(text.c_str()); + for(NSString *one in [k componentsSeparatedByString:@" "])if([one rangeOfString:@"fetch"].location!=NSNotFound)[s appendFormat:@" [%@]",one]; + } + 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 bool sweetDrawNoteDraw(id encoder,const char *how,NSUInteger count) { + if(!sweetDrawNoteOn())return false; + NSMutableDictionary *d=objc_getAssociatedObject(encoder,&gDrawNoteKey); + if(!d)return false; + if(sweetFetchDrawProbeOn()) { + NSString *pl=d[@"p"]; + if(pl && [pl rangeOfString:@"frag TimgA3Xhf_Ixrg"].location!=NSNotFound) { + static std::atomic last{0};static std::atomic asked{0}; + const uint64_t now=clock_gettime_nsec_np(CLOCK_UPTIME_RAW)/1000;uint64_t l=last.load(); + if(now-l>=1000000 && last.compare_exchange_strong(l,now) && asked.load()<30) { + const unsigned k=1000+(asked.fetch_add(1)+1); + Ivar iv=class_getInstanceVariable(object_getClass(encoder),"_commandBuffer"); + id cb=iv?object_getIvar(encoder,iv):nil;id c0=objc_getAssociatedObject(encoder,&gFetchC0Key); + if(cb && c0)objc_setAssociatedObject(cb,&gFetchProbeKey,@[c0,@(k)],OBJC_ASSOCIATION_RETAIN_NONATOMIC); + NSMutableString *t=[NSMutableString stringWithFormat:@"native-metal: camera draw %u: %s %lu cb %s | %@ |",k,how,(unsigned long)count,cb&&c0?"probed":"NOT probed",pl]; + for(NSString *key in [d.allKeys sortedArrayUsingSelector:@selector(compare:)]) { + id v=d[key]; + if([key hasPrefix:@"t"] && [v isKindOfClass:[NSString class]])[t appendFormat:@" %@ %@ |",key,v]; + else if([key hasPrefix:@"fb"] && [v isKindOfClass:[NSString class]])[t appendFormat:@" %@ %@ |",key,v]; + else if([key isEqualToString:@"vb1"] && [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+64<=b.length)[t appendFormat:@" vb1 +%lu: %@ |",(unsigned long)off,sweetDrawNoteFloats(c+off,64)]; + } + } + const char *line=t.UTF8String; + for(size_t at=0,n=strlen(line);at said{0}; + if(said.fetch_add(1)<10) { + NSMutableString *s=[NSMutableString stringWithFormat:@"native-metal: luma note: %s %lu | %@ |",how,(unsigned long)count,pl]; + for(NSString *key in [d.allKeys sortedArrayUsingSelector:@selector(compare:)]) { + if([key isEqualToString:@"p"] || [key isEqualToString:@"#"])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)64,b.length-off))]; + } else [s appendFormat:@" %@ %@ |",key,v]; + } + const char *line=s.UTF8String; + for(size_t at=0,n=strlen(line);at ... | vb1 +: the first 8 floats`. + if(gDrawNote==2) { + const unsigned pass=sweetFetchEncoderPass(encoder); + if(pass!=2 && pass!=5 && pass!=8)return false; + static std::atomic lines{0}; + NSNumber *k=d[@"#"];const unsigned draw=k?k.unsignedIntValue+1:1;d[@"#"]=@(draw); + if(lines.fetch_add(1)>=400)return false; + NSMutableString *s=[NSMutableString stringWithFormat:@"native-metal: fb draw %u.%u: %s %lu | %@ |",pass,draw,how,(unsigned long)count,d[@"p"]?:@"(no pipeline)"]; + for(NSString *key in [d.allKeys sortedArrayUsingSelector:@selector(compare:)]) { + id v=d[key]; + if([key hasPrefix:@"t"] && [v isKindOfClass:[NSString class]] && [key length]<=3)[s appendFormat:@" %@ %@ |",key,v]; + else if([key isEqualToString:@"vb1"] && [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+32<=b.length)[s appendFormat:@" vb1 +%lu: %@ |",(unsigned long)off,sweetDrawNoteFloats(c+off,32)]; + } + } + const char *line=s.UTF8String; + for(size_t at=0,n=strlen(line);at=500 && f<=510); + } + if(!ycc)return false; + 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 false; + [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 device=(id)gDeviceObject; + char said[400]; + NSError *error=nil; + dispatch_data_t data=dispatch_data_create(sweet_fetch_probe_metallib,sizeof sweet_fetch_probe_metallib,nullptr,DISPATCH_DATA_DESTRUCTOR_DEFAULT); + id library=[device newLibraryWithData:data error:&error]; + if(!library){snprintf(said,sizeof said,"native-metal: fetch probe: no library: %s",error?error.localizedDescription.UTF8String:"?");sm2_logs(said);return;} + // A pipeline of the three formats (color 2 left out where `three` is false), writing only the attachments of `writes`. + auto pipeline=[&](NSString *fragment,unsigned writes,bool three)->id { + MTLRenderPipelineDescriptor *pd=[MTLRenderPipelineDescriptor new]; + pd.vertexFunction=[library newFunctionWithName:@"sweet_fetch_vert"];pd.fragmentFunction=[library newFunctionWithName:fragment]; + pd.colorAttachments[0].pixelFormat=MTLPixelFormatBGRA8Unorm;pd.colorAttachments[1].pixelFormat=MTLPixelFormatRGBA16Float; + if(three)pd.colorAttachments[2].pixelFormat=MTLPixelFormatR32Float; + for(unsigned i=0;i<3;i++)pd.colorAttachments[i].writeMask=(writes>>i)&1?MTLColorWriteMaskAll:MTLColorWriteMaskNone; + NSError *e=nil; + id state=[device newRenderPipelineStateWithDescriptor:pd error:&e]; + if(!state){char line[300];snprintf(line,sizeof line,"native-metal: fetch probe: pipeline %s (%s) refused: %s",fragment.UTF8String,three?"three":"two", + e?e.localizedDescription.UTF8String:"?");sm2_logs(line);} + return state; + }; + id w1=pipeline(@"sweet_fetch_write1",2,true),r1=pipeline(@"sweet_fetch_read1",1,true); + id w0=pipeline(@"sweet_fetch_write0",1,true),r0=pipeline(@"sweet_fetch_read0",1,true); + id w1b=pipeline(@"sweet_fetch_write1",2,false),r1b=pipeline(@"sweet_fetch_read1",1,false); + id queue=[device newCommandQueue]; + if(!queue)return; + auto texture=[&](MTLPixelFormat format,MTLStorageMode mode)->id { + MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:format width:64 height:64 mipmapped:NO]; + td.usage=MTLTextureUsageRenderTarget|(mode==MTLStorageModeMemoryless?0:MTLTextureUsageShaderRead);td.storageMode=mode; + return [device newTextureWithDescriptor:td]; + }; + enum {Mem,Priv,Half,Clear,Self,Two}; + const char *names[]={"mem","priv","half","clear","self","two"}; + for(int c=Mem;c<=Two;c++) { + id c0=texture(MTLPixelFormatBGRA8Unorm,MTLStorageModeShared); + id c1=c==Self?nil:texture(MTLPixelFormatRGBA16Float,c==Priv?MTLStorageModePrivate:MTLStorageModeMemoryless); + id c2=(c==Self || c==Two)?nil:texture(MTLPixelFormatR32Float,MTLStorageModeMemoryless); + if(!c0 || (c!=Self && !c1)){snprintf(said,sizeof said,"native-metal: fetch probe %s: no texture",names[c]);sm2_logs(said);continue;} + MTLRenderPassDescriptor *pass=[MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture=c0;pass.colorAttachments[0].loadAction=MTLLoadActionClear; + pass.colorAttachments[0].clearColor=MTLClearColorMake(1,0,1,1);pass.colorAttachments[0].storeAction=MTLStoreActionStore; + if(c1) { + pass.colorAttachments[1].texture=c1; + pass.colorAttachments[1].loadAction=c==Clear || c==Priv?MTLLoadActionClear:MTLLoadActionDontCare; + pass.colorAttachments[1].clearColor=c==Clear?MTLClearColorMake(0,1,0,1):MTLClearColorMake(0,0,0,0); + pass.colorAttachments[1].storeAction=c==Priv?MTLStoreActionStore:MTLStoreActionDontCare; + } + if(c2){pass.colorAttachments[2].texture=c2;pass.colorAttachments[2].loadAction=MTLLoadActionDontCare;pass.colorAttachments[2].storeAction=MTLStoreActionDontCare;} + id commands=[queue commandBuffer]; + id re=[commands renderCommandEncoderWithDescriptor:pass]; + auto draw=[&](id state){if(state){[re setRenderPipelineState:state];[re drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];}}; + switch(c) { + case Mem:case Priv:draw(w1);draw(r1);break; + case Half:{MTLScissorRect left={0,0,32,64},all={0,0,64,64};[re setScissorRect:left];draw(w1);[re setScissorRect:all];draw(r1);break;} + case Clear:draw(r1);break; + case Self:{ + // color 0 alone: pipelines of one attachment + MTLRenderPipelineDescriptor *pd=[MTLRenderPipelineDescriptor new]; + pd.vertexFunction=[library newFunctionWithName:@"sweet_fetch_vert"];pd.colorAttachments[0].pixelFormat=MTLPixelFormatBGRA8Unorm; + pd.fragmentFunction=[library newFunctionWithName:@"sweet_fetch_write0"];id a=[device newRenderPipelineStateWithDescriptor:pd error:nil]; + pd.fragmentFunction=[library newFunctionWithName:@"sweet_fetch_read0"];id b=[device newRenderPipelineStateWithDescriptor:pd error:nil]; + (void)w0;(void)r0;draw(a);draw(b);break;} + case Two:draw(w1b);draw(r1b);break; + } + [re endEncoding]; + [commands commit];[commands waitUntilCompleted]; + uint8_t px[64*64*4]={}; + [c0 getBytes:px bytesPerRow:64*4 fromRegion:MTLRegionMake2D(0,0,64,64) mipmapLevel:0]; + unsigned long s[2][4]={}; + for(unsigned y=0;y<64;y++)for(unsigned x=0;x<64;x++)for(unsigned k=0;k<4;k++)s[x>=32][k]+=px[(y*64+x)*4+k]; + snprintf(said,sizeof said,"native-metal: fetch probe %s: left %lu %lu %lu %lu, right %lu %lu %lu %lu (status %ld%s%s)",names[c], + s[0][0]/2048,s[0][1]/2048,s[0][2]/2048,s[0][3]/2048,s[1][0]/2048,s[1][1]/2048,s[1][2]/2048,s[1][3]/2048,(long)commands.status, + commands.error?": ":"",commands.error?commands.error.localizedDescription.UTF8String:""); + sm2_logs(said); + } +} +#endif +// From the device's making: in the window server only, start the probe 25 s later, off every caller's thread. +static void sweetFetchProbeStart() { +#ifdef SWEET_FETCH_PROBE + if(!sweetFetchProbeOn() || strcmp(getprogname(),"backboardd"))return; + static std::atomic started{false}; + if(started.exchange(true))return; + static dispatch_queue_t lane=dispatch_queue_create("scion.fetch-probe",DISPATCH_QUEUE_SERIAL); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW,25*NSEC_PER_SEC),lane,^{@autoreleasepool{sweetFetchProbeRun();}}); +#endif +} +// SWEET_MTL2_FBPROBE=2 (window server only), the main pass's color 1: while a converted two-plane YCbCr texture (formats 500 to 510, the +// camera preview) was bound in the last 2 s, a render pass whose color 1 is a memoryless RGBA16Float texture of color 0's size (at +// least 1000 high) gets instead a private texture of that size (one, kept), cleared at its load and stored, the shadow. Every 2 s from +// 4 s after the first such pass (20 probes at most), after its command buffer: a compute pass of the same queue reads an 8 x 8 grid of +// the shadow over the viewfinder's rows (178 to 1284 of 1702; the whole height of another target), and the processor reads the same +// grid of color 0's surface when the command buffer completes. Said: `native-metal: fetch shadow N: c1 R G B A, K of 64 lit` and +// `... c0 R G B A, K of 64 lit` (0 to 255; lit: luma above 24). With SWEET_MTL2_DRAWNOTE=2 the draws of probes 2, 5 and 8's passes +// are said too (DrawNote.h). Writes nothing the window server reads but the shadow. Run on phone 1 on 24 November (F3). +static std::atomic gFetchYccUs{0}; +static std::atomic gFetchShadowPasses{0},gFetchShadowProbes{0}; +static std::mutex gFetchShadowLock; +static id gFetchShadow; +static id gFetchGrid; +static char gFetchProbeKey,gFetchEncoderKey; +// SWEET_MTL2_FBPROBE=3 (window server only): a draw of CoreAnimation's direct camera layer function (TimgA3Xhf_Ixrg..., the steady +// preview draw into color 0) asks, at most once a second and 30 times a process, that its command buffer's completion read the +// same 8 x 8 viewfinder grid of that pass's color 0 surface on the processor (`fetch shadow N: c0 ...`, N from 1001), and says the +// draw: `native-metal: camera draw N: PIPELINE | t3 ... | vb1 ...`. +static char gFetchC0Key; +static bool sweetFetchDrawProbeOn() { + static int on=-1; + if(on<0){const char *e=getenv("SWEET_MTL2_FBPROBE");on=(e && e[0]=='3' && !strcmp(getprogname(),"backboardd"))?1:0;} + return on==1; +} +static bool sweetFetchShadowOn() { + static int on=-1; + if(on<0){const char *e=getenv("SWEET_MTL2_FBPROBE");on=(e && e[0]=='2' && !strcmp(getprogname(),"backboardd"))?1:0;} + return on==1; +} +static void sweetFetchSawYcc(uint64_t format) { + if(format>=500 && format<=510)gFetchYccUs.store(clock_gettime_nsec_np(CLOCK_UPTIME_RAW)/1000,std::memory_order_relaxed); +} +// The probe number of the shadow pass `encoder` draws (0 for every other encoder). +static unsigned sweetFetchEncoderPass(id encoder) { + NSNumber *n=encoder?objc_getAssociatedObject(encoder,&gFetchEncoderKey):nil;return n?n.unsignedIntValue:0; +} +static void sweetFetchRect(id t,uint32_t r[4]) { + const uint32_t w=(uint32_t)t.width,h=(uint32_t)t.height; + r[0]=0;r[2]=w; + if(h==1702){r[1]=178;r[3]=1106;}else{r[1]=0;r[3]=h;} +} +// From renderCommandEncoderWithDescriptor: the descriptor to use, and the probe number of a probed shadow pass (else 0). +static MTLRenderPassDescriptor *sweetFetchShadowPass(MTLRenderPassDescriptor *d,id commandBuffer,unsigned *number) { + *number=0; +#ifdef SWEET_FETCH_PROBE + if(!sweetFetchShadowOn() || !gDeviceObject)return d; + id c1=d.colorAttachments[1].texture; + id c0=d.colorAttachments[0].texture; + if(!c1 || !c0 || c1.storageMode!=MTLStorageModeMemoryless || c1.pixelFormat!=MTLPixelFormatRGBA16Float || c1.width!=c0.width || c1.height!=c0.height || c1.height<1000)return d; + const uint64_t seen=gFetchYccUs.load(std::memory_order_relaxed),now=clock_gettime_nsec_np(CLOCK_UPTIME_RAW)/1000; + if(!seen || now-seen>2000000)return d; + id shadow; + { + std::lock_guard hold(gFetchShadowLock); + if(!gFetchShadow || gFetchShadow.width!=c1.width || gFetchShadow.height!=c1.height) { + MTLTextureDescriptor *td=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA16Float width:c1.width height:c1.height mipmapped:NO]; + td.usage=MTLTextureUsageRenderTarget|MTLTextureUsageShaderRead;td.storageMode=MTLStorageModePrivate; + gFetchShadow=[(id)gDeviceObject newTextureWithDescriptor:td]; + char said[160];snprintf(said,sizeof said,"native-metal: fetch shadow: %s %lux%lu",gFetchShadow?"made":"NOT made",(unsigned long)c1.width,(unsigned long)c1.height);sm2_logs(said); + } + if(!gFetchGrid) { + dispatch_data_t data=dispatch_data_create(sweet_fetch_probe_metallib,sizeof sweet_fetch_probe_metallib,nullptr,DISPATCH_DATA_DESTRUCTOR_DEFAULT); + id library=[(id)gDeviceObject newLibraryWithData:data error:nil]; + id f=[library newFunctionWithName:@"sweet_fetch_grid"]; + gFetchGrid=f?[(id)gDeviceObject newComputePipelineStateWithFunction:f error:nil]:nil; + } + shadow=gFetchShadow; + } + if(!shadow)return d; + MTLRenderPassDescriptor *copy=[d copy]; + copy.colorAttachments[1].texture=shadow;copy.colorAttachments[1].loadAction=MTLLoadActionClear; + copy.colorAttachments[1].clearColor=MTLClearColorMake(0,0,0,0);copy.colorAttachments[1].storeAction=MTLStoreActionStore; + // a probe every 2 s from 4 s after the first such pass (20 at most); its pass is the one the draw notes describe (probes 2, 5 and 8) + static std::atomic first{0},last{0}; + gFetchShadowPasses.fetch_add(1); + uint64_t f=first.load();if(!f){first.compare_exchange_strong(f,now);f=first.load();} + uint64_t l=last.load(); + if(now-f>=4000000 && now-l>=2000000 && last.compare_exchange_strong(l,now)) { + const unsigned k=gFetchShadowProbes.fetch_add(1)+1; + if(k<=20){*number=k;objc_setAssociatedObject(commandBuffer,&gFetchProbeKey,@[c0,@(k)],OBJC_ASSOCIATION_RETAIN_NONATOMIC);} + } + return copy; +#else + (void)commandBuffer;return d; +#endif +} +#ifdef SWEET_FETCH_PROBE +static void sweetFetchSay(unsigned n,const char *what,const float *c,bool bytes) { + 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])*(bytes?1.0:255.0)>24.0;} + const double s=bytes?1.0/64:255.0/64; + char said[200];snprintf(said,sizeof said,"native-metal: fetch shadow %u: %s %.0f %.0f %.0f %.0f, %u of 64 lit",n,what,r*s,g*s,b*s,a*s,lit);sm2_logs(said); +} +// Wrapped at load: a render encoder's making takes the shadow pass's descriptor, and its encoder is marked with the probe number; +// with SWEET_MTL2_FBPROBE=3 every encoder keeps its color 0 texture (for the camera draw probe in DrawNote.h). +__attribute__((constructor)) static void sweetFetchShadowEncoderInstall() { + Class cls=NSClassFromString(@"NBCommandBuffer");const SEL make=@selector(renderCommandEncoderWithDescriptor:); + Method m=cls?class_getInstanceMethod(cls,make):nullptr; + if(!m)return; + typedef id (*F)(id,SEL,MTLRenderPassDescriptor *);const F old=(F)method_getImplementation(m); + method_setImplementation(m,imp_implementationWithBlock(^id(id self,MTLRenderPassDescriptor *d) { + sweetFetchProbeStart(); + unsigned n=0;MTLRenderPassDescriptor *use=sweetFetchShadowPass(d,self,&n); + id encoder=old(self,make,use); + if(encoder && sweetFetchDrawProbeOn() && d.colorAttachments[0].texture)objc_setAssociatedObject(encoder,&gFetchC0Key,d.colorAttachments[0].texture,OBJC_ASSOCIATION_RETAIN_NONATOMIC); + if(n && encoder)objc_setAssociatedObject(encoder,&gFetchEncoderKey,@(n),OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return encoder; + })); +} +// Wrapped at load: a command buffer with a probe request commits, then a probe of the shadow follows it on its queue. +__attribute__((constructor)) static void sweetFetchShadowInstall() { + 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) { + NSArray *req=objc_getAssociatedObject(self,&gFetchProbeKey); + if(!req){old(self,commit);return;} + objc_setAssociatedObject(self,&gFetchProbeKey,nil,OBJC_ASSOCIATION_RETAIN_NONATOMIC); + id c0=req[0];const unsigned n=[req[1] unsignedIntValue]; + [(id)self addCompletedHandler:^(id) { + IOSurfaceRef s=c0.iosurface; + if(!s || IOSurfaceGetBytesPerElement(s)!=4 || IOSurfaceLock(s,kIOSurfaceLockReadOnly,nullptr)){sm2_logs("native-metal: fetch shadow: c0 not read");return;} + const uint8_t *base=(const uint8_t *)IOSurfaceGetBaseAddress(s);const size_t bpr=IOSurfaceGetBytesPerRow(s); + uint32_t r[4];sweetFetchRect(c0,r);float px[256]; + sys_dcache_flush((void *)base,bpr*IOSurfaceGetHeight(s)); + for(unsigned y=0;y<8;y++)for(unsigned x=0;x<8;x++){const uint8_t *p=base+(size_t)(r[1]+r[3]*(2*y+1)/16)*bpr+(size_t)(r[0]+r[2]*(2*x+1)/16)*4; + float *q=px+4*(y*8+x);q[0]=p[2];q[1]=p[1];q[2]=p[0];q[3]=p[3];} + IOSurfaceUnlock(s,kIOSurfaceLockReadOnly,nullptr); + sweetFetchSay(n,"c0 (surface, RGBA bytes)",px,true); + }]; + old(self,commit); + id shadow;{std::lock_guard hold(gFetchShadowLock);shadow=gFetchShadow;} + if(!shadow || !gFetchGrid)return; + id out=[(id)gDeviceObject newBufferWithLength:64*4*sizeof(float) options:MTLResourceStorageModeShared]; + id probe=[[(id)self commandQueue] commandBuffer]; + if(!out || !probe)return; + uint32_t r[4];sweetFetchRect(shadow,r); + id e=[probe computeCommandEncoder]; + [e setComputePipelineState:gFetchGrid];[e setTexture:shadow atIndex:0];[e setBuffer:out offset:0 atIndex:0];[e setBytes:r length:sizeof r atIndex:1]; + [e dispatchThreadgroups:MTLSizeMake(1,1,1) threadsPerThreadgroup:MTLSizeMake(8,8,1)];[e endEncoding]; + [probe addCompletedHandler:^(id done) { + if(done.status!=MTLCommandBufferStatusCompleted){char said[120];snprintf(said,sizeof said,"native-metal: fetch shadow %u: c1 probe status %ld",n,(long)done.status);sm2_logs(said);return;} + sweetFetchSay(n,"c1 (shadow, RGBA)",(const float *)out.contents,false); + }]; + [probe commit]; + })); +} +#endif diff --git a/tools/ios27/metal2/FetchProbe.metal b/tools/ios27/metal2/FetchProbe.metal new file mode 100644 index 000000000..c4bd3ec22 --- /dev/null +++ b/tools/ios27/metal2/FetchProbe.metal @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MIT-0 +// Framebuffer fetch through a memoryless color attachment (docs/ios27/CAMERA.md, "The display side"): the shape of +// CoreAnimation's camera layer draw in the window server's main pass, on a small target. Built by +// tools/ios27/metal/mk-bundle27.sh into FetchProbe.inc; used by FetchProbe.h. +// color 0: BGRA8Unorm (the framebuffer), color 1: RGBA16Float, color 2: R32Float (both memoryless in the window server). +// sweet_fetch_write1: writes color 1 only (the pipeline masks color 0 and 2 off), as TimgA3S1Xhfu_Ixrg does. +// sweet_fetch_read1: reads color 1 by framebuffer fetch and writes color 0, as TimgBbcmA3Xhf_Isup does. +// sweet_fetch_write0 / sweet_fetch_read0: the same through color 0 itself (a blend done in the shader). +#include +using namespace metal; + +vertex float4 sweet_fetch_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); +} + +struct SweetFetchColor1 { + half4 c1 [[color(1)]]; +}; +struct SweetFetchColor0 { + half4 c0 [[color(0)]]; +}; + +fragment SweetFetchColor1 sweet_fetch_write1() { + return {half4(0.25h, 0.5h, 0.75h, 1.0h)}; +} + +fragment SweetFetchColor0 sweet_fetch_read1(half4 c1 [[color(1)]]) { + return {c1}; +} + +fragment SweetFetchColor0 sweet_fetch_write0() { + return {half4(0.25h, 0.5h, 0.75h, 1.0h)}; +} + +fragment SweetFetchColor0 sweet_fetch_read0(half4 c0 [[color(0)]]) { + return {half4(c0.rgb * 0.5h, 1.0h)}; +} + +// The shadow probe (SWEET_MTL2_FBPROBE=2): an 8 x 8 grid of a texture read inside a rectangle (x, y, w, h) of it. +kernel void sweet_fetch_grid(texture2d t [[texture(0)]], device float4 *out [[buffer(0)]], + constant uint4 &r [[buffer(1)]], uint2 c [[thread_position_in_grid]]) { + if (c.x >= 8 || c.y >= 8) + return; + const uint2 at = uint2(r.x + r.z * (2 * c.x + 1) / 16, r.y + r.w * (2 * c.y + 1) / 16); + out[c.y * 8 + c.x] = t.read(at); +} diff --git a/tools/ios27/metal2/NativeBridgeMetalFrontend.mm b/tools/ios27/metal2/NativeBridgeMetalFrontend.mm index 9e4f4bcf6..2f5ea2a4b 100644 --- a/tools/ios27/metal2/NativeBridgeMetalFrontend.mm +++ b/tools/ios27/metal2/NativeBridgeMetalFrontend.mm @@ -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"}]; } @@ -630,7 +632,7 @@ - (NSData *)bitCodeWithHash:(const void *)hash {(void)hash;return nil;} } } std::string text; - if(!gJournalPath.empty()) { + if(!gJournalPath.empty() || sweetDrawNoteOn()) { for(const NmbConstant &c:constants) { char head[32];if(!c.name)snprintf(head,sizeof head,"#%llu",(unsigned long long)c.index); text+=text.empty()?"":" ";text+=c.name?c.name:head;snprintf(head,sizeof head,":%llu:",(unsigned long long)c.type);text+=head; @@ -928,12 +930,18 @@ - (void)texture:(id)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);sweetFetchSawYcc(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); +}