文件
dayu-color/大鱼调色/Plugin/DYFaceRender.inc.h
T

62 行
8.0 KiB
C++

// Authored adaptation of Vision face support in FCP-BeautyGirl (MIT).
// Geometry is rebuilt from this input frame; no previous-shot mask is reused.
- (void)prepareFaceSupport:(FxImageTile*)source {
[_faceEntries release];_faceEntries=nil;std::vector<DYToolMaskEntry> entries;
FxRect image=source.imagePixelBounds,tile=source.tilePixelBounds;
if(image.left!=tile.left||image.right!=tile.right||image.top!=tile.top||image.bottom!=tile.bottom)return;
NSMutableDictionary *device=[self device:source.deviceRegistryID error:nil];id<MTLTexture>texture=[source metalTextureForDevice:device[@"device"]];if(!texture)return;
if(!_faceContext)_faceContext=[[CIContext contextWithMTLDevice:device[@"device"] options:@{kCIContextCacheIntermediates:@NO}]retain];
CGColorSpaceRef linear=CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB);
CIImage *input=[CIImage imageWithMTLTexture:texture options:@{kCIImageColorSpace:(id)linear}];CGColorSpaceRelease(linear);if(!input)return;
// CIImage's MTLTexture coordinates are bottom-up; normalize FxPlug top-first rows.
if(source.imageOrigin==kFxImageOrigin_TOP_LEFT)input=[input imageByApplyingTransform:CGAffineTransformMake(1,0,0,-1,0,input.extent.size.height)];
CGFloat scale=MIN(1.,960./MAX(input.extent.size.width,input.extent.size.height));input=[input imageByApplyingTransform:CGAffineTransformMakeScale(scale,scale)];
CGColorSpaceRef srgb=CGColorSpaceCreateWithName(kCGColorSpaceSRGB);CGImageRef cg=[_faceContext createCGImage:input fromRect:input.extent format:kCIFormatRGBA8 colorSpace:srgb];CGColorSpaceRelease(srgb);if(!cg)return;
NSData *raster=[(NSData*)CGDataProviderCopyData(CGImageGetDataProvider(cg)) autorelease];
if(raster&&[_faceInput isEqualToData:raster]){_faceEntries=[_faceCachedEntries retain];CGImageRelease(cg);return;}
VNDetectFaceLandmarksRequest *request=[VNDetectFaceLandmarksRequest new];request.revision=VNDetectFaceLandmarksRequestRevision3;request.constellation=VNRequestFaceLandmarksConstellation76Points;
VNImageRequestHandler *handler=[[VNImageRequestHandler alloc]initWithCGImage:cg orientation:kCGImagePropertyOrientationUp options:@{}];CGImageRelease(cg);
BOOL detected=[handler performRequests:@[request] error:nil];NSUInteger originalEntryCount=0;
if(detected)for(VNFaceObservation *face in request.results){
if(originalEntryCount>64||face.confidence<.5||face.landmarks.faceContour.pointCount<3||face.landmarks.faceContour.pointCount>243)continue;CGRect box=face.boundingBox;if(box.size.width<.015||box.size.height<.015)continue;
DYToolMaskEntry support{};support.section=-100;support.mask.parameters=dyDefaultMaskParameters();auto &p=support.mask.parameters;p.kind=DYMaskBezier;p.centerX=CGRectGetMidX(box);p.centerY=1-CGRectGetMidY(box);p.width=box.size.width;p.height=box.size.height;p.feather=.1;
auto &path=support.mask.path;VNFaceLandmarkRegion2D *contour=face.landmarks.faceContour;
for(NSUInteger i=0;i<contour.pointCount;i++){CGPoint q=contour.normalizedPoints[i];path.x[path.count]=q.x-.5;path.y[path.count]=.5-q.y;path.count++;}
// Close the jaw along a soft forehead cap, instead of selecting the whole box.
BOOL forward=path.x[path.count-1]>path.x[0];for(int i=0;i<=12;i++){float t=i/12.f,x=forward?1-t:t;path.x[path.count]=x-.5;path.y[path.count]=-.28-.28*sinf(t*M_PI);path.count++;}
auto xs=std::minmax_element(path.x,path.x+path.count),ys=std::minmax_element(path.y,path.y+path.count);
// Small padding protects the conservative bound against GPU rounding.
constexpr float padding=1e-5f;
support.minX=p.centerX+*xs.first*p.width-padding;support.maxX=p.centerX+*xs.second*p.width+padding;
support.minY=p.centerY+*ys.first*p.height-padding;support.maxY=p.centerY+*ys.second*p.height+padding;
entries.push_back(support);originalEntryCount+=2;
for(VNFaceLandmarkRegion2D *region in @[face.landmarks.leftEye?:[NSNull null],face.landmarks.rightEye?:[NSNull null],face.landmarks.outerLips?:[NSNull null],face.landmarks.leftEyebrow?:[NSNull null],face.landmarks.rightEyebrow?:[NSNull null]]){
if(![region isKindOfClass:VNFaceLandmarkRegion2D.class]||!region.pointCount)continue;CGFloat loX=1,loY=1,hiX=0,hiY=0;for(NSUInteger i=0;i<region.pointCount;i++){CGPoint q=region.normalizedPoints[i];loX=MIN(loX,q.x);hiX=MAX(hiX,q.x);loY=MIN(loY,q.y);hiY=MAX(hiY,q.y);}
DYToolMaskEntry hole{};hole.section=-101;hole.mask.parameters=dyDefaultMaskParameters();auto &h=hole.mask.parameters;h.kind=DYMaskEllipse;h.centerX=box.origin.x+(loX+hiX)*.5*box.size.width;h.centerY=1-(box.origin.y+(loY+hiY)*.5*box.size.height);h.width=(hiX-loX)*box.size.width*1.2;h.height=MAX(.035,hiY-loY)*box.size.height*1.6;h.feather=.35;entries.push_back(hole);originalEntryCount++;
}
}
[handler release];[request release];
if(!detected)return;
_faceEntries=[[NSData alloc]initWithBytes:entries.data() length:entries.size()*sizeof(DYToolMaskEntry)];
[_faceInput release];_faceInput=[raster retain];
[_faceCachedEntries release];_faceCachedEntries=[_faceEntries retain];
}
- (BOOL)renderSource:(FxImageTile*)src destination:(FxImageTile*)dst uniforms:(DYUniforms)u paths:(NSDictionary*)paths spider:(NSData*)spider tools:(NSDictionary*)tools error:(NSError**)error {@synchronized(self){
DYUniforms effective=DYEffectiveFaceUniforms(u,paths,tools);BOOL face=effective.skinProtection.x>.5&&(effective.skinProtection.y>0||effective.skinVisualize>.5)&&(effective.skinFaceOnly>.5||effective.skinVisualize>.5);for(NSDictionary *node in tools[@"layers"]){
if(face)break;
if(![node[@"type"]isEqual:@"skin"]||DYToolIsNeutral(node))continue;
DYUniforms layer=DYToolUniforms(node);
face=layer.skinProtection.x>.5&&(layer.skinFaceOnly>.5||layer.skinVisualize>.5);
}
if(face&&!_exporting)[self prepareFaceSupport:src];else{[_faceEntries release];_faceEntries=nil;}
BOOL ok=[self renderToolsSource:src destination:dst uniforms:u paths:paths spider:spider tools:tools error:error];
return ok;
}}
- (BOOL)renderLens:(FxImageTile*)source destination:(FxImageTile*)destination uniforms:(DYUniforms)u masks:(NSArray*)masks entry:(NSDictionary*)entry error:(NSError**)error {
if(source.imageOrigin==kFxImageOrigin_BOTTOM_LEFT)u.lensCenterY=1-u.lensCenterY;
id<MTLDevice>d=entry[@"device"];id<MTLTexture>before=[source metalTextureForDevice:d],output=[destination metalTextureForDevice:d];
id<MTLComputePipelineState> pipeline=[self computePipeline:@"dyLensRepair" entry:entry error:error];if(!pipeline)return NO;
id<MTLCommandBuffer>cb=[entry[@"queue"]commandBuffer];id<MTLComputeCommandEncoder>ce=[cb computeCommandEncoder];if(!ce||!before||!output)return fail(error,@"无法创建修复镜头编码器");[ce setComputePipelineState:pipeline];[ce setTexture:before atIndex:0];[ce setTexture:output atIndex:1];[ce setBytes:&u length:sizeof(u) atIndex:0];float aspect=before.width*source.pixelAspect/MAX(1.,(double)before.height);[ce setBytes:&aspect length:sizeof(aspect) atIndex:1];[ce dispatchThreads:MTLSizeMake(output.width,output.height,1)threadsPerThreadgroup:MTLSizeMake(16,16,1)];[ce endEncoding];
if(!masks.count)return [self completeCommands:cb destination:destination texture:output entry:entry]?YES:fail(error,cb.error.localizedDescription);MTLTextureDescriptor *desc=[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:output.pixelFormat width:output.width height:output.height mipmapped:NO];desc.storageMode=MTLStorageModePrivate;desc.usage=MTLTextureUsageShaderRead|MTLTextureUsageShaderWrite|MTLTextureUsageRenderTarget;id<MTLTexture>blend=[d newTextureWithDescriptor:desc];if(!blend)return fail(error,@"无法分配修复蒙版");DYToolMaskHeader h{};h.section=(int)[DYToolTypes()indexOfObject:@"lens"];id<MTLBuffer>buffer=[self maskBuffer:@{@"lens":masks}tile:source device:d header:&h];if(![self encodeBlend:before after:output output:blend masks:buffer header:h entry:entry commands:cb error:error]){[blend release];return NO;}DYExportTile *tile=[[DYExportTile alloc]initWithTexture:blend registry:d.registryID];[tile setBounds:destination.tilePixelBounds origin:destination.imageOrigin];[tile setPixelAspect:destination.pixelAspect];BOOL ok=[self copyTile:tile to:destination rotation:0 entry:entry commands:cb error:error];[tile release];[blend release];return ok;
}