MPSTemporaryImage

Struct MPSTemporaryImage 

Source
pub struct MPSTemporaryImage { /* private fields */ }
Available on crate feature MPSImage only.
Expand description

Dependencies: MPSImage

MPSTemporaryImages are for MPSImages with short lifetimes.

What is temporary memory? It is memory, plain and simple. Analogy: If we use an app as an analogy for a command buffer, then “Regular memory” (such as what backs a MPSImage or the typical MTLTexture) would be memory that you allocate at launch and never free. Temporary memory would be memory that you free when you are done with it so it can be used for something else as needed later in your app. You /could/ write your app to allocate everything you will ever need up front, but this is very inefficient and quite frankly a pain to plan out in advance. You don’t do it for your app, so why would you do it for your command buffers?

Welcome to the 1970’s! We have added a heap.

Unsurprisingly, MPSTemporaryImages can provide for profound reduction in the the amount of memory used by your application. Like malloc, MPS maintains a heap of memory usable in a command buffer. Over the lifetime of a command buffer, the same piece of memory may be reused many times. This means that each time the same memory is reused, it aliases with previous uses. If we aren’t careful, we might find that needed data is overwritten by successive allocations. However, this is no different than accessing freed memory only to discover it doesn’t contain what you thought it did anymore, so you should be able to keep out of trouble by following a few simple rules, like with malloc.

To this end, we added some restrictions to help you out and get a bit more performance. Some comments are appended in parentheses below to extend the analogy of command buffer = program:

  • The textures are MTLStorageModePrivate. You can not, for example, use [MTLTexture getBytes…] or [MTLTexture replaceRegion…] with them. MPSTemporaryImages are strictly read and written by the GPU. (There is protected memory to prevent other processes from overwriting your heap.)

  • The temporary image may be used only on a single MTLCommandBuffer. This limits the chronology to a single linear time stream. (The heap is specific to just one command buffer. There are no mutexes to coordinate timing of simultaneous access by multiple GPUs. Nor are we likely to like them if there were. So, we disallow it.)

  • The readCount property must be managed correctly. Please see the description of the readCount property for full details. (The readCount is a reference count for the block of memory that holds your data. The usual undefined behaviors apply to reading data that has been released. We assert when we can to prevent that from happening accidentally, just as a program might segfault. The readCount counts procedural users of the object – MPSKernel.encode… calls that read the MPSTemporaryImage. As each reads from it, the readCount is automatically decremented. The texture data will be freed in typical usage at the right time as the readCount reaches zero, typically with little user involvement other than to set the readCount up front. We did examine using the main MPSTemporaryImage reference count for this instead so that ARC would do work for you automatically. Alas, ARC destroys things at end of scope rather than promptly, sometimes resulting in greatly increased memory usage. These allocations are large! So, we use this method instead.)

Since MPSTemporaryImages can only be used with a single MTLCommandBuffer, and can not be used off the GPU, they generally should not be kept around past the completion of the MTLCommandBuffer. The lifetime of MPSTemporaryImages is expected to be typically extremely short, perhaps only a few lines of code. Like malloc, it is intended to be fairly cheap to make MPSTemporaryImages and throw them away. Please do so.

To keep the lifetime of the underlying texture allocation as short as possible, the underlying texture is not allocated until the first time the MPSTemporaryImage is used by a MPSCNNKernel or the .texture property is read. The readCount property serves to limit the lifetime on the other end.

You may use the MPSTemporaryImage.texture with MPSUnaryImageKernel -encode… methods, iff featureChannels < = 4 and the MTLTexture conforms to requirements of that MPSKernel. There is no locking mechanism provided to prevent a MTLTexture returned from the .texture property from becoming invalid when the readCount reaches 0.

Finally, MPSTemporaryImages are complicated to use with blit encoders. Your application should assume that the MPSTemporaryImage is backed by a MTLHeap, and consequently needs a MTLFence to ensure that compute command encoders and other encoders do not trip over one another with heap based memory. MPS will almost never use a blit encoder for this reason. If you do need one, then you will need to make a new compute encoder to block on whatever previous compute encoder last used the heap block. (MPS will not tell you who previously used the heap block. That encoder is almost certainly long dead anyway.) If concurrent encoders are involved, then a barrier might be needed. Within that compute encoder, you will call -updateFence. End the compute encoder, make a blit encoder wait for the fence, do the blit, update a new fence, then make a new compute encoder, wait for the second fence, then you can continue. Possibly the second do-nothing compute encoder needs to be ended so MPS can be called. Frankly, we don’t bother with blit encoders and just write a compute operation for copy / clear as needed, or better yet find a way to eliminate the clear / copy pass so we don’t have to pay for it. Note: the most common use of a blit encoder, -synchronizeResource: can not encounter this problem because MPSTemporaryImages live in GPU private memory and can not be read by the CPU.

MPSTemporaryImages can otherwise be used wherever MPSImages are used.

See also Apple’s documentation

Implementations§

Source§

impl MPSTemporaryImage

Source

pub unsafe fn defaultAllocator() -> Retained<ProtocolObject<dyn MPSImageAllocator>>

Available on crate feature MPSCore only.

Get a well known MPSImageAllocator that makes MPSTemporaryImages

Source

pub unsafe fn temporaryImageWithCommandBuffer_imageDescriptor( command_buffer: &ProtocolObject<dyn MTLCommandBuffer>, image_descriptor: &MPSImageDescriptor, ) -> Retained<Self>

Available on crate feature MPSCore only.

Initialize a MPSTemporaryImage for use on a MTLCommandBuffer

Parameter commandBuffer: The MTLCommandBuffer on which the MPSTemporaryImage will be exclusively used

Parameter imageDescriptor: A valid imageDescriptor describing the MPSImage format to create.

Returns: A valid MPSTemporaryImage. The object will be released when the command buffer is committed. The underlying texture will become invalid before this time due to the action of the readCount property.

Source

pub unsafe fn temporaryImageWithCommandBuffer_textureDescriptor( command_buffer: &ProtocolObject<dyn MTLCommandBuffer>, texture_descriptor: &MTLTextureDescriptor, ) -> Retained<Self>

Available on crate feature MPSCore only.

Low level interface for creating a MPSTemporaryImage using a MTLTextureDescriptor

This function provides access to MTLPixelFormats not typically covered by -initForCommandBuffer:imageDescriptor: The feature channels will be inferred from the MTLPixelFormat without changing the width. The following restrictions apply:

MTLTextureType must be MTLTextureType2D or MTLTextureType2DArray MTLTextureUsage must contain at least one of MTLTextureUsageShaderRead, MTLTextureUsageShaderWrite MTLStorageMode must be MTLStorageModePrivate depth must be 1

Parameter commandBuffer: The command buffer on which the MPSTemporaryImage may be used

Parameter textureDescriptor: A texture descriptor describing the MPSTemporaryImage texture

Returns: A valid MPSTemporaryImage. The object will be released when the command buffer is committed. The underlying texture will become invalid before this time due to the action of the readCount property.

Source

pub unsafe fn temporaryImageWithCommandBuffer_textureDescriptor_featureChannels( command_buffer: &ProtocolObject<dyn MTLCommandBuffer>, texture_descriptor: &MTLTextureDescriptor, feature_channels: NSUInteger, ) -> Retained<Self>

Available on crate feature MPSCore only.

Low level interface for creating a MPSTemporaryImage using a MTLTextureDescriptor

This function provides access to MTLPixelFormats not typically covered by -initForCommandBuffer:imageDescriptor: The number of images will be inferred from number of slices in the descriptor.arrayLength and the number of feature channels.

The following restrictions apply:

MTLTextureType must be MTLTextureType2D or MTLTextureType2DArray MTLTextureUsage must contain at least one of MTLTextureUsageShaderRead, MTLTextureUsageShaderWrite MTLStorageMode must be MTLStorageModePrivate

Parameter commandBuffer: The command buffer on which the MPSTemporaryImage may be used

Parameter textureDescriptor: A texture descriptor describing the MPSTemporaryImage texture

Returns: A valid MPSTemporaryImage. The object will be released when the command buffer is committed. The underlying texture will become invalid before this time due to the action of the readCount property.

Source

pub unsafe fn prefetchStorageWithCommandBuffer_imageDescriptorList( command_buffer: &ProtocolObject<dyn MTLCommandBuffer>, descriptor_list: &NSArray<MPSImageDescriptor>, )

Available on crate feature MPSCore only.

Help MPS decide which allocations to make ahead of time

The texture cache that underlies the MPSTemporaryImage can automatically allocate new storage as needed as you create new temporary images. However, sometimes a more global view of what you plan to make is useful for maximizing memory reuse to get the most efficient operation. This class method hints to the cache what the list of images will be.

It is never necessary to call this method. It is purely a performance and memory optimization.

This method makes a conservative estimate of memory required and may not fully cover temporary memory needs, resulting in additional allocations later that could encounter pathological behavior, if they are too small. If the full extent and timing of the workload is known in advance, it is recommended that MPSHintTemporaryMemoryHighWaterMark() be used instead.

Parameter commandBuffer: The command buffer on which the MPSTemporaryImages will be used

Parameter descriptorList: A NSArray of MPSImageDescriptors, indicating images that will be created

Source

pub unsafe fn initWithTexture_featureChannels( this: Allocated<Self>, texture: &ProtocolObject<dyn MTLTexture>, feature_channels: NSUInteger, ) -> Retained<Self>

Available on crate feature MPSCore only.

Unavailable. Use temporaryImageForCommandBuffer:textureDescriptor: or -temporaryImageForCommandBuffer:imageDescriptor: instead.

§Safety
  • texture may need to be synchronized.
  • texture may be unretained, you must ensure it is kept alive while in use.
Source

pub unsafe fn initWithDevice_imageDescriptor( this: Allocated<Self>, device: &ProtocolObject<dyn MTLDevice>, image_descriptor: &MPSImageDescriptor, ) -> Retained<Self>

Available on crate feature MPSCore only.

Unavailable. Use itemporaryImageForCommandBuffer:textureDescriptor: instead.

Source

pub unsafe fn readCount(&self) -> NSUInteger

Available on crate feature MPSCore only.
Source

pub unsafe fn setReadCount(&self, read_count: NSUInteger)

Available on crate feature MPSCore only.

Setter for readCount.

Source§

impl MPSTemporaryImage

Methods declared on superclass MPSImage.

Source

pub unsafe fn initWithParentImage_sliceRange_featureChannels( this: Allocated<Self>, parent: &MPSImage, slice_range: NSRange, feature_channels: NSUInteger, ) -> Retained<Self>

Available on crate feature MPSCore only.

Use -batchRepresentation or -subImageWithFeatureChannelRange instead

Generally, you should call -batchRepresentation or -subImageWithFeatureChannelRange instead because they are safer. This is provided so that these interfaces will work with your MPSImage subclass.

Parameter parent: The parent image that owns the texture. It may be a sub-image.

Parameter sliceRange: The range of MTLTexture2dArray slices to be included in the sub-image

Parameter featureChannels: The number of feature channels in the new image. The number of images is inferred.

Returns: A MPSImage that references a subregion of the texel storage in parent instead of using its own storage.

Source

pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>

Available on crate feature MPSCore only.
Source§

impl MPSTemporaryImage

Methods declared on superclass NSObject.

Source

pub unsafe fn new() -> Retained<Self>

Available on crate feature MPSCore only.

Methods from Deref<Target = MPSImage>§

Source

pub unsafe fn device(&self) -> Retained<ProtocolObject<dyn MTLDevice>>

Available on crate feature MPSCore only.

The device on which the MPSImage will be used

Source

pub unsafe fn width(&self) -> NSUInteger

Available on crate feature MPSCore only.

The formal width of the image in pixels.

Source

pub unsafe fn height(&self) -> NSUInteger

Available on crate feature MPSCore only.

The formal height of the image in pixels.

Source

pub unsafe fn featureChannels(&self) -> NSUInteger

Available on crate feature MPSCore only.

The number of feature channels per pixel.

Source

pub unsafe fn numberOfImages(&self) -> NSUInteger

Available on crate feature MPSCore only.

numberOfImages for batch processing

Source

pub unsafe fn textureType(&self) -> MTLTextureType

Available on crate feature MPSCore only.

The type of the underlying texture, typically MTLTextureType2D or MTLTextureType2DArray

Source

pub unsafe fn pixelFormat(&self) -> MTLPixelFormat

Available on crate feature MPSCore only.

The MTLPixelFormat of the underlying texture

Note that in some cases, this value may be misleading. For example, float16 data (BFloat16) is sometimes stored in MTLPixelFormatRGBA16Unorm Please consult the featureChannelFormat.

Source

pub unsafe fn precision(&self) -> NSUInteger

Available on crate feature MPSCore only.

The number of bits of numeric precision available for each feature channel.

This is precision, not size. That is, float is 24 bits, not 32. half precision floating-point is 11 bits, not 16. SNorm formats have one less bit of precision for the sign bit, etc. For formats like MTLPixelFormatB5G6R5Unorm it is the precision of the most precise channel, in this case 6. When this information is unavailable, typically compressed formats, 0 will be returned.

Source

pub unsafe fn usage(&self) -> MTLTextureUsage

Available on crate feature MPSCore only.

Description of texture usage.

Source

pub unsafe fn featureChannelFormat(&self) -> MPSImageFeatureChannelFormat

Available on crate features MPSCore and MPSCoreTypes only.

The true encoding of the feature channels

Source

pub unsafe fn pixelSize(&self) -> usize

Available on crate feature MPSCore only.

Number of bytes from the first byte of one pixel to the first byte of the next pixel in storage order. (Includes padding.)

Source

pub unsafe fn texture(&self) -> Retained<ProtocolObject<dyn MTLTexture>>

Available on crate feature MPSCore only.

The associated MTLTexture object. This is a 2D texture if numberOfImages is 1 and number of feature channels < = 4. It is a 2D texture array otherwise.

To avoid the high cost of premature allocation of the underlying texture, avoid calling this property except when strictly necessary. [MPSCNNKernel encode…] calls typically cause their arguments to become allocated. Likewise, MPSImages initialized with -initWithTexture: featureChannels: have already been allocated.

Source

pub unsafe fn label(&self) -> Option<Retained<NSString>>

Available on crate feature MPSCore only.

A string to help identify this object.

Source

pub unsafe fn setLabel(&self, label: Option<&NSString>)

Available on crate feature MPSCore only.

Setter for label.

This is copied when set.

Source

pub unsafe fn parent(&self) -> Option<Retained<MPSImage>>

Available on crate feature MPSCore only.

The MPSImage from which this MPSImage was derived. Otherwise nil.

This will point to the original image if this image was created using -batchRepresentation, -batchRepresentationWithRange: or -subImageWithFeatureChannelRange:.

Source

pub unsafe fn batchRepresentationWithSubRange( &self, sub_range: NSRange, ) -> Retained<MPSImageBatch>

Available on crate feature MPSCore only.

Make a representation of a MPSImage (batch) as a MPSImageBatch

Before the MPSImageBatch was introduced, several images could be concatenated into a MPSImage as multiple image slices in a MTLTexture2DArray to make a image batch. If the image contained more than 4 feature channels, then each image would have round_up( feature channels / 4) slices and the total number of slices in the MPSImage would be slices * number of images.

Because many devices can operate on texture arrays of no more than 2048 slices, storage in this format is limited. For example in InceptionV3, 2048 feature channels at its widest point, the largest batch size that can be processed in this way is 4, well under commonly accepted practice for training. Consequently, the older batching style is deprecated and the MPSImageBatch is introduced. It is also easier to manage sub-batches and to concatenate sub-batches for memory management with the MPSImageBatch, so this format is favored going forward.

To facilitate forward migration, this method will prepare an array of MPSImages that each point to the appropriate set of slices in storage for the original image. Since they share storage, writes to the parent will alter the content of the children, and vice versa.

If the original is a temporary image, the result will be a temporary image. It will hold 1 readCount on the original. When the readCount drops to 0, it will decrement the appropriate counter on the parent.

This is a much cheaper form of the slice operator, and should be used instead when the slice operator does not need to operate out of place.

Parameter subRange: The range of images in the original image from which the batch will be derived.

Returns: A MPSImageBatch referencing a subregion of the original batch image.

Source

pub unsafe fn batchRepresentation(&self) -> Retained<MPSImageBatch>

Available on crate feature MPSCore only.

Make a MPSImageBatch that points to the individual images in the MPSImage

If the original is a temporary image, the result will be a temporary image. It will hold 1 readCount on the original. When the readCount drops to 0, it will decrement the appropriate counter on the parent.

Returns: A MPSImageBatch aliasing the texel storage in the original batch image

Source

pub unsafe fn subImageWithFeatureChannelRange( &self, range: NSRange, ) -> Retained<MPSImage>

Available on crate feature MPSCore only.
Source

pub unsafe fn resourceSize(&self) -> NSUInteger

Available on crate feature MPSCore only.

Get the number of bytes used to allocate underyling MTLResources

This is the size of the backing store of underlying MTLResources. It does not include all storage used by the object, for example the storage used to hold the MPSImage instantiation and MTLTexture is not included. It only measures the size of the allocation used to hold the texels in the image. This value is subject to change between different devices and operating systems.

Except when -initWithTexture:featureChannels: is used, most MPSImages (including MPSTemporaryImages) are allocated without a backing store. The backing store is allocated lazily when it is needed, typically when the .texture property is called. Consequently, in most cases, it should be inexpensive to make a MPSImage to see how much memory it will need, and release it if it is too large.

This method may fail in certain circumstances, such as when the MPSImage is created with -initWithTexture:featureChannels:, in which case 0 will be returned. 0 will also be returned if it is a sub-image or sub-batch (.parent is not nil).

Source

pub unsafe fn setPurgeableState( &self, state: MPSPurgeableState, ) -> MPSPurgeableState

Available on crate feature MPSCore only.

Set (or query) the purgeability state of a MPSImage

Usage is per [MTLResource setPurgeableState:], except that the MTLTexture might be MPSPurgeableStateAllocationDeferred, which means there is no texture to mark volatile / nonvolatile. Attempts to set purgeability on MTLTextures that have not been allocated will be ignored.

Source

pub unsafe fn readBytes_dataLayout_bytesPerRow_region_featureChannelInfo_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, bytes_per_row: NSUInteger, region: MTLRegion, feature_channel_info: MPSImageReadWriteParams, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Get the values inside MPSImage and put them in the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter bytesPerRow: Bytes to stride to point to next row(pixel just below current one) in the user buffer.

Parameter featureChannelInfo: information user fills in to write to a set of feature channels in the image

Parameter imageIndex: Image index in MPSImage to write to.

Parameter region: region of the MPSImage to read from. A region is a structure with the origin in the Image from which to start reading values and a size which represents the width and height of the rectangular region to read from. The z direction denotes the number of images, thus for 1 image, origin.z = 0 and size.depth = 1

Use the enum to set data is coming in with what order. The data type will be determined by the pixelFormat defined in the Image Descriptor.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn writeBytes_dataLayout_bytesPerRow_region_featureChannelInfo_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, bytes_per_row: NSUInteger, region: MTLRegion, feature_channel_info: MPSImageReadWriteParams, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Set the values inside MPSImage with the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter bytesPerRow: Bytes to stride to point to next row(pixel just below current one) in the user buffer.

Parameter region: region of the MPSImage to write to. A region is a structure with the origin in the Image from which to start writing values and a size which represents the width and height of the rectangular region to write in. The z direction denotes the number of images, thus for 1 image, origin.z = 0 and size.depth = 1

Parameter featureChannelInfo: information user fills in to read from a set of feature channels in the image

Parameter imageIndex: Image index in MPSImage to write to.

This method is used to copy data from the storage provided by dataBytes to the MPSImage. The ordering of data in your dataBytes buffer is given by dataLayout. Each image may be stored as either a series of planar images (a series of single WxH images, one per feature channel) or a single chunky image, WxHxfeature_channels. BytesPerRow and BytesPerImage are there to allow some padding between successive rows and successive images. No padding is allowed between successive feature channels.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn writeBytes_dataLayout_bytesPerColumn_bytesPerRow_bytesPerImage_region_featureChannelInfo_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, bytes_per_column: NSUInteger, bytes_per_row: NSUInteger, bytes_per_image: NSUInteger, region: MTLRegion, feature_channel_info: MPSImageReadWriteParams, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Set the values inside MPSImage with the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter bytesPerColumn: This is the stride in bytes from W[0] to W[1], for both HWC and CHW orderings in the buffer pointed to by dataBytes.

Parameter bytesPerRow: Bytes to stride to point to next row(pixel just below current one, i.e. H[0] to H[1]) in the buffer pointed to by dataBytes.

Parameter bytesPerImage: This is the stride in bytes from image[0] to image[1] im the buffer pointed to by dataBytes.

Parameter region: region of the MPSImage to write to. A region is a structure with the origin in the Image from which to start writing values and a size which represents the width and height of the rectangular region to write in. The z direction denotes the number of images, thus for 1 image, origin.z = 0 and size.depth = 1

Parameter featureChannelInfo: information user fills in to read from a set of feature channels in the image

Parameter imageIndex: Image index in MPSImage to write to.

This method is used to copy data from the storage provided by dataBytes to the MPSImage. The ordering of data in your dataBytes buffer is given by dataLayout. Each image may be stored as either a series of planar images (a series of single WxH images, one per feature channel) or a single chunky image, WxHxfeature_channels. BytesPerRow and BytesPerImage are there to allow some padding between successive rows and successive images. No padding is allowed between successive feature channels.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn readBytes_dataLayout_bytesPerRow_bytesPerImage_region_featureChannelInfo_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, bytes_per_row: NSUInteger, bytes_per_image: NSUInteger, region: MTLRegion, feature_channel_info: MPSImageReadWriteParams, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Get the values inside MPSImage and put them in the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter bytesPerRow: Bytes to stride to point to next row(pixel just below current one) in the user buffer.

Parameter bytesPerImage: Bytes to stride to point to next dataBytes image. See region.size.depth for image count.

Parameter featureChannelInfo: information user fills in to write to a set of feature channels in the image

Parameter imageIndex: Image index in MPSImage to write to.

Parameter region: region of the MPSImage to read from. A region is a structure with the origin in the Image from which to start reading values and a size which represents the width and height of the rectangular region to read from. The z direction denotes the number of images, thus for 1 image, origin.z = 0 and size.depth = 1

This method is used to copy data from the MPSImage to the storage provided by dataBytes. The ordering of data in your dataBytes buffer is given by dataLayout. Each image may be stored as either a series of planar images (a series of single WxH images, one per feature channel) or a single chunky image, WxHxfeature_channels. BytesPerRow and BytesPerImage are there to allow some padding between successive rows and successive images. No padding is allowed between successive feature channels.

BUG: Prior to MacOS 10.15, iOS/tvOS 13.0, incorrect behavior may be observed if region.size.depth != 1 or if bytesPerRow allowed for unused padding between rows. BUG: To provide for full capability to extract and insert content from arbitrarily sized buffers, there should also be a featureChannelStride in addition to bytesPerRow and bytesPerImage. With the current design, when we finish the last feature channel, the next byte will contain the 0th feature channel for the next texel or slice, depending on packing order. This method can not be used to modify some but not all of the feature channels in an image.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn writeBytes_dataLayout_bytesPerRow_bytesPerImage_region_featureChannelInfo_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, bytes_per_row: NSUInteger, bytes_per_image: NSUInteger, region: MTLRegion, feature_channel_info: MPSImageReadWriteParams, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Set the values inside MPSImage with the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter bytesPerRow: Bytes to stride to point to next row(pixel just below current one) in the user buffer.

Parameter bytesPerImage: Bytes to stride to point to next dataBytes image. See region.size.depth for image count.

Parameter region: region of the MPSImage to write to. A region is a structure with the origin in the Image from which to start writing values and a size which represents the width and height of the rectangular region to write in. The z direction denotes the number of images, thus for 1 image, origin.z = 0 and size.depth = 1

Parameter featureChannelInfo: information user fills in to read from a set of feature channels in the image

Parameter imageIndex: Image index in MPSImage to write to.

Use the enum to set data is coming in with what order. The data type will be determined by the pixelFormat defined in the Image Descriptor.

BUG: Prior to MacOS 10.15, iOS/tvOS 13.0, incorrect behavior may be observed if region.size.depth != 1 or if bytesPerRow allowed for unused padding between rows. BUG: To provide for full capability to extract and insert content from arbitrarily sized buffers, there should also be a featureChannelStride in addition to bytesPerRow and bytesPerImage. With the current design, when we finish the last feature channel, the next byte will contain the 0th feature channel for the next texel or slice, depending on packing order. This method can not be used to modify some but not all of the feature channels in an image.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn readBytes_dataLayout_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Get the values inside MPSImage and put them in the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter imageIndex: Image index in MPSImage to read from.

Use the enum to set data is coming in with what order. The data type will be determined by the pixelFormat defined in the Image Descriptor. Region is full image, buffer width and height is same as MPSImage width and height.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn writeBytes_dataLayout_imageIndex( &self, data_bytes: NonNull<c_void>, data_layout: MPSDataLayout, image_index: NSUInteger, )

Available on crate feature MPSCore only.

Set the values inside MPSImage with the Buffer passed in.

Parameter dataBytes: The array allocated by the user to be used to put data from MPSImage, the length should be imageWidth * imageHeight * numberOfFeatureChannels and dataType should be inferred from pixelFormat defined in the Image Descriptor.

Parameter dataLayout: The enum tells how to layout MPS data in the buffer.

Parameter imageIndex: Image index in MPSImage to write to.

Use the enum to set data is coming in with what order. The data type will be determined by the pixelFormat defined in the Image Descriptor. Region is full image, buffer width and height is same as MPSImage width and height.

§Safety

data_bytes must be a valid pointer.

Source

pub unsafe fn synchronizeOnCommandBuffer( &self, command_buffer: &ProtocolObject<dyn MTLCommandBuffer>, )

Available on crate feature MPSCore only.

Flush the underlying MTLTexture from the device’s caches, and invalidate any CPU caches if needed.

This will call [id <MTLBlitEncoder

synchronizeResource: ] on the image’s MTLTexture, if any. This is necessary for all MTLStorageModeManaged resources. For other resources, including temporary resources (these are all MTLStorageModePrivate), and textures that have not yet been allocated, nothing is done. It is more efficient to use this method than to attempt to do this yourself with the texture property.

Parameter commandBuffer: The commandbuffer on which to synchronize

Methods from Deref<Target = NSObject>§

Source

pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !

Handle messages the object doesn’t recognize.

See Apple’s documentation for details.

Methods from Deref<Target = AnyObject>§

Source

pub fn class(&self) -> &'static AnyClass

Dynamically find the class of this object.

§Panics

May panic if the object is invalid (which may be the case for objects returned from unavailable init/new methods).

§Example

Check that an instance of NSObject has the precise class NSObject.

use objc2::ClassType;
use objc2::runtime::NSObject;

let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());
Source

pub unsafe fn get_ivar<T>(&self, name: &str) -> &T
where T: Encode,

👎Deprecated: this is difficult to use correctly, use Ivar::load instead.

Use Ivar::load instead.

§Safety

The object must have an instance variable with the given name, and it must be of type T.

See Ivar::load_ptr for details surrounding this.

Source

pub fn downcast_ref<T>(&self) -> Option<&T>
where T: DowncastTarget,

Attempt to downcast the object to a class of type T.

This is the reference-variant. Use Retained::downcast if you want to convert a retained object to another type.

§Mutable classes

Some classes have immutable and mutable variants, such as NSString and NSMutableString.

When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable “under the hood”.

So using this method to convert a NSString to a NSMutableString, while not unsound, is generally frowned upon unless you created the string yourself, or the API explicitly documents the string to be mutable.

See Apple’s documentation on mutability and on isKindOfClass: for more details.

§Generic classes

Objective-C generics are called “lightweight generics”, and that’s because they aren’t exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.

You can, however, safely downcast to generic collections where all the type-parameters are AnyObject.

§Panics

This works internally by calling isKindOfClass:. That means that the object must have the instance method of that name, and an exception will be thrown (if CoreFoundation is linked) or the process will abort if that is not the case. In the vast majority of cases, you don’t need to worry about this, since both root objects NSObject and NSProxy implement this method.

§Examples

Cast an NSString back and forth from NSObject.

use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};

let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();

Try (and fail) to cast an NSObject to an NSString.

use objc2_foundation::{NSObject, NSString};

let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());

Try to cast to an array of strings.

use objc2_foundation::{NSArray, NSObject, NSString};

let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();

This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.

Downcast when processing each element instead.

use objc2_foundation::{NSArray, NSObject, NSString};

let arr = NSArray::from_retained_slice(&[NSObject::new()]);

for elem in arr {
    if let Some(data) = elem.downcast_ref::<NSString>() {
        // handle `data`
    }
}

Trait Implementations§

Source§

impl AsRef<AnyObject> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn as_ref(&self) -> &AnyObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<MPSImage> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn as_ref(&self) -> &MPSImage

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<MPSTemporaryImage> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSObject> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn as_ref(&self) -> &NSObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<AnyObject> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<MPSImage> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn borrow(&self) -> &MPSImage

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

const NAME: &'static str = "MPSTemporaryImage"

The name of the Objective-C class that this type represents. Read more
Source§

type Super = MPSImage

The superclass of this class. Read more
Source§

type ThreadKind = <<MPSTemporaryImage as ClassType>::Super as ClassType>::ThreadKind

Whether the type can be used from any thread, or from only the main thread. Read more
Source§

fn class() -> &'static AnyClass

Get a reference to the Objective-C class that this type represents. Read more
Source§

fn as_super(&self) -> &Self::Super

Get an immutable reference to the superclass.
Source§

impl Debug for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

type Target = MPSImage

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Hash for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Message for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn retain(&self) -> Retained<Self>
where Self: Sized,

Increment the reference count of the receiver. Read more
Source§

impl NSObjectProtocol for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn isEqual(&self, other: Option<&AnyObject>) -> bool
where Self: Sized + Message,

Check whether the object is equal to an arbitrary other object. Read more
Source§

fn hash(&self) -> usize
where Self: Sized + Message,

An integer that can be used as a table address in a hash table structure. Read more
Source§

fn isKindOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of the class, or one of its subclasses. Read more
Source§

fn is_kind_of<T>(&self) -> bool
where T: ClassType, Self: Sized + Message,

👎Deprecated: use isKindOfClass directly, or cast your objects with AnyObject::downcast_ref
Check if the object is an instance of the class type, or one of its subclasses. Read more
Source§

fn isMemberOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of a specific class, without checking subclasses. Read more
Source§

fn respondsToSelector(&self, aSelector: Sel) -> bool
where Self: Sized + Message,

Check whether the object implements or inherits a method with the given selector. Read more
Source§

fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
where Self: Sized + Message,

Check whether the object conforms to a given protocol. Read more
Source§

fn description(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object. Read more
Source§

fn debugDescription(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object to use when debugging. Read more
Source§

fn isProxy(&self) -> bool
where Self: Sized + Message,

Check whether the receiver is a subclass of the NSProxy root class instead of the usual NSObject. Read more
Source§

fn retainCount(&self) -> usize
where Self: Sized + Message,

The reference count of the object. Read more
Source§

impl PartialEq for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RefEncode for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

const ENCODING_REF: Encoding = <MPSImage as ::objc2::RefEncode>::ENCODING_REF

The Objective-C type-encoding for a reference of this type. Read more
Source§

impl DowncastTarget for MPSTemporaryImage

Available on crate feature MPSCore only.
Source§

impl Eq for MPSTemporaryImage

Available on crate feature MPSCore only.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T> AnyThread for T
where T: ClassType<ThreadKind = dyn AnyThread + 'a> + ?Sized,

Source§

fn alloc() -> Allocated<Self>
where Self: Sized + ClassType,

Allocate a new instance of the class. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,