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
use libc::c_void;
use std;
use std::mem;
use std::marker::PhantomData;
use std::collections::HashMap;
use num::FromPrimitive;
use error::{Error as OclError, Result as OclResult};
use ffi::{self, cl_mem, cl_buffer_region, cl_context_properties, cl_platform_id};
use ::{Mem, MemObjectType, ImageChannelOrder, ImageChannelDataType, ContextProperty,
PlatformId, OclPrm};
pub type TemporaryPlaceholderType = ();
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct OpenclVersion {
ver: [u16; 2],
}
impl OpenclVersion {
pub fn new(major: u16, minor: u16) -> OpenclVersion {
OpenclVersion { ver: [major, minor] }
}
pub fn max(&self) -> OpenclVersion {
OpenclVersion { ver: [u16::max_value(), u16::max_value()] }
}
pub fn from_info_str(ver: &str) -> OclResult<OpenclVersion> {
let mut version_word_idx: Option<usize> = None;
let mut version: Option<OpenclVersion> = None;
for (word_idx, word) in ver.split_whitespace().enumerate() {
if let Some(wi) = version_word_idx {
assert!(wi == word_idx);
let nums: Vec<_> = word.split('.').collect();
if nums.len() == 2 {
let (major, minor) = (nums[0].parse::<u16>(), nums[1].parse::<u16>());
if major.is_ok() && minor.is_ok() {
version = Some(OpenclVersion::new(major.unwrap(), minor.unwrap()));
}
}
break;
}
for (ch_idx, ch) in word.chars().enumerate() {
match ch_idx {
0 => if ch != 'O' && ch != 'o' { break; },
1 => if ch != 'P' && ch != 'p' { break; },
2 => if ch != 'E' && ch != 'e' { break; },
3 => if ch != 'N' && ch != 'n' { break; },
4 => if ch != 'C' && ch != 'c' { break; },
5 => if ch == 'L' || ch == 'l' {
version_word_idx = Some(word_idx + 1);
break;
},
_ => break,
}
}
}
match version {
Some(cl_ver) => Ok(cl_ver),
None => OclError::err_string(format!("DeviceInfoResult::as_opencl_version(): \
Error parsing version from the string: '{}'.", ver)),
}
}
}
impl From<[u16; 2]> for OpenclVersion {
fn from(ver: [u16; 2]) -> OpenclVersion {
OpenclVersion { ver: ver }
}
}
impl std::fmt::Display for OpenclVersion {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}.{}", self.ver[0], self.ver[1])
}
}
#[derive(Clone, Debug)]
pub enum ContextPropertyValue {
Platform(PlatformId),
InteropUserSync(bool),
D3d10DeviceKhr(*mut ffi::cl_d3d10_device_source_khr),
GlContextKhr(ffi::cl_GLuint),
EglDisplayKhr(ffi::CLeglDisplayKHR),
GlxDisplayKhr(*mut c_void),
CglSharegroupKhr(*mut c_void),
WglHdcKhr(*mut c_void),
AdapterD3d9Khr(isize),
AdapterD3d9exKhr(isize),
AdapterDxvaKhr(isize),
D3d11DeviceKhr(isize),
}
#[derive(Clone, Debug)]
pub struct ContextProperties(HashMap<ContextProperty, ContextPropertyValue>);
impl ContextProperties {
pub fn new() -> ContextProperties {
ContextProperties(HashMap::with_capacity(16))
}
pub fn platform<P: Into<PlatformId>>(mut self, platform: P) -> ContextProperties {
self.set_platform(platform);
self
}
pub fn interop_user_sync(mut self, sync: bool) -> ContextProperties {
self.set_interop_user_sync(sync);
self
}
pub fn gl_context(mut self, gl_ctx: ffi::cl_GLuint) -> ContextProperties {
self.set_gl_context(gl_ctx);
self
}
pub fn cgl_sharegroup(mut self, gl_sharegroup: *mut c_void) -> ContextProperties {
self.set_cgl_sharegroup(gl_sharegroup);
self
}
pub fn property_value(mut self, prop: ContextPropertyValue) -> ContextProperties {
self.set_property_value(prop);
self
}
pub fn set_platform<P: Into<PlatformId>>(&mut self, platform: P) {
self.0.insert(ContextProperty::Platform, ContextPropertyValue::Platform(platform.into()));
}
pub fn set_interop_user_sync(&mut self, sync: bool) {
self.0.insert(ContextProperty::InteropUserSync, ContextPropertyValue::InteropUserSync(sync));
}
pub fn set_gl_context(&mut self, gl_ctx: ffi::cl_GLuint) {
self.0.insert(ContextProperty::GlContextKhr, ContextPropertyValue::GlContextKhr(gl_ctx));
}
pub fn set_cgl_sharegroup(&mut self, gl_sharegroup: *mut c_void) {
self.0.insert(ContextProperty::CglSharegroupKhr, ContextPropertyValue::CglSharegroupKhr(gl_sharegroup));
}
pub fn set_property_value(&mut self, prop: ContextPropertyValue) {
match prop {
ContextPropertyValue::Platform(val) => {
self.0.insert(ContextProperty::Platform, ContextPropertyValue::Platform(val));
},
ContextPropertyValue::InteropUserSync(val) => {
self.0.insert(ContextProperty::InteropUserSync,
ContextPropertyValue::InteropUserSync(val));
},
ContextPropertyValue::GlContextKhr(val) => {
self.0.insert(ContextProperty::GlContextKhr,
ContextPropertyValue::GlContextKhr(val));
},
ContextPropertyValue::CglSharegroupKhr(val) => {
self.0.insert(ContextProperty::CglSharegroupKhr,
ContextPropertyValue::CglSharegroupKhr(val));
},
_ => panic!("'{:?}' is not yet a supported variant.", prop),
}
}
pub fn get_platform(&self) -> Option<PlatformId> {
match self.0.get(&ContextProperty::Platform) {
Some(prop_val) => {
if let ContextPropertyValue::Platform(ref plat) = *prop_val {
Some(plat.clone())
} else {
panic!("Internal error returning platform.");
}
},
None => None
}
}
pub fn get_cgl_sharegroup(&self) -> Option<*mut c_void> {
match self.0.get(&ContextProperty::CglSharegroupKhr) {
Some(prop_val) => {
if let ContextPropertyValue::CglSharegroupKhr(ref cgl_sharegroup) = *prop_val {
Some(cgl_sharegroup.clone())
} else {
panic!("Internal error returning cgl_sharegroup.");
}
},
None => None
}
}
pub fn to_raw(&self) -> Vec<isize> {
let mut props_raw = Vec::with_capacity(32);
for (key, val) in self.0.iter() {
match *val {
ContextPropertyValue::Platform(ref platform_id_core) => {
props_raw.push(key.clone() as isize);
props_raw.push(platform_id_core.as_ptr() as isize);
},
ContextPropertyValue::InteropUserSync(sync) => {
props_raw.push(key.clone() as isize);
props_raw.push(sync as isize);
},
ContextPropertyValue::CglSharegroupKhr(sync) => {
props_raw.push(key.clone() as isize);
props_raw.push(sync as isize);
},
_ => panic!("'{:?}' is not yet a supported variant.", key),
};
}
props_raw.push(0);
props_raw.shrink_to_fit();
props_raw
}
pub unsafe fn extract_property_from_raw(property: ContextProperty,
raw_context_properties: &[isize]) -> Option<ContextPropertyValue>
{
assert!(raw_context_properties.len() % 2 == 1);
assert!(*raw_context_properties.last().unwrap() == 0);
let pair_count = raw_context_properties.len() / 2;
match property {
ContextProperty::Platform => {
for pair_idx in 0..pair_count {
let idz = pair_idx * 2;
let key_raw = *raw_context_properties.get_unchecked(idz);
let val_raw = *raw_context_properties.get_unchecked(idz + 1);
if key_raw == property as cl_context_properties {
return Some(ContextPropertyValue::Platform(
PlatformId::from_raw(val_raw as cl_platform_id)));
}
}
},
_ => unimplemented!(),
}
None
}
#[allow(unused_variables, unused_mut)]
pub unsafe fn from_raw(raw_context_properties: &[isize]) -> OclResult<ContextProperties> {
assert!(mem::size_of::<cl_context_properties>() == mem::size_of::<isize>());
assert!(raw_context_properties.len() % 2 == 1);
assert!(*raw_context_properties.last().unwrap() == 0);
let pair_count = raw_context_properties.len() / 2;
let mut context_props = ContextProperties(HashMap::with_capacity(pair_count));
for pair_idx in 0..pair_count {
let idz = pair_idx * 2;
let key_raw = *raw_context_properties.get_unchecked(idz);
let val_raw = *raw_context_properties.get_unchecked(idz + 1);
let key = ContextProperty::from_isize(key_raw).ok_or(OclError::from(
format!("ContextProperties::from_raw: Unable to convert '{}' using \
'ContextProperty::from_isize'.", key_raw)))?;
match key {
ContextProperty::Platform => {
context_props.0.insert(ContextProperty::Platform,
ContextPropertyValue::Platform(PlatformId::from_raw(val_raw as cl_platform_id))
);
},
ContextProperty::InteropUserSync => {
context_props.0.insert(ContextProperty::InteropUserSync,
ContextPropertyValue::InteropUserSync(val_raw > 0),
);
},
ContextProperty::D3d10DeviceKhr => {
context_props.0.insert(ContextProperty::D3d10DeviceKhr,
ContextPropertyValue::D3d10DeviceKhr(val_raw as *mut ffi::cl_d3d10_device_source_khr),
);
},
ContextProperty::GlContextKhr => {
context_props.0.insert(ContextProperty::GlContextKhr,
ContextPropertyValue::GlContextKhr(val_raw as ffi::cl_GLuint),
);
},
ContextProperty::EglDisplayKhr => {
context_props.0.insert(ContextProperty::EglDisplayKhr,
ContextPropertyValue::EglDisplayKhr(val_raw as ffi::CLeglDisplayKHR),
);
},
ContextProperty::GlxDisplayKhr => {
context_props.0.insert(ContextProperty::GlxDisplayKhr,
ContextPropertyValue::GlxDisplayKhr(val_raw as *mut c_void),
);
},
ContextProperty::CglSharegroupKhr => {
context_props.0.insert(ContextProperty::CglSharegroupKhr,
ContextPropertyValue::CglSharegroupKhr(val_raw as *mut c_void),
);
},
ContextProperty::WglHdcKhr => {
context_props.0.insert(ContextProperty::WglHdcKhr,
ContextPropertyValue::WglHdcKhr(val_raw as *mut c_void),
);
},
ContextProperty::AdapterD3d9Khr => {
context_props.0.insert(ContextProperty::AdapterD3d9Khr,
ContextPropertyValue::AdapterD3d9Khr(val_raw),
);
},
ContextProperty::AdapterD3d9exKhr => {
context_props.0.insert(ContextProperty::AdapterD3d9exKhr,
ContextPropertyValue::AdapterD3d9exKhr(val_raw),
);
},
ContextProperty::AdapterDxvaKhr => {
context_props.0.insert(ContextProperty::AdapterDxvaKhr,
ContextPropertyValue::AdapterDxvaKhr(val_raw),
);
},
ContextProperty::D3d11DeviceKhr => {
context_props.0.insert(ContextProperty::D3d11DeviceKhr,
ContextPropertyValue::D3d11DeviceKhr(val_raw),
);
},
}
}
Ok(context_props)
}
}
impl From<ContextProperties> for Vec<isize> {
fn from(cp: ContextProperties) -> Vec<isize> {
cp.to_raw()
}
}
pub struct BufferRegion<T> {
origin: usize,
len: usize,
_data: PhantomData<T>,
}
impl<T: OclPrm> BufferRegion<T> {
pub fn new(origin: usize, len: usize) -> BufferRegion<T> {
BufferRegion {
origin: origin,
len: len,
_data: PhantomData,
}
}
pub fn to_bytes(&self) -> cl_buffer_region {
cl_buffer_region {
origin: self.origin * mem::size_of::<T>(),
size: self.len * mem::size_of::<T>(),
}
}
pub fn from_bytes(ffi_struct: cl_buffer_region) -> BufferRegion<T> {
assert!(ffi_struct.origin % mem::size_of::<T>() == 0);
assert!(ffi_struct.size % mem::size_of::<T>() == 0);
BufferRegion::new(ffi_struct.origin / mem::size_of::<T>(),
ffi_struct.size / mem::size_of::<T>())
}
}
pub enum ImageFormatParseError {
UnknownImageChannelOrder(ffi::cl_channel_order),
UnknownImageChannelDataType(ffi::cl_channel_type),
}
impl ::std::fmt::Debug for ImageFormatParseError {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match *self {
ImageFormatParseError::UnknownImageChannelOrder(ord) => {
write!(f, "unknown image channel ordering: '{}'", ord)
},
ImageFormatParseError::UnknownImageChannelDataType(dt) => {
write!(f, "unknown image channel data type: '{}'", dt)
},
}
}
}
impl ::std::fmt::Display for ImageFormatParseError {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl ::std::error::Error for ImageFormatParseError {
fn description(&self) -> &str {
match *self {
ImageFormatParseError::UnknownImageChannelOrder(_) => "unknown image channel ordering",
ImageFormatParseError::UnknownImageChannelDataType(_) => "unknown image channel data type",
}
}
}
pub type ImageFormatParseResult = Result<ImageFormat, ImageFormatParseError>;
#[derive(Debug, Clone)]
pub struct ImageFormat {
pub channel_order: ImageChannelOrder,
pub channel_data_type: ImageChannelDataType,
}
impl ImageFormat {
pub fn new(order: ImageChannelOrder, data_type: ImageChannelDataType) -> ImageFormat {
ImageFormat {
channel_order: order,
channel_data_type: data_type,
}
}
pub fn new_rgba() -> ImageFormat {
ImageFormat {
channel_order: ImageChannelOrder::Rgba,
channel_data_type: ImageChannelDataType::SnormInt8,
}
}
pub fn from_raw(fmt_raw: ffi::cl_image_format) -> ImageFormatParseResult {
let channel_order = match ImageChannelOrder::from_u32(fmt_raw.image_channel_order) {
Some(ord) => ord,
None => return Err(ImageFormatParseError::UnknownImageChannelOrder(
fmt_raw.image_channel_order)),
};
let channel_data_type = match ImageChannelDataType::from_u32(fmt_raw.image_channel_data_type) {
Some(dt) => dt,
None => return Err(ImageFormatParseError::UnknownImageChannelDataType(
fmt_raw.image_channel_data_type)),
};
Ok(ImageFormat { channel_order, channel_data_type })
}
pub fn list_from_raw(list_raw: Vec<ffi::cl_image_format>)
-> Vec<ImageFormatParseResult>
{
list_raw.into_iter().map(|fmt_raw| ImageFormat::from_raw(fmt_raw)).collect()
}
pub fn to_raw(&self) -> ffi::cl_image_format {
ffi::cl_image_format {
image_channel_order: self.channel_order as ffi::cl_channel_order,
image_channel_data_type: self.channel_data_type as ffi::cl_channel_type,
}
}
pub fn new_raw() -> ffi::cl_image_format {
ffi::cl_image_format {
image_channel_order: 0 as ffi::cl_channel_order,
image_channel_data_type: 0 as ffi::cl_channel_type,
}
}
pub fn pixel_bytes(&self) -> usize {
let channel_count = match self.channel_order {
ImageChannelOrder::R => 1,
ImageChannelOrder::A => 1,
ImageChannelOrder::Rg => 2,
ImageChannelOrder::Ra => 2,
ImageChannelOrder::Rgb => 1,
ImageChannelOrder::Rgba => 4,
ImageChannelOrder::Bgra => 4,
ImageChannelOrder::Argb => 4,
ImageChannelOrder::Intensity => 4,
ImageChannelOrder::Luminance => 4,
ImageChannelOrder::Rx => 2,
ImageChannelOrder::Rgx => 4,
ImageChannelOrder::Rgbx => 4,
_ => 0,
};
let channel_size = match self.channel_data_type {
ImageChannelDataType::SnormInt8 => 1,
ImageChannelDataType::SnormInt16 => 2,
ImageChannelDataType::UnormInt8 => 1,
ImageChannelDataType::UnormInt16 => 2,
ImageChannelDataType::UnormShort565 => 2,
ImageChannelDataType::UnormShort555 => 2,
ImageChannelDataType::UnormInt101010 => 4,
ImageChannelDataType::SignedInt8 => 1,
ImageChannelDataType::SignedInt16 => 2,
ImageChannelDataType::SignedInt32 => 4,
ImageChannelDataType::UnsignedInt8 => 1,
ImageChannelDataType::UnsignedInt16 => 2,
ImageChannelDataType::UnsignedInt32 => 4,
ImageChannelDataType::HalfFloat => 2,
ImageChannelDataType::Float => 4,
_ => 0
};
channel_count * channel_size
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct ImageDescriptor {
pub image_type: MemObjectType,
pub image_width: usize,
pub image_height: usize,
pub image_depth: usize,
pub image_array_size: usize,
pub image_row_pitch: usize,
pub image_slice_pitch: usize,
num_mip_levels: u32,
num_samples: u32,
pub buffer: Option<Mem>,
}
impl ImageDescriptor {
pub fn new(image_type: MemObjectType, width: usize, height: usize, depth: usize,
array_size: usize, row_pitch: usize, slc_pitch: usize, buffer: Option<Mem>,
) -> ImageDescriptor {
ImageDescriptor {
image_type: image_type,
image_width: width,
image_height: height,
image_depth: depth,
image_array_size: array_size,
image_row_pitch: row_pitch,
image_slice_pitch: slc_pitch,
num_mip_levels: 0,
num_samples: 0,
buffer: buffer,
}
}
pub fn to_raw(&self) -> ffi::cl_image_desc {
ffi::cl_image_desc {
image_type: self.image_type as u32,
image_width: self.image_width,
image_height: self.image_height,
image_depth: self.image_depth,
image_array_size: self.image_array_size,
image_row_pitch: self.image_row_pitch,
image_slice_pitch: self.image_slice_pitch,
num_mip_levels: self.num_mip_levels,
num_samples: self.num_mip_levels,
buffer: match self.buffer {
Some(ref b) => b.as_ptr(),
None => 0 as cl_mem,
},
}
}
}