|
| 1 | +# SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 | +# Copyright (C) 2022, Tomi Valkeinen <tomi.valkeinen@ideasonboard.com> |
| 3 | + |
| 4 | +from ._libcamera import * |
| 5 | + |
| 6 | + |
| 7 | +class MappedFrameBuffer: |
| 8 | + def __init__(self, fb): |
| 9 | + self.__fb = fb |
| 10 | + |
| 11 | + def __enter__(self): |
| 12 | + import os |
| 13 | + import mmap |
| 14 | + |
| 15 | + fb = self.__fb |
| 16 | + |
| 17 | + # Collect information about the buffers |
| 18 | + |
| 19 | + bufinfos = {} |
| 20 | + |
| 21 | + for i in range(fb.num_planes): |
| 22 | + fd = fb.fd(i) |
| 23 | + |
| 24 | + if fd not in bufinfos: |
| 25 | + buflen = os.lseek(fd, 0, os.SEEK_END) |
| 26 | + bufinfos[fd] = {'maplen': 0, 'buflen': buflen} |
| 27 | + else: |
| 28 | + buflen = bufinfos[fd]['buflen'] |
| 29 | + |
| 30 | + if fb.offset(i) > buflen or fb.offset(i) + fb.length(i) > buflen: |
| 31 | + raise RuntimeError(f'plane is out of buffer: buffer length={buflen}, ' + |
| 32 | + f'plane offset={fb.offset(i)}, plane length={fb.length(i)}') |
| 33 | + |
| 34 | + bufinfos[fd]['maplen'] = max(bufinfos[fd]['maplen'], fb.offset(i) + fb.length(i)) |
| 35 | + |
| 36 | + # mmap the buffers |
| 37 | + |
| 38 | + maps = [] |
| 39 | + |
| 40 | + for fd, info in bufinfos.items(): |
| 41 | + map = mmap.mmap(fd, info['maplen'], mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE) |
| 42 | + info['map'] = map |
| 43 | + maps.append(map) |
| 44 | + |
| 45 | + self.__maps = tuple(maps) |
| 46 | + |
| 47 | + # Create memoryviews for the planes |
| 48 | + |
| 49 | + planes = [] |
| 50 | + |
| 51 | + for i in range(fb.num_planes): |
| 52 | + fd = fb.fd(i) |
| 53 | + info = bufinfos[fd] |
| 54 | + |
| 55 | + mv = memoryview(info['map']) |
| 56 | + |
| 57 | + start = fb.offset(i) |
| 58 | + end = fb.offset(i) + fb.length(i) |
| 59 | + |
| 60 | + mv = mv[start:end] |
| 61 | + |
| 62 | + planes.append(mv) |
| 63 | + |
| 64 | + self.__planes = tuple(planes) |
| 65 | + |
| 66 | + return self |
| 67 | + |
| 68 | + def __exit__(self, exc_type, exc_value, exc_traceback): |
| 69 | + for p in self.__planes: |
| 70 | + p.release() |
| 71 | + |
| 72 | + for mm in self.__maps: |
| 73 | + mm.close() |
| 74 | + |
| 75 | + @property |
| 76 | + def planes(self): |
| 77 | + return self.__planes |
| 78 | + |
| 79 | + |
| 80 | +def __FrameBuffer__mmap(self): |
| 81 | + return MappedFrameBuffer(self) |
| 82 | + |
| 83 | + |
| 84 | +FrameBuffer.mmap = __FrameBuffer__mmap |
0 commit comments