drm.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """The panel through the s1d13700-tca DRM driver: one dumb buffer, with each
  2. change reported as a dirty rectangle.
  3. libdrm through ctypes, limited to calls that libdrm 2.4.97 (Debian buster)
  4. already has; the dumb buffer is made with plain ioctls.
  5. """
  6. import ctypes
  7. import ctypes.util
  8. import fcntl
  9. import mmap
  10. import os
  11. import struct
  12. DRIVER_NAME = "s1d13700-tca"
  13. FORMAT_XRGB8888 = 0x34325258 # "XR24"
  14. class DrmError(Exception):
  15. pass
  16. class _Version(ctypes.Structure):
  17. _fields_ = [("version_major", ctypes.c_int), ("version_minor", ctypes.c_int),
  18. ("version_patchlevel", ctypes.c_int),
  19. ("name_len", ctypes.c_int), ("name", ctypes.c_char_p),
  20. ("date_len", ctypes.c_int), ("date", ctypes.c_char_p),
  21. ("desc_len", ctypes.c_int), ("desc", ctypes.c_char_p)]
  22. class _Res(ctypes.Structure):
  23. _fields_ = [("count_fbs", ctypes.c_int), ("fbs", ctypes.POINTER(ctypes.c_uint32)),
  24. ("count_crtcs", ctypes.c_int), ("crtcs", ctypes.POINTER(ctypes.c_uint32)),
  25. ("count_connectors", ctypes.c_int),
  26. ("connectors", ctypes.POINTER(ctypes.c_uint32)),
  27. ("count_encoders", ctypes.c_int),
  28. ("encoders", ctypes.POINTER(ctypes.c_uint32)),
  29. ("min_width", ctypes.c_uint32), ("max_width", ctypes.c_uint32),
  30. ("min_height", ctypes.c_uint32), ("max_height", ctypes.c_uint32)]
  31. class ModeInfo(ctypes.Structure):
  32. _fields_ = [("clock", ctypes.c_uint32)] + [
  33. (n, ctypes.c_uint16) for n in (
  34. "hdisplay", "hsync_start", "hsync_end", "htotal", "hskew",
  35. "vdisplay", "vsync_start", "vsync_end", "vtotal", "vscan")] + [
  36. ("vrefresh", ctypes.c_uint32), ("flags", ctypes.c_uint32),
  37. ("type", ctypes.c_uint32), ("name", ctypes.c_char * 32)]
  38. class _Connector(ctypes.Structure):
  39. _fields_ = [("connector_id", ctypes.c_uint32), ("encoder_id", ctypes.c_uint32),
  40. ("connector_type", ctypes.c_uint32), ("connector_type_id", ctypes.c_uint32),
  41. ("connection", ctypes.c_int),
  42. ("mmWidth", ctypes.c_uint32), ("mmHeight", ctypes.c_uint32),
  43. ("subpixel", ctypes.c_int),
  44. ("count_modes", ctypes.c_int), ("modes", ctypes.POINTER(ModeInfo))]
  45. # the rest (props, encoders) is not used
  46. class _Clip(ctypes.Structure):
  47. _fields_ = [("x1", ctypes.c_uint16), ("y1", ctypes.c_uint16),
  48. ("x2", ctypes.c_uint16), ("y2", ctypes.c_uint16)]
  49. def _iowr(nr, size):
  50. return (3 << 30) | (size << 16) | (ord("d") << 8) | nr
  51. _CREATE_DUMB = struct.Struct("=IIIIIIQ") # height width bpp flags handle pitch size
  52. _MAP_DUMB = struct.Struct("=IIQ") # handle pad offset
  53. DRM_IOCTL_MODE_CREATE_DUMB = _iowr(0xB2, _CREATE_DUMB.size)
  54. DRM_IOCTL_MODE_MAP_DUMB = _iowr(0xB3, _MAP_DUMB.size)
  55. def _load_libdrm():
  56. name = ctypes.util.find_library("drm") or "libdrm.so.2"
  57. lib = ctypes.CDLL(name, use_errno=True)
  58. vp, ci, u32 = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint32
  59. lib.drmGetVersion.restype = ctypes.POINTER(_Version)
  60. lib.drmGetVersion.argtypes = [ci]
  61. lib.drmFreeVersion.argtypes = [vp]
  62. lib.drmModeGetResources.restype = ctypes.POINTER(_Res)
  63. lib.drmModeGetResources.argtypes = [ci]
  64. lib.drmModeFreeResources.argtypes = [vp]
  65. lib.drmModeGetConnector.restype = ctypes.POINTER(_Connector)
  66. lib.drmModeGetConnector.argtypes = [ci, u32]
  67. lib.drmModeFreeConnector.argtypes = [vp]
  68. lib.drmModeAddFB2.restype = ci
  69. lib.drmModeAddFB2.argtypes = [ci, u32, u32, u32, ctypes.POINTER(u32 * 4),
  70. ctypes.POINTER(u32 * 4), ctypes.POINTER(u32 * 4),
  71. ctypes.POINTER(u32), u32]
  72. lib.drmModeSetCrtc.restype = ci
  73. lib.drmModeSetCrtc.argtypes = [ci, u32, u32, u32, u32, ctypes.POINTER(u32), ci,
  74. ctypes.POINTER(ModeInfo)]
  75. lib.drmModeDirtyFB.restype = ci
  76. lib.drmModeDirtyFB.argtypes = [ci, u32, ctypes.POINTER(_Clip), u32]
  77. return lib
  78. def _errno_error(what):
  79. e = ctypes.get_errno()
  80. return DrmError("%s: %s" % (what, os.strerror(e) if e else "failed"))
  81. class DrmPanel(object):
  82. def __init__(self):
  83. self.lib = _load_libdrm()
  84. self.fd = self._open_panel()
  85. try:
  86. self._setup()
  87. except Exception:
  88. os.close(self.fd)
  89. raise
  90. def _open_panel(self):
  91. """Only ever our own device: never take over the machine's real display"""
  92. for i in range(16):
  93. try:
  94. fd = os.open("/dev/dri/card%d" % i, os.O_RDWR | os.O_CLOEXEC)
  95. except OSError:
  96. continue
  97. v = self.lib.drmGetVersion(fd)
  98. match = bool(v) and v.contents.name == DRIVER_NAME.encode()
  99. if v:
  100. self.lib.drmFreeVersion(v)
  101. if match:
  102. self.card = i
  103. return fd
  104. os.close(fd)
  105. raise DrmError("no %s DRM device found" % DRIVER_NAME)
  106. def _setup(self):
  107. lib, fd = self.lib, self.fd
  108. res = lib.drmModeGetResources(fd)
  109. if not res:
  110. raise _errno_error("no mode resources")
  111. try:
  112. r = res.contents
  113. if r.count_connectors < 1 or r.count_crtcs < 1:
  114. raise DrmError("no connector or CRTC")
  115. crtc = r.crtcs[0]
  116. conn = lib.drmModeGetConnector(fd, r.connectors[0])
  117. finally:
  118. lib.drmModeFreeResources(res)
  119. if not conn:
  120. raise _errno_error("no connector")
  121. try:
  122. c = conn.contents
  123. if c.count_modes < 1:
  124. raise DrmError("the connector has no mode")
  125. self.mode = ModeInfo.from_buffer_copy(c.modes[0])
  126. conn_id = ctypes.c_uint32(c.connector_id)
  127. finally:
  128. lib.drmModeFreeConnector(conn)
  129. self.width, self.height = self.mode.hdisplay, self.mode.vdisplay
  130. req = bytearray(_CREATE_DUMB.pack(self.height, self.width, 32, 0, 0, 0, 0))
  131. fcntl.ioctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, req, True)
  132. _, _, _, _, handle, self.pitch, size = _CREATE_DUMB.unpack(bytes(req))
  133. u32x4 = ctypes.c_uint32 * 4
  134. fb_id = ctypes.c_uint32()
  135. if lib.drmModeAddFB2(fd, self.width, self.height, FORMAT_XRGB8888,
  136. ctypes.byref(u32x4(handle)), ctypes.byref(u32x4(self.pitch)),
  137. ctypes.byref(u32x4(0)), ctypes.byref(fb_id), 0):
  138. raise _errno_error("ADDFB2")
  139. self.fb_id = fb_id.value
  140. req = bytearray(_MAP_DUMB.pack(handle, 0, 0))
  141. fcntl.ioctl(fd, DRM_IOCTL_MODE_MAP_DUMB, req, True)
  142. offset = _MAP_DUMB.unpack(bytes(req))[2]
  143. self.map = mmap.mmap(fd, size, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE,
  144. offset=offset)
  145. self.map[:] = b"\xff" * size
  146. if lib.drmModeSetCrtc(fd, crtc, self.fb_id, 0, 0, ctypes.byref(conn_id), 1,
  147. ctypes.byref(self.mode)):
  148. raise _errno_error("SETCRTC")
  149. def i2c_bus(self):
  150. """Number of the I2C bus the panel is on, from sysfs, or None"""
  151. try:
  152. dev = os.path.realpath("/sys/class/drm/card%d/device" % self.card)
  153. return int(os.path.basename(dev).split("-", 1)[0])
  154. except (OSError, ValueError):
  155. return None
  156. def bpp(self):
  157. """The driver's bits per pixel (its module parameter); 2 if unreadable"""
  158. try:
  159. with open("/sys/module/%s/parameters/bpp" % DRIVER_NAME.replace("-", "_")) as f:
  160. return int(f.read())
  161. except (OSError, ValueError):
  162. return 2
  163. def present(self, data, stride, x, y, w, h):
  164. for row in range(y, y + h):
  165. src = row * stride + x * 4
  166. dst = row * self.pitch + x * 4
  167. self.map[dst:dst + w * 4] = data[src:src + w * 4]
  168. clip = _Clip(x, y, x + w, y + h)
  169. if self.lib.drmModeDirtyFB(self.fd, self.fb_id, ctypes.byref(clip), 1):
  170. raise _errno_error("DIRTYFB")