forked from MooreThreads/mthreads-ml-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpymtml.py
More file actions
2409 lines (1876 loc) · 67.3 KB
/
pymtml.py
File metadata and controls
2409 lines (1876 loc) · 67.3 KB
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
##
# Python bindings for the MTML library
##
from __future__ import annotations
import string
import sys
import threading
from ctypes import *
from dataclasses import dataclass
from functools import wraps
from typing import TYPE_CHECKING as _TYPE_CHECKING
from contextlib import contextmanager
if _TYPE_CHECKING:
from typing_extensions import TypeAlias as _TypeAlias # Python 3.10+
## C Type mappings ##
## Constants
MTML_LIBRARY_VERSION_BUFFER_SIZE = 32
MTML_DRIVER_VERSION_BUFFER_SIZE = 80
MTML_DEVICE_NAME_BUFFER_SIZE = 32
MTML_DEVICE_UUID_BUFFER_SIZE = 48
MTML_DEVICE_MTBIOS_VERSION_BUFFER_SIZE = 64
MTML_DEVICE_VBIOS_VERSION_BUFFER_SIZE = MTML_DEVICE_MTBIOS_VERSION_BUFFER_SIZE
MTML_DEVICE_PATH_BUFFER_SIZE = 64
MTML_DEVICE_PCI_SBDF_BUFFER_SIZE = 32
MTML_VIRT_TYPE_ID_BUFFER_SIZE = 16
MTML_VIRT_TYPE_CLASS_BUFFER_SIZE = 32
MTML_VIRT_TYPE_NAME_BUFFER_SIZE = 32
MTML_VIRT_TYPE_API_BUFFER_SIZE = 16
MTML_LOG_FILE_PATH_BUFFER_SIZE = 200
MTML_MPC_PROFILE_NAME_BUFFER_SIZE = 32
MTML_MPC_CONF_NAME_BUFFER_SIZE = 32
MTML_MPC_CONF_MAX_PROF_NUM = 16
MTML_DEVICE_SLOT_NAME_BUFFER_SIZE = 32
MTML_MEMORY_VENDOR_BUFFER_SIZE = 64
MTML_DEVICE_SERIAL_NUMBER_BUFFER_SIZE = 64
MTML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE = 80
MTML_DEVICE_PCI_BUS_ID_BUFFER_SIZE = 32
## Enums
_mtmlReturn_t = c_uint
MTML_SUCCESS = 0
MTML_ERROR_DRIVER_NOT_LOADED = 1
MTML_ERROR_DRIVER_FAILURE = 2
MTML_ERROR_INVALID_ARGUMENT = 3
MTML_ERROR_NOT_SUPPORTED = 4
MTML_ERROR_NO_PERMISSION = 5
MTML_ERROR_INSUFFICIENT_SIZE = 6
MTML_ERROR_NOT_FOUND = 7
MTML_ERROR_INSUFFICIENT_MEMORY = 8
MTML_ERROR_DRIVER_TOO_OLD = 9
MTML_ERROR_DRIVER_TOO_NEW = 10
MTML_ERROR_TIMEOUT = 11
MTML_ERROR_RESOURCE_IS_BUSY = 12
MTML_ERROR_UNKNOWN = 999
# Additional error codes for compatibility
MTML_ERROR_UNINITIALIZED = 666
MTML_ERROR_FUNCTION_NOT_FOUND = 667
MTML_ERROR_GPU_IS_LOST = 669
MTML_ERROR_LIBRARY_NOT_FOUND = 670
_mtmlBrandType_t = c_uint
MTML_BRAND_MTT = 0
MTML_BRAND_UNKNOWN = 1
MTML_BRAND_COUNT = 2
_mtmlMemoryType_t = c_uint
MTML_MEM_TYPE_LPDDR4 = 0
MTML_MEM_TYPE_GDDR6 = 1
_mtmlCodecType_t = c_uint
MTML_CODEC_TYPE_AVC = 0
MTML_CODEC_TYPE_VC1 = 1
MTML_CODEC_TYPE_MPEG2 = 2
MTML_CODEC_TYPE_MPEG4 = 3
MTML_CODEC_TYPE_H263 = 4
MTML_CODEC_TYPE_DIV3 = 5
MTML_CODEC_TYPE_RV = 6
MTML_CODEC_TYPE_AVS = 7
MTML_CODEC_TYPE_RSVD1 = 8
MTML_CODEC_TYPE_THO = 9
MTML_CODEC_TYPE_VP3 = 10
MTML_CODEC_TYPE_VP8 = 11
MTML_CODEC_TYPE_HEVC = 12
MTML_CODEC_TYPE_VP9 = 13
MTML_CODEC_TYPE_AVS2 = 14
MTML_CODEC_TYPE_RSVD2 = 15
MTML_CODEC_TYPE_AV1 = 16
MTML_CODEC_TYPE_COUNT = 17
_mtmlCodecSessionState_t = c_uint
MTML_CODEC_SESSION_STATE_UNKNOWN = -1
MTML_CODEC_SESSION_STATE_IDLE = 0
MTML_CODEC_SESSION_STATE_ACTIVE = 1
MTML_CODEC_SESSION_STATE_COUNT = 2
_mtmlVirtCapability_t = c_uint
MTML_DEVICE_NOT_SUPPORT_VIRTUALIZATION = 0
MTML_DEVICE_SUPPORT_VIRTUALIZATION = 1
_mtmlVirtRole_t = c_uint
MTML_VIRT_ROLE_NONE = 0
MTML_VIRT_ROLE_HOST_VIRTDEVICE = 1
MTML_VIRT_ROLE_GUEST_VIRTDEVICE = 2
MTML_VIRT_ROLE_COUNT = 3
_mtmlDeviceTopologyLevel_t = c_uint
MTML_TOPOLOGY_INTERNAL = 0
MTML_TOPOLOGY_SINGLE = 1
MTML_TOPOLOGY_MULTIPLE = 2
MTML_TOPOLOGY_HOSTBRIDGE = 3
MTML_TOPOLOGY_NODE = 4
MTML_TOPOLOGY_SYSTEM = 5
_mtmlLogLevel_t = c_uint
MTML_LOG_LEVEL_OFF = 0
MTML_LOG_LEVEL_FATAL = 1
MTML_LOG_LEVEL_ERROR = 2
MTML_LOG_LEVEL_WARNING = 3
MTML_LOG_LEVEL_INFO = 4
_mtmlMpcMode_t = c_uint
MTML_DEVICE_MPC_DISABLE = 0
MTML_DEVICE_MPC_ENABLE = 1
_mtmlMpcCapability_t = c_uint
MTML_DEVICE_NOT_SUPPORT_MPC = 0
MTML_DEVICE_SUPPORT_MPC = 1
_mtmlMpcType_t = c_uint
MTML_MPC_TYPE_NONE = 0
MTML_MPC_TYPE_PARENT = 1
MTML_MPC_TYPE_INSTANCE = 2
_mtmlDeviceP2PStatus_t = c_uint
MTML_P2P_STATUS_OK = 0
MTML_P2P_STATUS_CHIPSET_NOT_SUPPORTED = 1
MTML_P2P_STATUS_GPU_NOT_SUPPORTED = 2
MTML_P2P_STATUS_UNKNOWN = 3
_mtmlDeviceP2PCaps_t = c_uint
MTML_P2P_CAPS_READ = 0
MTML_P2P_CAPS_WRITE = 1
_mtmlGpuEngine_t = c_uint
MTML_GPU_ENGINE_GEOMETRY = 0
MTML_GPU_ENGINE_2D = 1
MTML_GPU_ENGINE_3D = 2
MTML_GPU_ENGINE_COMPUTE = 3
MTML_GPU_ENGINE_MAX = 4
_mtmlEccMode_t = c_uint
MTML_MEMORY_ECC_DISABLE = 0
MTML_MEMORY_ECC_ENABLE = 1
_mtmlPageRetirementCause_t = c_uint
MTML_PAGE_RETIREMENT_CAUSE_MULTIPLE_SINGLE_BIT_ECC_ERRORS = 0
MTML_PAGE_RETIREMENT_CAUSE_DOUBLE_BIT_ECC_ERROR = 1
MTML_PAGE_RETIREMENT_CAUSE_MAX = 2
_mtmlRetiredPagesPendingState_t = c_uint
MTML_RETIRED_PAGES_PENDING_STATE_FALSE = 0
MTML_RETIRED_PAGES_PENDING_STATE_TRUE = 1
_mtmlEccCounterType_t = c_uint
MTML_VOLATILE_ECC = 0
MTML_AGGREGATE_ECC = 1
MTML_ECC_COUNTER_TYPE_COUNT = 2
_mtmlMemoryErrorType_t = c_uint
MTML_MEMORY_ERROR_TYPE_CORRECTED = 0
MTML_MEMORY_ERROR_TYPE_UNCORRECTED = 1
MTML_MEMORY_ERROR_TYPE_COUNT = 2
_mtmlMemoryLocation_t = c_uint
MTML_MEMORY_LOCATION_DRAM = 0x1
_mtmlDispIntfType_t = c_uint
MTML_DISP_INTF_TYPE_DP = 0
MTML_DISP_INTF_TYPE_EDP = 1
MTML_DISP_INTF_TYPE_VGA = 2
MTML_DISP_INTF_TYPE_HDMI = 3
MTML_DISP_INTF_TYPE_LVDS = 4
MTML_DISP_INTF_TYPE_MAX = 5
_mtmlMtLinkState_t = c_uint
MTML_MTLINK_STATE_DOWN = 0
MTML_MTLINK_STATE_UP = 1
MTML_MTLINK_STATE_DOWNGRADE = 2
## Library structures
class struct_c_mtmlLibrary_t(Structure):
pass # opaque handle
c_mtmlLibrary_t = POINTER(struct_c_mtmlLibrary_t)
## Device structures
class struct_c_mtmlDevice_t(Structure):
pass # opaque handle
c_mtmlDevice_t = POINTER(struct_c_mtmlDevice_t)
## FieldValue structures(for nvmlFieldValue_t)
class struct_c_mtmlFieldValue_t(Structure):
pass # opaque handle
c_mtmlFieldValue_t = POINTER(struct_c_mtmlFieldValue_t)
## System structures
class struct_c_mtmlSystem_t(Structure):
pass # opaque handle
c_mtmlSystem_t = POINTER(struct_c_mtmlSystem_t)
## Memory structures
class struct_c_mtmlMemory_t(Structure):
pass # opaque handle
c_mtmlMemory_t = POINTER(struct_c_mtmlMemory_t)
## Gpu structures
class struct_c_mtmlGpu_t(Structure):
pass # opaque handle
c_mtmlGpu_t = POINTER(struct_c_mtmlGpu_t)
## Vpu structures
class struct_c_mtmlVpu_t(Structure):
pass
c_mtmlVpu_t = POINTER(struct_c_mtmlVpu_t)
class mtmlFriendlyObject(object):
def __init__(self, dictionary):
for x in dictionary:
setattr(self, x, dictionary[x])
def __str__(self):
return self.__dict__.__str__()
def mtmlStructToFriendlyObject(struct):
d = {}
for x in struct._fields_:
key = x[0]
value = getattr(struct, key)
# only need to convert from bytes if bytes, no need to check python version.
d[key] = value.decode() if isinstance(value, bytes) else value
obj = mtmlFriendlyObject(d)
return obj
class _PrintableStructure(Structure):
"""
Abstract class that produces nicer __str__ output than ctypes.Structure.
e.g. instead of:
>>> print str(obj)
<class_name object at 0x7fdf82fef9e0>
this class will print
class_name(field_name: formatted_value, field_name: formatted_value)
_fmt_ dictionary of <str _field_ name> -> <str format>
e.g. class that has _field_ 'hex_value', c_uint could be formatted with
_fmt_ = {"hex_value" : "%08X"}
to produce nicer output.
Default formatting string for all fields can be set with key "<default>" like:
_fmt_ = {"<default>" : "%d MHz"} # e.g all values are numbers in MHz.
If not set it's assumed to be just "%s"
Exact format of returned str from this class is subject to change in the future.
"""
_fmt_ = {}
def __str__(self):
result = []
for x in self._fields_:
key = x[0]
value = getattr(self, key)
fmt = "%s"
if key in self._fmt_:
fmt = self._fmt_[key]
elif "<default>" in self._fmt_:
fmt = self._fmt_["<default>"]
result.append(("%s: " + fmt) % (key, value))
return self.__class__.__name__ + "(" + ", ".join(result) + ")"
def __getattribute__(self, name):
res = super(_PrintableStructure, self).__getattribute__(name)
# need to convert bytes to unicode for python3 don't need to for python2
# Python 2 strings are of both str and bytes
# Python 3 strings are not of type bytes
# ctypes should convert everything to the correct values otherwise
if isinstance(res, bytes):
if isinstance(res, str):
return res
return res.decode()
return res
def __setattr__(self, name, value):
if isinstance(value, str):
# encoding a python2 string returns the same value, since python2 strings are bytes already
# bytes passed in python3 will be ignored.
value = value.encode()
super(_PrintableStructure, self).__setattr__(name, value)
## MtLink structures
class c_mtmlMtLinkSpec_t(_PrintableStructure):
_fields_ = [
("version", c_uint),
("bandWidth", c_uint),
("linkNum", c_uint),
("rsvd", c_uint * 4),
]
class c_mtmlPciInfo_t(_PrintableStructure):
_fields_ = [
("sbdf", c_char * MTML_DEVICE_PCI_SBDF_BUFFER_SIZE),
("segment", c_uint),
("bus", c_uint),
("device", c_uint),
("pciDeviceId", c_uint),
("busWidth", c_uint),
("pciMaxSpeed", c_float),
("pciCurSpeed", c_float),
("pciMaxWidth", c_uint),
("pciCurWidth", c_uint),
("pciMaxGen", c_uint),
("pciCurGen", c_uint),
("busId", c_char * MTML_DEVICE_PCI_BUS_ID_BUFFER_SIZE),
("rsvd", c_uint * 6),
]
## Device property structure
class c_mtmlDeviceProperty_t(_PrintableStructure):
_fields_ = [
("virtCapability", c_uint),
("virtRole", c_uint),
("mpcCapability", c_uint),
("mpcType", c_uint),
("rsvd", c_uint * 12),
]
## PCI slot info structure
class c_mtmlPciSlotInfo_t(_PrintableStructure):
_fields_ = [
("slotType", c_uint),
("slotName", c_char * MTML_DEVICE_SLOT_NAME_BUFFER_SIZE),
("rsvd", c_uint * 4),
]
## Display interface spec structure
class c_mtmlDispIntfSpec_t(_PrintableStructure):
_fields_ = [
("type", c_uint),
("maxResWidth", c_uint),
("maxResHeight", c_uint),
("rsvd", c_uint * 4),
]
## Virtualization type structure
class c_mtmlVirtType_t(_PrintableStructure):
_fields_ = [
("id", c_char * MTML_VIRT_TYPE_ID_BUFFER_SIZE),
("deviceClass", c_char * MTML_VIRT_TYPE_CLASS_BUFFER_SIZE),
("name", c_char * MTML_VIRT_TYPE_NAME_BUFFER_SIZE),
("maxInstances", c_uint),
("memSize", c_ulonglong),
("gpuCores", c_uint),
("maxResWidth", c_uint),
("maxResHeight", c_uint),
("apiType", c_char * MTML_VIRT_TYPE_API_BUFFER_SIZE),
("encoderNum", c_uint),
("decoderNum", c_uint),
("rsvd", c_uint * 4),
]
## Codec utilization structure
class c_mtmlCodecUtil_t(_PrintableStructure):
_fields_ = [
("encodeUtil", c_uint),
("decodeUtil", c_uint),
("rsvd", c_uint * 4),
]
## Codec session state structure
class c_mtmlCodecSessionState_t(_PrintableStructure):
_fields_ = [
("sessionId", c_uint),
("state", c_uint),
("rsvd", c_uint * 4),
]
## Codec session metrics structure
class c_mtmlCodecSessionMetrics_t(_PrintableStructure):
_fields_ = [
("width", c_uint),
("height", c_uint),
("codecType", c_uint),
("fps", c_uint),
("rsvd", c_uint * 4),
]
## Log configuration structure
class c_mtmlLogConfiguration_t(_PrintableStructure):
_fields_ = [
("filePath", c_char * MTML_LOG_FILE_PATH_BUFFER_SIZE),
("maxSize", c_uint),
("logLevel", c_uint),
("rsvd", c_uint * 4),
]
## MPC profile structure
class c_mtmlMpcProfile_t(_PrintableStructure):
_fields_ = [
("profileId", c_uint),
("name", c_char * MTML_MPC_PROFILE_NAME_BUFFER_SIZE),
("memSize", c_ulonglong),
("gpuCores", c_uint),
("rsvd", c_uint * 4),
]
## MPC configuration structure
class c_mtmlMpcConfiguration_t(_PrintableStructure):
_fields_ = [
("id", c_uint),
("name", c_char * MTML_MPC_CONF_NAME_BUFFER_SIZE),
("profileNum", c_uint),
("profileIds", c_uint * MTML_MPC_CONF_MAX_PROF_NUM),
("rsvd", c_uint * 4),
]
## MtLink layout structure
class c_mtmlMtLinkLayout_t(_PrintableStructure):
_fields_ = [
("localLinkId", c_uint),
("remoteLinkId", c_uint),
("rsvd", c_uint * 4),
]
## Page retirement count structure
class c_mtmlPageRetirementCount_t(_PrintableStructure):
_fields_ = [
("singleBitEcc", c_uint),
("doubleBitEcc", c_uint),
("rsvd", c_uint * 4),
]
## Page retirement structure
class c_mtmlPageRetirement_t(_PrintableStructure):
_fields_ = [
("address", c_ulonglong),
("timestamp", c_ulonglong),
("rsvd", c_uint * 4),
]
## Lib loading ##
mtmlLib = None
libLoadLock = threading.Lock()
libHandle = c_mtmlLibrary_t()
_mtmlLib_refcount = 0 # Incremented on each mtmlInit and decremented on mtmlShutdown
## Error Checking ##
class MTMLError(Exception):
_valClassMapping = dict()
# List of currently known error codes
_errcode_to_string = {
MTML_ERROR_UNINITIALIZED: "Uninitialized",
MTML_ERROR_NOT_SUPPORTED: "Not Supported",
MTML_ERROR_FUNCTION_NOT_FOUND: "Function Not Found",
MTML_ERROR_UNKNOWN: "Unknown Error",
MTML_ERROR_INSUFFICIENT_SIZE: "Insufficient Size",
MTML_ERROR_GPU_IS_LOST: "Gpu Is Lost",
MTML_ERROR_LIBRARY_NOT_FOUND: "Library Not Found",
MTML_ERROR_NO_PERMISSION: "No Permission",
MTML_ERROR_NOT_FOUND: "Not Found",
}
def __new__(typ, value):
"""
Maps value to a proper subclass of MTMLError.
See _extractMTMLErrorsAsClasses function for more details
"""
if typ == MTMLError:
typ = MTMLError._valClassMapping.get(value, typ)
obj = Exception.__new__(typ)
obj.value = value
return obj
def __str__(self):
try:
if self.value not in MTMLError._errcode_to_string:
MTMLError._errcode_to_string[self.value] = str(
mtmlErrorString(self.value)
)
return MTMLError._errcode_to_string[self.value]
except MTMLError:
return "MTML Error with code %d" % self.value
def __eq__(self, other):
return self.value == other.value
def _extractMTMLErrorsAsClasses():
"""
Generates a hierarchy of classes on top of MTMLError class.
Each MTML Error gets a new MTMLError subclass. This way try,except blocks can filter appropriate
exceptions more easily.
MTMLError is a parent class. Each MTML_ERROR_* gets it's own subclass.
e.g. MTML_ERROR_ALREADY_INITIALIZED will be turned into MTMLError_AlreadyInitialized
"""
this_module = sys.modules[__name__]
mtmlErrorsNames = [x for x in dir(this_module) if x.startswith("MTML_ERROR_")]
for err_name in mtmlErrorsNames:
# e.g. Turn MTML_ERROR_ALREADY_INITIALIZED into MTMLError_AlreadyInitialized
class_name = "MTMLError_" + string.capwords(
err_name.replace("MTML_ERROR_", ""), "_"
).replace("_", "")
err_val = getattr(this_module, err_name)
def gen_new(val):
def new(typ, *args):
obj = MTMLError.__new__(typ, val)
return obj
return new
new_error_class = type(class_name, (MTMLError,), {"__new__": gen_new(err_val)})
new_error_class.__module__ = __name__
setattr(this_module, class_name, new_error_class)
MTMLError._valClassMapping[err_val] = new_error_class
_extractMTMLErrorsAsClasses()
def _mtmlCheckReturn(ret):
if ret != MTML_SUCCESS:
raise MTMLError(ret)
return ret
## Function access ##
_mtmlGetFunctionPointer_cache = (
dict()
) # function pointers are cached to prevent unnecessary libLoadLock locking
def _mtmlGetFunctionPointer(name):
global mtmlLib
if name in _mtmlGetFunctionPointer_cache:
return _mtmlGetFunctionPointer_cache[name]
libLoadLock.acquire()
try:
# ensure library was loaded
if mtmlLib == None:
raise MTMLError(MTML_ERROR_FUNCTION_NOT_FOUND)
try:
_mtmlGetFunctionPointer_cache[name] = getattr(mtmlLib, name)
return _mtmlGetFunctionPointer_cache[name]
except AttributeError:
raise MTMLError(MTML_ERROR_FUNCTION_NOT_FOUND)
finally:
# lock is always freed
libLoadLock.release()
## string/bytes conversion for ease of use
def convertStrBytes(func):
"""
In python 3, strings are unicode instead of bytes, and need to be converted for ctypes
Args from caller: (1, 'string', <__main__.c_mtmlDevice_t at 0xFFFFFFFF>)
Args passed to function: (1, b'string', <__main__.c_mtmlDevice_t at 0xFFFFFFFF)>
----
Returned from function: b'returned string'
Returned to caller: 'returned string'
"""
@wraps(func)
def wrapper(*args, **kwargs):
# encoding a str returns bytes in python 2 and 3
args = [arg.encode() if isinstance(arg, str) else arg for arg in args]
res = func(*args, **kwargs)
# In python 2, str and bytes are the same
# In python 3, str is unicode and should be decoded.
# Ctypes handles most conversions, this only effects c_char and char arrays.
if isinstance(res, bytes):
if isinstance(res, str):
return res
return res.decode()
return res
if sys.version_info >= (3,):
return wrapper
return func
## C function wrappers ##
def _LoadMtmlLibrary():
"""
Load the library if it isn't loaded already
"""
global mtmlLib
if mtmlLib == None:
# lock to ensure only one caller loads the library
libLoadLock.acquire()
try:
# ensure the library still isn't loaded
if mtmlLib == None:
try:
# assume linux
mtmlLib = CDLL("libmtml.so")
except OSError as ose:
_mtmlCheckReturn(MTML_ERROR_FUNCTION_NOT_FOUND)
if mtmlLib == None:
_mtmlCheckReturn(MTML_ERROR_FUNCTION_NOT_FOUND)
finally:
# lock is always freed
libLoadLock.release()
def mtmlLibraryInit():
_LoadMtmlLibrary()
#
# Initialize the library
#
global libHandle
fn = _mtmlGetFunctionPointer("mtmlLibraryInit")
ret = fn(byref(libHandle))
_mtmlCheckReturn(ret)
# Atomically update refcount
global _mtmlLib_refcount
libLoadLock.acquire()
_mtmlLib_refcount += 1
libLoadLock.release()
return None
def mtmlLibraryShutDown():
#
# Leave the library loaded, but shutdown the interface
#
global libHandle
if libHandle is None:
return None
fn = _mtmlGetFunctionPointer("mtmlLibraryShutDown")
ret = fn(libHandle)
_mtmlCheckReturn(ret)
# Reset libHandle to a fresh instance to allow reinitialization
# and prevent dangling references during garbage collection
libHandle = c_mtmlLibrary_t()
# Atomically update refcount
global _mtmlLib_refcount
libLoadLock.acquire()
if 0 < _mtmlLib_refcount:
_mtmlLib_refcount -= 1
libLoadLock.release()
return None
@convertStrBytes
def mtmlErrorString(result):
fn = _mtmlGetFunctionPointer("mtmlErrorString")
fn.restype = c_char_p # otherwise return is an int
ret = fn(result)
return ret
def mtmlLibraryCountDevice():
global libHandle
c_count = c_uint()
fn = _mtmlGetFunctionPointer("mtmlLibraryCountDevice")
ret = fn(libHandle, byref(c_count))
_mtmlCheckReturn(ret)
return c_count.value
def mtmlLibraryInitDeviceByIndex(index):
global libHandle
c_index = c_uint(index)
c_device = c_mtmlDevice_t()
fn = _mtmlGetFunctionPointer("mtmlLibraryInitDeviceByIndex")
ret = fn(libHandle, c_index, byref(c_device))
_mtmlCheckReturn(ret)
return c_device
@convertStrBytes
def mtmlLibraryInitDeviceByUuid(uuid):
global libHandle
c_uuid = c_char_p(uuid)
c_device = c_mtmlDevice_t()
fn = _mtmlGetFunctionPointer("mtmlLibraryInitDeviceByUuid")
ret = fn(libHandle, c_uuid, byref(c_device))
_mtmlCheckReturn(ret)
return c_device
@convertStrBytes
def mtmlLibraryInitDeviceByPciSbdf(pciSbdf):
global libHandle
c_pciSbdf = c_char_p(pciSbdf)
c_device = c_mtmlDevice_t()
fn = _mtmlGetFunctionPointer("mtmlLibraryInitDeviceByPciSbdf")
ret = fn(libHandle, c_pciSbdf, byref(c_device))
_mtmlCheckReturn(ret)
return c_device
def mtmlLibraryInitSystem():
global libHandle
c_system = c_mtmlSystem_t()
fn = _mtmlGetFunctionPointer("mtmlLibraryInitSystem")
ret = fn(libHandle, byref(c_system))
_mtmlCheckReturn(ret)
return c_system
def mtmlDeviceInitMemory(device):
global libHandle
c_memory = c_mtmlMemory_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceInitMemory")
ret = fn(device, byref(c_memory))
_mtmlCheckReturn(ret)
return c_memory
def mtmlDeviceInitGpu(device):
global libHandle
c_gpu = c_mtmlGpu_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceInitGpu")
ret = fn(device, byref(c_gpu))
_mtmlCheckReturn(ret)
return c_gpu
def mtmlDeviceInitVpu(device):
global libHandle
c_vpu = c_mtmlVpu_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceInitVpu")
ret = fn(device, byref(c_vpu))
_mtmlCheckReturn(ret)
return c_vpu
def mtmlDeviceGetIndex(device):
global libHandle
c_index = c_uint()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetIndex")
ret = fn(device, byref(c_index))
_mtmlCheckReturn(ret)
return c_index.value
@convertStrBytes
def mtmlDeviceGetName(device):
global libHandle
c_name = create_string_buffer(MTML_DEVICE_NAME_BUFFER_SIZE)
fn = _mtmlGetFunctionPointer("mtmlDeviceGetName")
ret = fn(device, c_name, c_uint(MTML_DEVICE_NAME_BUFFER_SIZE))
_mtmlCheckReturn(ret)
return c_name.value
def mtmlDeviceGetPciInfo(device):
global libHandle
c_pciinfo = c_mtmlPciInfo_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetPciInfo")
ret = fn(device, byref(c_pciinfo))
_mtmlCheckReturn(ret)
# If busId is empty or invalid (contains non-printable chars), fill it with sbdf
bus_id = c_pciinfo.busId
if not bus_id or not bus_id[0].isalnum():
c_pciinfo.busId = c_pciinfo.sbdf
return c_pciinfo
@convertStrBytes
def mtmlDeviceGetSerialNumber(device):
global libHandle
c_serial = create_string_buffer(MTML_DEVICE_SERIAL_NUMBER_BUFFER_SIZE)
fn = _mtmlGetFunctionPointer("mtmlDeviceGetSerialNumber")
ret = fn(device, c_uint(MTML_DEVICE_SERIAL_NUMBER_BUFFER_SIZE), c_serial)
_mtmlCheckReturn(ret)
return c_serial.value
def mtmlDeviceGetPowerUsage(device):
global libHandle
c_power = c_uint()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetPowerUsage")
ret = fn(device, byref(c_power))
_mtmlCheckReturn(ret)
return c_power.value
@convertStrBytes
def mtmlDeviceGetUUID(device):
c_uuid = (c_char * MTML_DEVICE_UUID_BUFFER_SIZE)()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetUUID")
ret = fn(device, byref(c_uuid), MTML_DEVICE_UUID_BUFFER_SIZE)
_mtmlCheckReturn(ret)
return c_uuid.value
def mtmlDeviceGetMtLinkSpec(device):
c_mtLinkSpec = c_mtmlMtLinkSpec_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetMtLinkSpec")
ret = fn(device, byref(c_mtLinkSpec))
_mtmlCheckReturn(ret)
return c_mtLinkSpec
def mtmlDeviceGetMtLinkState(device, linkIndex):
c_mtLinkState = _mtmlMtLinkState_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetMtLinkState")
ret = fn(device, linkIndex, byref(c_mtLinkState))
_mtmlCheckReturn(ret)
return c_mtLinkState.value
def mtmlDeviceGetMtLinkRemoteDevice(device, linkIndex):
c_device = c_mtmlDevice_t()
fn = _mtmlGetFunctionPointer("mtmlDeviceGetMtLinkRemoteDevice")
ret = fn(device, linkIndex, byref(c_device))
_mtmlCheckReturn(ret)
return c_device
def mtmlMemoryGetTotal(memory):
global libHandle
c_total = c_uint64()
fn = _mtmlGetFunctionPointer("mtmlMemoryGetTotal")
ret = fn(memory, byref(c_total))
_mtmlCheckReturn(ret)
return c_total.value
def mtmlMemoryGetUsed(memory):
global libHandle
c_used = c_uint64()
fn = _mtmlGetFunctionPointer("mtmlMemoryGetUsed")
ret = fn(memory, byref(c_used))
_mtmlCheckReturn(ret)
return c_used.value
def mtmlMemoryGetClock(memory):
global libHandle
c_clock = c_uint()
fn = _mtmlGetFunctionPointer("mtmlMemoryGetClock")
ret = fn(memory, byref(c_clock))
_mtmlCheckReturn(ret)
return c_clock.value
def mtmlMemoryGetMaxClock(memory):
global libHandle
c_clock = c_uint()
fn = _mtmlGetFunctionPointer("mtmlMemoryGetMaxClock")
ret = fn(memory, byref(c_clock))
_mtmlCheckReturn(ret)
return c_clock.value
def mtmlMemoryGetUtilization(memory):
global libHandle
utilization = c_uint()
fn = _mtmlGetFunctionPointer("mtmlMemoryGetUtilization")
ret = fn(memory, byref(utilization))
_mtmlCheckReturn(ret)
return utilization.value
def mtmlGpuGetUtilization(gpu):
global libHandle
utilization = c_uint()
fn = _mtmlGetFunctionPointer("mtmlGpuGetUtilization")
ret = fn(gpu, byref(utilization))
_mtmlCheckReturn(ret)
return utilization.value
def mtmlGpuGetClock(gpu):
global libHandle
c_clock = c_uint()
fn = _mtmlGetFunctionPointer("mtmlGpuGetClock")
ret = fn(gpu, byref(c_clock))
_mtmlCheckReturn(ret)
return c_clock.value
def mtmlGpuGetMaxClock(gpu):
global libHandle
c_clock = c_uint()
fn = _mtmlGetFunctionPointer("mtmlGpuGetMaxClock")
ret = fn(gpu, byref(c_clock))
_mtmlCheckReturn(ret)
return c_clock.value
def mtmlGpuGetTemperature(gpu):
global libHandle
c_temp = c_uint()
fn = _mtmlGetFunctionPointer("mtmlGpuGetTemperature")
ret = fn(gpu, byref(c_temp))
_mtmlCheckReturn(ret)
return c_temp.value
def mtmlVpuGetClock(vpu):
global libHandle
c_clock = c_uint()
fn = _mtmlGetFunctionPointer("mtmlVpuGetClock")
ret = fn(vpu, byref(c_clock))
_mtmlCheckReturn(ret)
return c_clock.value
def mtmlVpuGetMaxClock(vpu):
global libHandle
c_clock = c_uint()
fn = _mtmlGetFunctionPointer("mtmlVpuGetMaxClock")
ret = fn(vpu, byref(c_clock))
_mtmlCheckReturn(ret)
return c_clock.value
@convertStrBytes
def mtmlSystemGetDriverVersion(system):
c_version = create_string_buffer(MTML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE)
fn = _mtmlGetFunctionPointer("mtmlSystemGetDriverVersion")
ret = fn(system, c_version, c_uint(MTML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE))
_mtmlCheckReturn(ret)
return c_version.value
@convertStrBytes
def mtmlLibraryGetVersion():
global libHandle
c_version = create_string_buffer(MTML_LIBRARY_VERSION_BUFFER_SIZE)
fn = _mtmlGetFunctionPointer("mtmlLibraryGetVersion")
ret = fn(libHandle, c_version, c_uint(MTML_LIBRARY_VERSION_BUFFER_SIZE))
_mtmlCheckReturn(ret)
return c_version.value
def mtmlLibraryFreeSystem(system):
fn = _mtmlGetFunctionPointer("mtmlLibraryFreeSystem")
ret = fn(system)
_mtmlCheckReturn(ret)
return None
def mtmlLibraryFreeDevice(device):
fn = _mtmlGetFunctionPointer("mtmlLibraryFreeDevice")
ret = fn(device)