1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
//! This file has been automatically generated by `objc2`'s `header-translator`.
//! DO NOT EDIT
use core::ffi::*;
use core::ptr::NonNull;
use objc2::__framework_prelude::*;
use objc2_foundation::*;
use objc2_metal::*;
use crate::*;
extern_class!(
/// Dependencies: This depends on Metal.framework
///
/// A MPSImageDescriptor object describes a attributes of MPSImage and is used to
/// create one (see MPSImage discussion below)
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsimagedescriptor?language=objc)
#[unsafe(super(NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MPSImageDescriptor;
);
extern_conformance!(
unsafe impl NSCopying for MPSImageDescriptor {}
);
unsafe impl CopyingHelper for MPSImageDescriptor {
type Result = Self;
}
extern_conformance!(
unsafe impl NSObjectProtocol for MPSImageDescriptor {}
);
impl MPSImageDescriptor {
extern_methods!(
/// The width of the CNN image.
///
/// The formal width of the CNN image in pixels. Default = 1.
#[unsafe(method(width))]
#[unsafe(method_family = none)]
pub unsafe fn width(&self) -> NSUInteger;
/// Setter for [`width`][Self::width].
#[unsafe(method(setWidth:))]
#[unsafe(method_family = none)]
pub unsafe fn setWidth(&self, width: NSUInteger);
/// The height of the CNN image.
///
/// The formal height of the CNN image in pixels. Default = 1.
#[unsafe(method(height))]
#[unsafe(method_family = none)]
pub unsafe fn height(&self) -> NSUInteger;
/// Setter for [`height`][Self::height].
#[unsafe(method(setHeight:))]
#[unsafe(method_family = none)]
pub unsafe fn setHeight(&self, height: NSUInteger);
/// The number of feature channels per pixel. Default = 1.
#[unsafe(method(featureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn featureChannels(&self) -> NSUInteger;
/// Setter for [`featureChannels`][Self::featureChannels].
#[unsafe(method(setFeatureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn setFeatureChannels(&self, feature_channels: NSUInteger);
/// The number of images for batch processing. Default = 1.
#[unsafe(method(numberOfImages))]
#[unsafe(method_family = none)]
pub unsafe fn numberOfImages(&self) -> NSUInteger;
/// Setter for [`numberOfImages`][Self::numberOfImages].
#[unsafe(method(setNumberOfImages:))]
#[unsafe(method_family = none)]
pub unsafe fn setNumberOfImages(&self, number_of_images: NSUInteger);
/// The MTLPixelFormat expected for the underlying texture.
#[unsafe(method(pixelFormat))]
#[unsafe(method_family = none)]
pub unsafe fn pixelFormat(&self) -> MTLPixelFormat;
#[cfg(feature = "MPSCoreTypes")]
/// The storage format to use for each channel in the image.
#[unsafe(method(channelFormat))]
#[unsafe(method_family = none)]
pub unsafe fn channelFormat(&self) -> MPSImageFeatureChannelFormat;
#[cfg(feature = "MPSCoreTypes")]
/// Setter for [`channelFormat`][Self::channelFormat].
#[unsafe(method(setChannelFormat:))]
#[unsafe(method_family = none)]
pub unsafe fn setChannelFormat(&self, channel_format: MPSImageFeatureChannelFormat);
/// Options to specify CPU cache mode of texture resource. Default = MTLCPUCacheModeDefaultCache
#[unsafe(method(cpuCacheMode))]
#[unsafe(method_family = none)]
pub unsafe fn cpuCacheMode(&self) -> MTLCPUCacheMode;
/// Setter for [`cpuCacheMode`][Self::cpuCacheMode].
#[unsafe(method(setCpuCacheMode:))]
#[unsafe(method_family = none)]
pub unsafe fn setCpuCacheMode(&self, cpu_cache_mode: MTLCPUCacheMode);
/// To specify storage mode of texture resource.
///
/// Storage mode options:
///
/// ```text
/// Default = MTLStorageModeShared on iOS
/// MTLStorageModeManaged on Mac OSX
/// MTLStorageModeShared not supported on Mac OSX.
/// See Metal headers for synchronization requirements when using StorageModeManaged
/// ```
#[unsafe(method(storageMode))]
#[unsafe(method_family = none)]
pub unsafe fn storageMode(&self) -> MTLStorageMode;
/// Setter for [`storageMode`][Self::storageMode].
#[unsafe(method(setStorageMode:))]
#[unsafe(method_family = none)]
pub unsafe fn setStorageMode(&self, storage_mode: MTLStorageMode);
/// Description of texture usage. Default = MTLTextureUsageShaderRead/Write
#[unsafe(method(usage))]
#[unsafe(method_family = none)]
pub unsafe fn usage(&self) -> MTLTextureUsage;
/// Setter for [`usage`][Self::usage].
#[unsafe(method(setUsage:))]
#[unsafe(method_family = none)]
pub unsafe fn setUsage(&self, usage: MTLTextureUsage);
#[cfg(feature = "MPSCoreTypes")]
/// Create a MPSImageDescriptor for a single read/write cnn image.
#[unsafe(method(imageDescriptorWithChannelFormat:width:height:featureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn imageDescriptorWithChannelFormat_width_height_featureChannels(
channel_format: MPSImageFeatureChannelFormat,
width: NSUInteger,
height: NSUInteger,
feature_channels: NSUInteger,
) -> Retained<Self>;
#[cfg(feature = "MPSCoreTypes")]
/// Create a MPSImageDescriptor for a read/write cnn image with option to set usage and batch size (numberOfImages).
#[unsafe(method(imageDescriptorWithChannelFormat:width:height:featureChannels:numberOfImages:usage:))]
#[unsafe(method_family = none)]
pub unsafe fn imageDescriptorWithChannelFormat_width_height_featureChannels_numberOfImages_usage(
channel_format: MPSImageFeatureChannelFormat,
width: NSUInteger,
height: NSUInteger,
feature_channels: NSUInteger,
number_of_images: NSUInteger,
usage: MTLTextureUsage,
) -> Retained<Self>;
/// # Safety
///
/// `zone` must be a valid pointer or null.
#[unsafe(method(copyWithZone:))]
#[unsafe(method_family = copy)]
pub unsafe fn copyWithZone(&self, zone: *mut NSZone) -> Retained<Self>;
);
}
/// Methods declared on superclass `NSObject`.
impl MPSImageDescriptor {
extern_methods!(
#[unsafe(method(init))]
#[unsafe(method_family = init)]
pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;
#[unsafe(method(new))]
#[unsafe(method_family = new)]
pub unsafe fn new() -> Retained<Self>;
);
}
impl MPSImage {
/// raise or lower the readcount of a batch by a set amount
///
/// In some circumstances, a MPSImage may appear in a MPSImageBatch
/// multiple times. This is particularly common when the MPSImage serves
/// as an accumulator across the entire batch, such as when accumulating
/// gradients for convolution weight update or batch statistics for
/// batch normalization. A naive function would then end up incrementing
/// the state multiple times, probably leading to an error.
///
/// MPSImageBatchIncrementReadCount() will efficiently increment the readCounts of
/// each object in the batch only once, avoiding this problem. Non-temporary
/// images and images with readCount already 0 will be ignored.
///
/// CAUTION: At many places in MPS, the framework assumes all images
/// in the batch have the same characteristics, such as MPSImageFeatureChannelFormat.
/// At times, for example, it is necessary to patch in a special version of the
/// kernel to handle BFloat16 or another characteristic. When this happens, the
/// kernel generally can't respond correctly when some images in a batch have that
/// characteristic and some do not, because the special case handling code is hard
/// compiled in. For this reason, all images in a batch should be constructed from
/// the same list of descriptor parameters.
///
///
/// Parameter `batch`: The MPSImageBatch to increment
///
/// Parameter `amount`: The value to add to the read count for each unique image in the batch
///
/// Returns: The number of different images in the batch
#[doc(alias = "MPSImageBatchIncrementReadCount")]
#[inline]
pub unsafe fn batch_increment_read_count(
batch: &MPSImageBatch,
amount: NSInteger,
) -> NSUInteger {
extern "C-unwind" {
fn MPSImageBatchIncrementReadCount(
batch: &MPSImageBatch,
amount: NSInteger,
) -> NSUInteger;
}
unsafe { MPSImageBatchIncrementReadCount(batch, amount) }
}
/// Call [MTLBlitEncoder synchronizeResource:] on unique resources
#[doc(alias = "MPSImageBatchSynchronize")]
#[inline]
pub unsafe fn batch_synchronize(
batch: &MPSImageBatch,
cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
) {
extern "C-unwind" {
fn MPSImageBatchSynchronize(
batch: &MPSImageBatch,
cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
);
}
unsafe { MPSImageBatchSynchronize(batch, cmd_buf) }
}
/// Call [MTLBlitEncoder resourceSize] on unique resources and return sum
#[doc(alias = "MPSImageBatchResourceSize")]
#[inline]
pub unsafe fn batch_resource_size(batch: &MPSImageBatch) -> NSUInteger {
extern "C-unwind" {
fn MPSImageBatchResourceSize(batch: &MPSImageBatch) -> NSUInteger;
}
unsafe { MPSImageBatchResourceSize(batch) }
}
/// Iterate over unique images in the batch
///
/// This function looks only at image address to determine uniqueness.
/// The same texture stored in different MPSImages would be considered not unique.
///
///
/// Parameter `batch`: The image batch
///
/// Parameter `iteratorBlock`: Callback block to execute once for each unique image.
/// Return a value greater than NSIntegerMin to terminate early.
/// The index gives the first position in the batch where the image appears.
/// Behavior is undefined if MPSImageBatchIterate is called recursively on the same images.
///
/// Returns: The value returned by the iterator block for the last image on which it ran
#[doc(alias = "MPSImageBatchIterate")]
#[cfg(feature = "block2")]
#[inline]
pub unsafe fn batch_iterate(
batch: &MPSImageBatch,
iterator_block: &block2::DynBlock<dyn Fn(NonNull<MPSImage>, NSUInteger) -> NSInteger>,
) -> NSInteger {
extern "C-unwind" {
fn MPSImageBatchIterate(
batch: &MPSImageBatch,
iterator_block: &block2::DynBlock<
dyn Fn(NonNull<MPSImage>, NSUInteger) -> NSInteger,
>,
) -> NSInteger;
}
unsafe { MPSImageBatchIterate(batch, iterator_block) }
}
}
extern_protocol!(
/// A class that allocates new MPSImage or MPSTemporaryImage
///
/// Sometimes it is prohibitively costly for MPS to figure out how
/// big an image should be in advance. In addition, you may want to
/// have some say over whether the image is a temporary image or not.
/// In such circumstances, the MPSImageAllocator is used to
/// provide the developer with an opportunity for just in time feedback
/// about how the image should be allocated.
///
/// Two standard MPSImageAllocators are provided: MPSImageDefaultAllocator
/// and MPSTemporaryImageDefaultAllocator. You may of course provide
/// your own allocator instead.
///
/// Example:
///
/// ```text
/// // Note: MPSImageDefaultAllocator is already provided
/// // by the framework under that name. It is provided here
/// // as sample code for writing your own variant.
/// -(MPSImage * __nonnull) imageForCommandBuffer: (__nonnull id <MTLCommandBuffer>) cmdBuf
/// imageDescriptor: (MPSImageDescriptor * __nonnull) descriptor
/// kernel: (MPSKernel * __nonnull) kernel
/// {
/// MPSImage * result = [[MPSImage alloc] initWithDevice: cmdBuf.device
/// imageDescriptor: descriptor ];
///
/// // make sure the object sticks around at least as lomg as the command buffer
/// [result retain];
/// [cmdBuf addCompletedHandler: ^(id <MTLCommandBuffer> c){[result release];}];
///
/// // return autoreleased result
/// return [result autorelease];
/// };
///
/// -(BOOL) supportsSecureCoding{ return YES; }
/// -(void)encodeWithCoder:(NSCoder * __nonnull)aCoder
/// {
/// [super encodeWithCoder: aCoder];
///
/// // encode any data owned by the class at this level
/// }
///
/// -(nullable instancetype) initWithCoder: (NSCoder*__nonnull) aDecoder
/// {
/// self = [super initWithCoder: aDecoder ];
/// if( nil == self )
/// return self;
///
/// // use coder to load any extra data kept by this object here
///
/// return self;
/// }
/// ```
///
/// Please see [MPSImage defaultAllocator] and [MPSTemporaryImage defaultAllocator]
/// for implentations of the protocol already provided by MPS.
///
/// When considering whether to write your own MPSImageAllocator, you should know
/// the existing MPSImage and MPSTemporaryImage default allocators are optimized
/// to make image batch allocation much faster than one MPSImage at a time in a loop.
/// When possible, it can be better to use the MPS provided allocators and override
/// the behavior in a padding policy instead, if the changes can be contained in
/// the MPSImageDescriptor. This will help reduce CPU encode time. However, custom
/// padding policies can inhibit optimizations in the MPSNNGraph, particularly node
/// fusion, resulting in more work for the GPU. In cases where the custom padding method
/// does not change filter properties but only adjusts the result image (e.g. adjust result
/// feature channel format) then MPSNNPaddingMethodCustomAllowForNodeFusion may be
/// used to signal that node fusion is acceptable.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsimageallocator?language=objc)
pub unsafe trait MPSImageAllocator: NSObjectProtocol + NSSecureCoding {
#[cfg(feature = "MPSKernel")]
/// Create a new MPSImage
///
/// See class description for sample implementation
///
/// Parameter `cmdBuf`: The MTLCommandBuffer on which the image will be initialized.
/// cmdBuf.device encodes the MTLDevice.
///
/// Parameter `descriptor`: A MPSImageDescriptor containing the image format to use.
/// This format is the result of your MPSPadding policy.
///
/// Parameter `kernel`: The kernel that will overwrite the image returned by the filter.
/// Note that the MPS implementations of this protocol don't need
/// this field. It is provided for your convenience.
///
///
/// Returns: A valid MPSImage or MPSTemporaryImage. It will be automatically released when the command buffer completes.
#[unsafe(method(imageForCommandBuffer:imageDescriptor:kernel:))]
#[unsafe(method_family = none)]
unsafe fn imageForCommandBuffer_imageDescriptor_kernel(
&self,
cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
descriptor: &MPSImageDescriptor,
kernel: &MPSKernel,
) -> Retained<MPSImage>;
#[cfg(feature = "MPSKernel")]
/// Efficiently create an array of MPSImages with a common descriptor
///
/// See class description for sample implementation
///
/// Parameter `cmdBuf`: The MTLCommandBuffer on which the image will be initialized.
/// cmdBuf.device encodes the MTLDevice.
///
/// Parameter `descriptor`: A MPSImageDescriptor containing the image format to use.
/// This format is the result of your MPSPadding policy.
///
/// Parameter `kernel`: The kernel that will overwrite the image returned by the filter.
/// Note that the MPS implementations of this protocol don't need
/// this field. It is provided for your convenience.
///
/// Parameter `count`: The number of images in the batch
///
///
/// Returns: A valid MPSImage or MPSTemporaryImage. It will be automatically released when the command buffer completes.
#[optional]
#[unsafe(method(imageBatchForCommandBuffer:imageDescriptor:kernel:count:))]
#[unsafe(method_family = none)]
unsafe fn imageBatchForCommandBuffer_imageDescriptor_kernel_count(
&self,
cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
descriptor: &MPSImageDescriptor,
kernel: &MPSKernel,
count: NSUInteger,
) -> Retained<MPSImageBatch>;
}
);
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpspurgeablestate?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MPSPurgeableState(pub NSUInteger);
impl MPSPurgeableState {
#[doc(alias = "MPSPurgeableStateAllocationDeferred")]
pub const AllocationDeferred: Self = Self(0);
#[doc(alias = "MPSPurgeableStateKeepCurrent")]
pub const KeepCurrent: Self = Self(MTLPurgeableState::KeepCurrent.0);
#[doc(alias = "MPSPurgeableStateNonVolatile")]
pub const NonVolatile: Self = Self(MTLPurgeableState::NonVolatile.0);
#[doc(alias = "MPSPurgeableStateVolatile")]
pub const Volatile: Self = Self(MTLPurgeableState::Volatile.0);
#[doc(alias = "MPSPurgeableStateEmpty")]
pub const Empty: Self = Self(MTLPurgeableState::Empty.0);
}
unsafe impl Encode for MPSPurgeableState {
const ENCODING: Encoding = NSUInteger::ENCODING;
}
unsafe impl RefEncode for MPSPurgeableState {
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
/// [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsdatalayout?language=objc)
// NS_ENUM
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MPSDataLayout(pub NSUInteger);
impl MPSDataLayout {
#[doc(alias = "MPSDataLayoutHeightxWidthxFeatureChannels")]
pub const HeightxWidthxFeatureChannels: Self = Self(0);
#[doc(alias = "MPSDataLayoutFeatureChannelsxHeightxWidth")]
pub const FeatureChannelsxHeightxWidth: Self = Self(1);
}
unsafe impl Encode for MPSDataLayout {
const ENCODING: Encoding = NSUInteger::ENCODING;
}
unsafe impl RefEncode for MPSDataLayout {
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
/// these parameters are passed in to allow user to read/write to a particular set of featureChannels in an MPSImage
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsimagereadwriteparams?language=objc)
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MPSImageReadWriteParams {
/// featureChannel offset from which to read/write featureChannels, this should be a multiple of 4
pub featureChannelOffset: NSUInteger,
/// is number of featureChannels, should be greater than 0 and multiple of 4 unless featureChannelOffset is 0
pub numberOfFeatureChannelsToReadWrite: NSUInteger,
}
unsafe impl Encode for MPSImageReadWriteParams {
const ENCODING: Encoding =
Encoding::Struct("?", &[<NSUInteger>::ENCODING, <NSUInteger>::ENCODING]);
}
unsafe impl RefEncode for MPSImageReadWriteParams {
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
}
extern_class!(
/// Dependencies: This depends on Metal.framework
///
/// A MPSImage object describes a MTLTexture that may have more than 4 channels.
///
/// Some image types, such as those found in convolutional neural networks (CNN)
/// differ from a standard texture in that they may have more than 4 channels
/// per image. While the channels could hold RGBA data, they will more commonly
/// hold a number of structural permutations upon a multi-channel image as the neural
/// network progresses. It is not uncommon for each pixel to have 32 or 64 channels
/// in it.
///
/// A standard MTLTexture may have no more than 4 channels. The additional
/// channels are stored in slices of 2d texture array (i.e. texture type is MTLTextureType2DArray)
/// such that 4 consecutive channels are stored in each slice of this array.
/// If the number of feature channels is N, number of array slices needed is (N+3)/4.
/// E.g. a CNN image with width 3 and height 2 with 9 channels will be stored as
///
/// ```text
/// slice 0 RGBA RGBA RGBA
/// RGBA RGBA RGBA
///
/// slice 1 RGBA RGBA RGBA
/// RGBA RGBA RGBA (ASCII art /diagonal offset/ intended to show a Z dimension)
///
/// slice 2 R??? R??? R???
/// R??? R??? R???
/// ```
///
/// The width and height of underlying 2d texture array is the same as the width and height of the MPSImage.
/// The array length is equal to (featureChannels + 3) / 4. Channels marked with ? are just
/// for padding and should not contain NaNs or Infs.
///
/// A MPSImage can be container of multiple CNN images for batch processing. In order to create a
/// MPSImage that contains N images, create MPSImageDescriptor with numberOfImages set to N.
///
/// Although a MPSImage can contain numberOfImages > 1, the actual number of images among these processed by MPSCNNKernel
/// is controlled by z-dimension of the clipRect. A MPSCNNKernel processes n=clipRect.size.depth images from this collection.
/// The starting source image index to process is given by offset.z. The starting index of the destination image is given by
/// clipRect.origin.z. The MPSCNNKernel takes n=clipRect.size.depth images from tje source at indices [offset.z, offset.z+n],
/// processes each independently and stores the result in the destination at indices [clipRect.origin.z, clipRect.origin.z+n]
/// respectively. Offset.z+n should be
/// <
/// = [src numberOfImage] and clipRect.origin.z+n should be
/// <
/// = [dest numberOfImages] and
/// offset.z must be >= 0.
///
/// Example: Suppose MPSCNNConvolution takes an input image with 8 channels and outputs an image with 16 channels. The number of
/// slices needed in the source 2d texture array is 2 and the number of slices needed in the destination 2d array is 4. Suppose
/// the source batch size is 5 and destination batch size is 4. (Multiple N-channel images can be processed concurrently in a
/// batch.) The number of source slices will be 2*5=10 and number of destination slices will be 4*4=16. If you want to process
/// just images 2 and 3 of the source and store the result at index 1 and 2 in the destination, you may achieve this by setting
/// offset.z=2, clipRect.origin.z=1 and clipRect.size.depth=2. MPSCNNConvolution will take, in this case, slice 4 and 5 of source and
/// produce slices 4 to 7 of destination. Similarly, slices 6 and 7 will be used to produce slices 8 to 11 of destination.
///
/// All MPSCNNKernels process images within each batch independently. That is, calling a MPSCNNKernel on an
/// batch is formally the same as calling it on each image in the batch one at a time. However, quite a lot of CPU and GPU overhead
/// will be avoided if batch processing is used. This is especially important for better performance on small images.
///
/// If the number of feature channels is
/// <
/// = 4 and numberOfImages = 1 i.e. only one slice is needed to represent a MPSImage, the underlying
/// metal texture type will be MTLTextureType2D rather than MTLTextureType2DArray.
///
/// There are also MPSTemporaryImages, intended for use for very short-lived image data that are produced and consumed
/// immediately in the same MTLCommandBuffer. They are a useful way to minimize CPU-side texture allocation costs and
/// greatly reduce the amount of memory used by your image pipeline.
///
/// Creation of the underlying texture may in some cases occur lazily. You should
/// in general avoid calling MPSImage.texture except when unavoidable to avoid
/// materializing memory for longer than necessary. When possible, use the other MPSImage
/// properties to get information about the MPSImage instead.
///
/// Most MPSImages of 4 or fewer feature channels can generate quicklooks output in
/// Xcode for easy visualization of image data in the object. MPSTemporaryImages can not.
///
/// See also [Apple's documentation](https://developer.apple.com/documentation/metalperformanceshaders/mpsimage?language=objc)
#[unsafe(super(NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MPSImage;
);
extern_conformance!(
unsafe impl NSObjectProtocol for MPSImage {}
);
impl MPSImage {
extern_methods!(
/// Get a well known MPSImageAllocator that makes MPSImages
#[unsafe(method(defaultAllocator))]
#[unsafe(method_family = none)]
pub unsafe fn defaultAllocator() -> Retained<ProtocolObject<dyn MPSImageAllocator>>;
/// The device on which the MPSImage will be used
#[unsafe(method(device))]
#[unsafe(method_family = none)]
pub unsafe fn device(&self) -> Retained<ProtocolObject<dyn MTLDevice>>;
/// The formal width of the image in pixels.
#[unsafe(method(width))]
#[unsafe(method_family = none)]
pub unsafe fn width(&self) -> NSUInteger;
/// The formal height of the image in pixels.
#[unsafe(method(height))]
#[unsafe(method_family = none)]
pub unsafe fn height(&self) -> NSUInteger;
/// The number of feature channels per pixel.
#[unsafe(method(featureChannels))]
#[unsafe(method_family = none)]
pub unsafe fn featureChannels(&self) -> NSUInteger;
/// numberOfImages for batch processing
#[unsafe(method(numberOfImages))]
#[unsafe(method_family = none)]
pub unsafe fn numberOfImages(&self) -> NSUInteger;
/// The type of the underlying texture, typically MTLTextureType2D
/// or MTLTextureType2DArray
#[unsafe(method(textureType))]
#[unsafe(method_family = none)]
pub unsafe fn textureType(&self) -> MTLTextureType;
/// 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.
#[unsafe(method(pixelFormat))]
#[unsafe(method_family = none)]
pub unsafe fn pixelFormat(&self) -> MTLPixelFormat;
/// 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.
#[unsafe(method(precision))]
#[unsafe(method_family = none)]
pub unsafe fn precision(&self) -> NSUInteger;
/// Description of texture usage.
#[unsafe(method(usage))]
#[unsafe(method_family = none)]
pub unsafe fn usage(&self) -> MTLTextureUsage;
#[cfg(feature = "MPSCoreTypes")]
/// The true encoding of the feature channels
#[unsafe(method(featureChannelFormat))]
#[unsafe(method_family = none)]
pub unsafe fn featureChannelFormat(&self) -> MPSImageFeatureChannelFormat;
/// Number of bytes from the first byte of one pixel to the first byte of the next
/// pixel in storage order. (Includes padding.)
#[unsafe(method(pixelSize))]
#[unsafe(method_family = none)]
pub unsafe fn pixelSize(&self) -> usize;
/// 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.
#[unsafe(method(texture))]
#[unsafe(method_family = none)]
pub unsafe fn texture(&self) -> Retained<ProtocolObject<dyn MTLTexture>>;
/// A string to help identify this object.
#[unsafe(method(label))]
#[unsafe(method_family = none)]
pub unsafe fn label(&self) -> Option<Retained<NSString>>;
/// Setter for [`label`][Self::label].
///
/// This is [copied][objc2_foundation::NSCopying::copy] when set.
#[unsafe(method(setLabel:))]
#[unsafe(method_family = none)]
pub unsafe fn setLabel(&self, label: Option<&NSString>);
/// 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:.
#[unsafe(method(parent))]
#[unsafe(method_family = none)]
pub unsafe fn parent(&self) -> Option<Retained<MPSImage>>;
/// Initialize an empty image object
///
/// Parameter `device`: The device that the image will be used. May not be NULL.
///
/// Parameter `imageDescriptor`: The MPSImageDescriptor. May not be NULL.
///
/// Returns: A valid MPSImage object or nil, if failure.
///
/// Storage to store data needed is allocated lazily on first use of MPSImage or
/// when application calls MPSImage.texture
#[unsafe(method(initWithDevice:imageDescriptor:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_imageDescriptor(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
image_descriptor: &MPSImageDescriptor,
) -> Retained<Self>;
/// 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.
#[unsafe(method(initWithParentImage:sliceRange:featureChannels:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithParentImage_sliceRange_featureChannels(
this: Allocated<Self>,
parent: &MPSImage,
slice_range: NSRange,
feature_channels: NSUInteger,
) -> Retained<Self>;
/// Initialize an MPSImage object using Metal texture. Metal texture has been created by
/// user for specific number of feature channels and number of images.
///
/// Parameter `texture`: The MTLTexture allocated by the user to be used as backing for MPSImage.
///
/// Parameter `featureChannels`: Number of feature channels this texture contains.
///
/// Returns: A valid MPSImage object or nil, if failure.
///
/// Application can let MPS framework allocate texture with properties specified in imageDescriptor
/// using initWithDevice:MPSImageDescriptor API above. However in memory intensive application,
/// you can save memory (and allocation/deallocation time) by using MPSTemporaryImage where MPS
/// framework aggressively reuse memory underlying textures on same command buffer. See MPSTemporaryImage
/// class for details below. However, in certain cases, application developer may want more control
/// on allocation, placement, reusing/recycling of memory backing textures used in application using
/// Metal Heaps API. In this case, application can create MPSImage from pre-allocated texture using
/// initWithTexture:featureChannels.
///
/// MTLTextureType of texture can be MTLTextureType2D ONLY if featureChannels
/// <
/// = 4 in which case
/// MPSImage.numberOfImages is set to 1. Else it should be MTLTextureType2DArray with
/// arrayLength == numberOfImage * ((featureChannels + 3)/4). MPSImage.numberOfImages is set to
/// texture.arrayLength / ((featureChannels + 3)/4).
///
/// For MTLTextures containing typical image data which application may obtain from MetalKit or
/// other libraries such as that drawn from a JPEG or PNG, featureChannels should
/// be set to number of valid color channel e.g. for RGB data, even thought MTLPixelFormat will be
/// MTLPixelFormatRGBA, featureChannels should be set to 3.
///
/// # Safety
///
/// - `texture` may need to be synchronized.
/// - `texture` may be unretained, you must ensure it is kept alive while in use.
#[unsafe(method(initWithTexture:featureChannels:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithTexture_featureChannels(
this: Allocated<Self>,
texture: &ProtocolObject<dyn MTLTexture>,
feature_channels: NSUInteger,
) -> Retained<Self>;
#[unsafe(method(init))]
#[unsafe(method_family = init)]
pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;
/// 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.
#[unsafe(method(batchRepresentationWithSubRange:))]
#[unsafe(method_family = none)]
pub unsafe fn batchRepresentationWithSubRange(
&self,
sub_range: NSRange,
) -> Retained<MPSImageBatch>;
/// 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
#[unsafe(method(batchRepresentation))]
#[unsafe(method_family = none)]
pub unsafe fn batchRepresentation(&self) -> Retained<MPSImageBatch>;
#[unsafe(method(subImageWithFeatureChannelRange:))]
#[unsafe(method_family = none)]
pub unsafe fn subImageWithFeatureChannelRange(&self, range: NSRange) -> Retained<MPSImage>;
/// 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).
#[unsafe(method(resourceSize))]
#[unsafe(method_family = none)]
pub unsafe fn resourceSize(&self) -> NSUInteger;
/// 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.
#[unsafe(method(setPurgeableState:))]
#[unsafe(method_family = none)]
pub unsafe fn setPurgeableState(&self, state: MPSPurgeableState) -> MPSPurgeableState;
/// 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.
#[unsafe(method(readBytes:dataLayout:bytesPerRow:region:featureChannelInfo:imageIndex:))]
#[unsafe(method_family = none)]
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,
);
/// 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.
#[unsafe(method(writeBytes:dataLayout:bytesPerRow:region:featureChannelInfo:imageIndex:))]
#[unsafe(method_family = none)]
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,
);
/// 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.
#[unsafe(method(writeBytes:dataLayout:bytesPerColumn:bytesPerRow:bytesPerImage:region:featureChannelInfo:imageIndex:))]
#[unsafe(method_family = none)]
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,
);
/// 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.
#[unsafe(method(readBytes:dataLayout:bytesPerRow:bytesPerImage:region:featureChannelInfo:imageIndex:))]
#[unsafe(method_family = none)]
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,
);
/// 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.
#[unsafe(method(writeBytes:dataLayout:bytesPerRow:bytesPerImage:region:featureChannelInfo:imageIndex:))]
#[unsafe(method_family = none)]
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,
);
/// 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.
#[unsafe(method(readBytes:dataLayout:imageIndex:))]
#[unsafe(method_family = none)]
pub unsafe fn readBytes_dataLayout_imageIndex(
&self,
data_bytes: NonNull<c_void>,
data_layout: MPSDataLayout,
image_index: NSUInteger,
);
/// 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.
#[unsafe(method(writeBytes:dataLayout:imageIndex:))]
#[unsafe(method_family = none)]
pub unsafe fn writeBytes_dataLayout_imageIndex(
&self,
data_bytes: NonNull<c_void>,
data_layout: MPSDataLayout,
image_index: NSUInteger,
);
/// 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
#[unsafe(method(synchronizeOnCommandBuffer:))]
#[unsafe(method_family = none)]
pub unsafe fn synchronizeOnCommandBuffer(
&self,
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
);
);
}
/// Methods declared on superclass `NSObject`.
impl MPSImage {
extern_methods!(
#[unsafe(method(new))]
#[unsafe(method_family = new)]
pub unsafe fn new() -> Retained<Self>;
);
}
extern_class!(
/// 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](https://developer.apple.com/documentation/metalperformanceshaders/mpstemporaryimage?language=objc)
#[unsafe(super(MPSImage, NSObject))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct MPSTemporaryImage;
);
extern_conformance!(
unsafe impl NSObjectProtocol for MPSTemporaryImage {}
);
impl MPSTemporaryImage {
extern_methods!(
/// Get a well known MPSImageAllocator that makes MPSTemporaryImages
#[unsafe(method(defaultAllocator))]
#[unsafe(method_family = none)]
pub unsafe fn defaultAllocator() -> Retained<ProtocolObject<dyn MPSImageAllocator>>;
/// 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.
#[unsafe(method(temporaryImageWithCommandBuffer:imageDescriptor:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryImageWithCommandBuffer_imageDescriptor(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
image_descriptor: &MPSImageDescriptor,
) -> Retained<Self>;
/// 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.
#[unsafe(method(temporaryImageWithCommandBuffer:textureDescriptor:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryImageWithCommandBuffer_textureDescriptor(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
texture_descriptor: &MTLTextureDescriptor,
) -> Retained<Self>;
/// 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.
#[unsafe(method(temporaryImageWithCommandBuffer:textureDescriptor:featureChannels:))]
#[unsafe(method_family = none)]
pub unsafe fn temporaryImageWithCommandBuffer_textureDescriptor_featureChannels(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
texture_descriptor: &MTLTextureDescriptor,
feature_channels: NSUInteger,
) -> Retained<Self>;
/// 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
#[unsafe(method(prefetchStorageWithCommandBuffer:imageDescriptorList:))]
#[unsafe(method_family = none)]
pub unsafe fn prefetchStorageWithCommandBuffer_imageDescriptorList(
command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
descriptor_list: &NSArray<MPSImageDescriptor>,
);
/// 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.
#[unsafe(method(initWithTexture:featureChannels:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithTexture_featureChannels(
this: Allocated<Self>,
texture: &ProtocolObject<dyn MTLTexture>,
feature_channels: NSUInteger,
) -> Retained<Self>;
/// Unavailable. Use itemporaryImageForCommandBuffer:textureDescriptor: instead.
#[unsafe(method(initWithDevice:imageDescriptor:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithDevice_imageDescriptor(
this: Allocated<Self>,
device: &ProtocolObject<dyn MTLDevice>,
image_descriptor: &MPSImageDescriptor,
) -> Retained<Self>;
#[unsafe(method(readCount))]
#[unsafe(method_family = none)]
pub unsafe fn readCount(&self) -> NSUInteger;
/// Setter for [`readCount`][Self::readCount].
#[unsafe(method(setReadCount:))]
#[unsafe(method_family = none)]
pub unsafe fn setReadCount(&self, read_count: NSUInteger);
);
}
/// Methods declared on superclass `MPSImage`.
impl MPSTemporaryImage {
extern_methods!(
/// 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.
#[unsafe(method(initWithParentImage:sliceRange:featureChannels:))]
#[unsafe(method_family = init)]
pub unsafe fn initWithParentImage_sliceRange_featureChannels(
this: Allocated<Self>,
parent: &MPSImage,
slice_range: NSRange,
feature_channels: NSUInteger,
) -> Retained<Self>;
#[unsafe(method(init))]
#[unsafe(method_family = init)]
pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;
);
}
/// Methods declared on superclass `NSObject`.
impl MPSTemporaryImage {
extern_methods!(
#[unsafe(method(new))]
#[unsafe(method_family = new)]
pub unsafe fn new() -> Retained<Self>;
);
}
extern "C-unwind" {
#[deprecated = "renamed to `MPSImage::batch_increment_read_count`"]
pub fn MPSImageBatchIncrementReadCount(batch: &MPSImageBatch, amount: NSInteger) -> NSUInteger;
}
extern "C-unwind" {
#[deprecated = "renamed to `MPSImage::batch_synchronize`"]
pub fn MPSImageBatchSynchronize(
batch: &MPSImageBatch,
cmd_buf: &ProtocolObject<dyn MTLCommandBuffer>,
);
}
extern "C-unwind" {
#[deprecated = "renamed to `MPSImage::batch_resource_size`"]
pub fn MPSImageBatchResourceSize(batch: &MPSImageBatch) -> NSUInteger;
}
extern "C-unwind" {
#[cfg(feature = "block2")]
#[deprecated = "renamed to `MPSImage::batch_iterate`"]
pub fn MPSImageBatchIterate(
batch: &MPSImageBatch,
iterator_block: &block2::DynBlock<dyn Fn(NonNull<MPSImage>, NSUInteger) -> NSInteger>,
) -> NSInteger;
}