2014 snapchat source code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
2.3 KiB

  1. //
  2. // SCMetalUtils.h
  3. // Snapchat
  4. //
  5. // Created by Michel Loenngren on 7/11/17.
  6. //
  7. // Utility class for metal related helpers.
  8. #import <Foundation/Foundation.h>
  9. #if !TARGET_IPHONE_SIMULATOR
  10. #import <Metal/Metal.h>
  11. #endif
  12. #import <AVFoundation/AVFoundation.h>
  13. #import <SCBase/SCMacros.h>
  14. SC_EXTERN_C_BEGIN
  15. #if !TARGET_IPHONE_SIMULATOR
  16. extern id<MTLDevice> SCGetManagedCaptureMetalDevice(void);
  17. #endif
  18. static SC_ALWAYS_INLINE BOOL SCDeviceSupportsMetal(void)
  19. {
  20. #if TARGET_CPU_ARM64
  21. return YES; // All 64 bit system supports Metal.
  22. #else
  23. return NO;
  24. #endif
  25. }
  26. #if !TARGET_IPHONE_SIMULATOR
  27. static inline id<MTLTexture> SCMetalTextureFromPixelBuffer(CVPixelBufferRef pixelBuffer, size_t planeIndex,
  28. MTLPixelFormat pixelFormat,
  29. CVMetalTextureCacheRef textureCache)
  30. {
  31. size_t width = CVPixelBufferGetWidthOfPlane(pixelBuffer, planeIndex);
  32. size_t height = CVPixelBufferGetHeightOfPlane(pixelBuffer, planeIndex);
  33. CVMetalTextureRef textureRef;
  34. if (kCVReturnSuccess != CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer,
  35. nil, pixelFormat, width, height, planeIndex,
  36. &textureRef)) {
  37. return nil;
  38. }
  39. id<MTLTexture> texture = CVMetalTextureGetTexture(textureRef);
  40. CVBufferRelease(textureRef);
  41. return texture;
  42. }
  43. static inline void SCMetalCopyTexture(id<MTLTexture> texture, CVPixelBufferRef pixelBuffer, NSUInteger planeIndex)
  44. {
  45. CVPixelBufferLockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
  46. void *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, planeIndex);
  47. NSUInteger bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, planeIndex);
  48. MTLRegion region = MTLRegionMake2D(0, 0, CVPixelBufferGetWidthOfPlane(pixelBuffer, planeIndex),
  49. CVPixelBufferGetHeightOfPlane(pixelBuffer, planeIndex));
  50. [texture getBytes:baseAddress bytesPerRow:bytesPerRow fromRegion:region mipmapLevel:0];
  51. CVPixelBufferUnlockBaseAddress(pixelBuffer, kCVPixelBufferLock_ReadOnly);
  52. }
  53. #endif
  54. SC_EXTERN_C_END