Page 1 of 1

why does the frambuf cannot use a memoryview as buf?

Posted: Sun Mar 13, 2022 1:37 pm
by NikS
Hi,
the background of this question is that i believe the following code does allocate a new bytearray for every char it draws.

Code: Select all

       
       for i in range(len(text)):
          glyph, H, W = self.font.get_ch(text[i])
          cb = framebuf.FrameBuffer( bytearray(glyph[0:len(glyph)]) , W, H, framebuf.MONO_HLSB)
          self.fb.blit(cb, o, 0)
          o=o+W
if i change the code to:

Code: Select all

       
       for i in range(len(text)):
          glyph, H, W = self.font.get_ch(text[i])
          cb = framebuf.FrameBuffer( glyph[0:len(glyph)] , W, H, framebuf.MONO_HLSB)
          self.fb.blit(cb, o, 0)
          o=o+W
it fails with: TypeError: object with buffer protocol required

Re: why does the frambuf cannot use a memoryview as buf?

Posted: Sun Mar 13, 2022 5:49 pm
by pythoncoder
You might like to study this code.

Re: why does the frambuf cannot use a memoryview as buf?

Posted: Sun Mar 13, 2022 7:33 pm
by NikS
Hi Peter,

thank you very much. Being able to read is a clear advantage :-)
though it's not really faster, it consumes less memory.

Nik

Code: Select all

# memoryview - test

from utime import sleep_ms, ticks_ms, ticks_us, ticks_diff
from uctypes import bytearray_at, addressof

def test():
  random_byte_array = bytearray('ABCDE1234567890', 'utf-8')
  mv = memoryview(random_byte_array)
  
  start = ticks_us()
  for i in range(70,80):
    mv[1]=i
 
    a = bytearray_at(addressof(mv), len(mv)) # create bytearray from memory view without copy
    #a=bytearray(mv[0:len(mv)]) # this copies

    #print(bytearray(mv[0:10]), a)
    #print (" show in ", stop, "us  mem:",  gc.mem_free())
  stop=ticks_us()-start
  print (" show in ", stop, "us  mem:",  gc.mem_free())

gc.collect()
gc.mem_free()
test()

Re: why does the frambuf cannot use a memoryview as buf?

Posted: Mon Mar 14, 2022 11:37 am
by pythoncoder
it consumes less memory
That is the point. The Python fonts are designed to reside in Flash. Using a memoryview enables a glyph to be accessed with minimal RAM use.

The fonts will work when loaded normally, but freezing them in Flash results in major RAM savings.

Re: why does the frambuf cannot use a memoryview as buf?

Posted: Mon Mar 14, 2022 11:48 pm
by c22
I stumbled upon the same buffer protocol problem, albeit aiming to a different target: viewtopic.php?f=15&t=9211

There's currently no proper solution, I had to make a compromise on RAM usage to achive an acceptable result. Maybe my topic contains something useful to you.