Why does FrameBuffer not accept bytes objects?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
LuckyResistor
Posts: 2
Joined: Mon Apr 19, 2021 11:22 am

Why does FrameBuffer not accept bytes objects?

Post by LuckyResistor » Mon Apr 19, 2021 11:48 am

I am working on a simple font engine for a Raspberry Pi Pico using MicroPython. The display driver I use is based on framebuf. So, I was searching for the best way to transfer bitmaps from flash memory into the frame buffer of the display. Ideally avoiding any unnecessary memory allocations.

I hope I got this right, but if I create a bytes object in a precompiled pym file, data from this object is read directly from flash and not allocated in RAM.

So in file fontengine.py:

Code: Select all

_font_data = b'\xff\x00..........'
Reading from this data block should be very efficient?

In order to transfer e.g. a single letter into the target frame buffer, I tried to wrap this memory segment in a FrameBuffer:

Code: Select all

fba = framebuf.FrameBuffer(_font_data, 8, 8, framebuf.MONO_VLSB)
This does not work, but raises the exception: "TypeError: object with buffer protocol required". I have to wrap the bytes object into a bytearray, which is, as far as I understand, very inefficient because it will create a copy of the data on the heap.

Code: Select all

fba = framebuf.FrameBuffer(bytearray(_font_data), 8, 8, framebuf.MONO_VLSB)
This created several questions where I did not find any answers for:
- Is this actually the most efficient way to render letters using the built-in framebuf module?
- Shouldn't bytes implement the buffer protocol?
- Is this an implementation problem of the framebuf module?

I think, reimplementing the bit mapping functions to transfer the pixels into the target frame buffer seems not the right way to go, because I only recreate slower versions of already existing functions.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Why does FrameBuffer not accept bytes objects?

Post by pythoncoder » Mon Apr 19, 2021 3:46 pm

I suggest you look at font-to-py. This solves the problem, enabling fonts to be accessed from flash with tiny RAM usage. The Writer and CWriter classes enable these to be rendered to any display whose driver is subclassed from FrameBuffer.

Key features are the use of a memoryview for allocation-free slicing and the use of frozen bytecode to place the font files in flash.
Peter Hinch
Index to my micropython libraries.

LuckyResistor
Posts: 2
Joined: Mon Apr 19, 2021 11:22 am

Re: Why does FrameBuffer not accept bytes objects?

Post by LuckyResistor » Wed Apr 21, 2021 12:38 pm

I will check this out, looks like a good font engine implementation. :D
Thank you very much!

Post Reply