Qball's Weblog
ESP32-P4 base immich photo frame

Motivation
I’ve recently bought a photo frame for my dad. After looking around, most I found are now are based on frameo. Effectively you buy an android tablet with an terribly outdated OS, that they expect you to connect to the internet so you can interact with it. If you don’t connect it to the network, it still works but complaints about it constantly and looses it clock.
Not to help things, the first one I got was defective, and after an hour of working fine started rebooting. Loosing it clock and some state every time. Getting it returned was a pain and only when I was making it more costly for them they followed the normal (easy) process.
First solution - Microsoft Surface Pro 2
I had an old Microsoft Surface Pro 2 lying around unused. It is a small tablet PC with a good quality screen. Put Debian Trixie on it, immich and immich-kiosk. This solution worked really well, it automatically wakes itself up at 8 in the morning and goes to sleep at 10 in the evening. There was one downside, the lead of the original power supply was damaged and the replacement cord to use a USB-C supply I got did not make good contact. This caused the tablet to constantly run out of power every time it was knocked loose and not put back exactly in the correct position. It also ran pretty warm, all in all not ideal when used by people in a care home.
Unhappy solution
For my dad the final solution was a replacement frameo again. This one at least
is a finished product. It is not without issues: sometimes it only showed
the top 32 lines of an image while the same image displayed fine other times,
it keeps complaining about WiFi, paywalled features, it loosing it clock and
very short power lead. But it is sufficient for now.
The itch, can I do better
The whole process frustrated me a bit, why not something that does not need an ‘app’, internet connection, paywalled features, etc. In the past picture frames just worked from sdcard, but had bad TN screens. Now they have good screens, but bad software. So I looked through my box of ‘hardware to play with’ to see if I could make something myself. A while back I bought a Guition ESP32-P4-M3 devkit. Displayed below (image from aliexpress product page):

I wanted to play with the P4 for a while, but did not have a nice project, so this seems to be the ideal opportunity. So I got a little screen (well 2, first one did not work). Ended up buying a raspberry pi 7” display touch 2 screen and printing this case.
Thanks to the this project as starting point I got the basics up and running quickly.
Next was to figure out the following items:
- IMMICH api
- Remove LVGL as it was giving a lot of performance issues.
- Use the hardware JPEG decoder
- Use the Pixel Processing Accelerator (PPA) for scaling, rotating, filling and blending.
While working on it, I found out that some images served by immich where not baseline but extended sequential. This is not supported by the hardware decoder, nor the default (tJPGd) decoder, or JPEG_DEC. After looking around, it seems libjpeg-turbo was the best solution. So that added the following task:
- Get libjpeg-turbo to work
Main architecture
There are 3 tasks running:
- immich-fetch (used to be 2 tasks):
- If asset list empty: Fetches list of assets in the album. Then pushes this into the queue.
- else: Get empty image buffer and asset ID. Download the asset and places them in the image buffer. Push this image buffer to decoder queue.
- immich-decode:
- Get empty framebuffer and get image from decoder queue.
- Decode the image.
- Hardware decoder first.
- Software decoder fallback
- Push decoded buffer to display queue.
- Return empty image buffer back to fetch queue
- immich-draw:
- Get decoded buffer from display queue
- Fill, rotate, scale the decoded image onto the foreground framebuffer.
- Blend foreground framebuffer in background framebuffer while displaying it
- set foreground framebuffer as background framebuffer
- return empty decoded buffer back to fetch queue
- Wait update interval
These tasks are mapped to different cores.
This makes sure there is always a frame ready to be displayed after the interval expired. The FIFOs are setup so we can pre-fetch up 4 assets, and have 1 decoded images ready for display (intended was 2, but see below).
Fetch
Using cJSON as parser and esp_http_client (I do wonder how future proof the setup is because I fetch over https and the embedded certificate store does not auto update?) I fetch the album info, that includes a list of assets in the album. I parse these assets out and pushes them into a FIFO queue. I then process the queue until its empty and then refetch the album again. This way I pick up new photos after one rotation.
For large albums the returned json can be very big, I have not tested yet what the limit is I can handle,but given the large amount of ram available I don’t expect to hit it any time soon.
In the future this code needs to be updated to see if we can do ‘checks’ in between to see if the album been updated and then re-fetch it. My idea now is to fetch it without assets, compare the ‘updatedAt’ field and refetch if needed. A second thing is to randomize the order of the images.
For fetching the image I use the asset thumbnail endpoint. You can request 3 different sizes (regrettable not a specific size), ‘thumbnail, ‘preview’ and ‘original’. The original images are to big in my setup, some of them are 11mbyte jpeg. The thumbnail is to small and was in non-jpeg format. The preview one is larger then I needed, but not crazy big. So perfect for my use. From what I’ve seen the jpegs are around 200kbyte to 1mbyte.
It would be great if immich could have an API endpoint where I could give the max width/height and it gives me an image that will fit. Offloading some of the work to the bigger server.
Hardware JPEG decoder
The hardware JPEG decoder is pretty quick, and would have been perfect if it supported more then ‘baseline’ jpeg. I cannot completely blame it, as most software solutions don’t (esp_jpeg and esp_new_jpeg component from espressif also don’t).
To use the hardware decoder you need to include driver/jpeg_decode.h,
instantiate the decoder with: jpeg_new_decoder_engine. You can use the helper
function jpeg_decoder_get_info method to get the size of the image (This is
done in software). If this method fails, (gives an empty size back) the
hardware decoder won’t be able to decode it. jpeg_decoder_process is the main
method to offload decoding to hardware. Important to note is, if the input data
is invalid (get_info does not validate this) the decoder will throw a
timeout, even before the timeout expired.
Some example code:
/** Configuration of the output format. */
jpeg_decode_cfg_t decode_cfg_rgb = {
.output_format = JPEG_DECODE_OUT_FORMAT_RGB565,
.rgb_order = JPEG_DEC_RGB_ELEMENT_ORDER_BGR,
};
/** Setup the allocators. */
size_t tx_buffer_size;
size_t rx_buffer_size;
jpeg_decode_memory_alloc_cfg_t rx_mem_cfg = {
.buffer_direction = JPEG_DEC_ALLOC_OUTPUT_BUFFER,
};
jpeg_decode_memory_alloc_cfg_t tx_mem_cfg = {
.buffer_direction = JPEG_DEC_ALLOC_INPUT_BUFFER,
};
uint8_t *bit_stream = (uint8_t*)jpeg_alloc_decoder_mem(jpeg_size, &tx_mem_cfg, &tx_buffer_size);
jpeg_decode_picture_info_t header_info;
ESP_ERROR_CHECK(jpeg_decoder_get_info(bit_stream, bit_stream_size, &header_info));
uint8_t *out_buf = (uint8_t*)jpeg_alloc_decoder_mem(header_info.width*header_info.height * sizeof(uint16_t), &rx_mem_cfg, &rx_buffer_size);
uint32_t out_size = 0;
ESP_ERROR_CHECK(jpeg_decoder_process(decoder_engine, &decode_cfg_rgb, bit_stream, bit_stream_size, out_buf, &out_size));
If the hardware encoder fails, I now falls back to libjpeg-turbo.
Documentation for hardware encoder/decoder
libjpeg-turbo
I’ve had a hard time to get libjpeg-turbo component to work. After playing
around a bit I found that it will not work as a ‘managed-component’. It will
fetch the component fine, but fails to build it correctly. Moving the fetched
component from the managed-component directory to component directory, then
it compiles well. To get it to run, you need to use the jpeglib.h API and not
the higher level turbojpeg.h.
At the moment I use it very limited, libjpeg-turbo can do a lot of extra parts that would be useful (scaling, rotate). For now I made it a functional drop in for the hardware encoder. If I intend to switch to use an SDCard as photo storage, I probably use libjpeg-turbo and have it downscale directly. This should allow me to parse very large images, without running out of memory.
The steps are: jpeg_read_header to obtain the size of the jpeg, then allocate
an output buffer. Start the decompressor: jpeg_start_decompress and parse
each line: jpeg_read_scanlines and end with jpeg_finish_decompress and
jpeg_destroy_compress.
A 1440p image takes around ~1 second to decode, this is around 10x slower then the hardware decoder. But still more then fast enough for this use.
Pixel Processing Accelerator
So one of the problems I still had to resolve was to scale and rotate the image. The screen is on it side, so I have to scale, center the image and then rotate it 270 degrees. This is an action that the PPA can do in one step using the ‘SRM’ operation.
There are some limitations, the scale happens in 1/16th steps. In practice this works out good enough. Landscape images work out well, portrait have a small bar at top and bottom.
ppa_srm_oper_config_t srm_config = {
.in.buffer = f.buffer,
.in.pic_w = f.width,
.in.pic_h = f.height,
.in.block_w = f.width,
.in.block_h = f.height,
.in.block_offset_x = 0,
.in.block_offset_y = 0,
.in.srm_cm = PPA_SRM_COLOR_MODE_RGB565,
.out.buffer = buf_fg,
.out.buffer_size = 1280 * 720 * 2,
.out.pic_w = 720,
.out.pic_h = 1280,
.out.block_offset_x = offset_y,
.out.block_offset_y = offset_x,
.out.srm_cm = PPA_SRM_COLOR_MODE_RGB565,
.rotation_angle = PPA_SRM_ROTATION_ANGLE_270,
.scale_x = scale,
.scale_y = scale,
.rgb_swap = 0,
.byte_swap = 0,
.mode = PPA_TRANS_MODE_BLOCKING,
};
This will in one operation, scale, rotate and center the image.
The PPA also has a FILL operation and a BLEND.
In the first step we walk over the edge pixels of the image and find the average color. Then I use this color as background color. This color is passed to the PPA that then very quickly fills the whole framebuffer. Regrettable the fill operation cannot do gradients, that would have been a nice addition.
In comparison to fill, the blend operation is pretty versatile, as it can work with alpha channels or do color keying. I have not tried every option yet, I was happy enough getting it to work. It at the moment is fast enough that in a loop I can fade in 16 steps between the old image and the new one.
I like the addition of the PPA, I think when integrated in f.e. LVGL it should be able to provide a good speedup. I tried doing the image display, transition in LVGL. It was a lot easier, but it was so slow it caused tons of drawing artifacts, it looked very unprofessional.
Documentation for Pixel Processing Accelerator
Below a gif of how the transition now looks like, the camera auto exposure/whitebalance makes it look a bit less nice:

TODO
Like with any project, there is still a big todo left:
- Figure out why it is not stable and gives a ‘access prohibited’ error when using 2 framebuffers. Checking makes it clear we are not running out of memory.
- Don’t hardcode everything (wifi,immich url, auth token, album id, etc.)
- Randomize the images shown.
- Instead of a one color background, do a blurring effect like immich kiosk.
- Allow the touch to do some form of navigation/reload. At the moment it only does dimming.
Interesting problems
The following problems took me more time then it should. I think these in total took more time then the rest of the project combined.
- An Espressif module provided does not mean it works. libjpeg-turbo is still a mystery for me. It works, if you copy it in your repo. If you use it as managed component, it does not work. This took me way to long to get resolved.
- libjpeg-turbo (
jpeglib.h) is very very badly documented. I had to basically search github with function names to find example use. - libjpeg-turbo expects it output buffer to be 4byte aligned, the hardware decoder 2byte aligned.
- The SPIRAM on the ESP32-P4 is a bottleneck. I had to tweak what ran when and where to avoid the DSI driver to run out of memory bandwidth and causing artifacts.
- Having 2 decoded frames in memory caused a weird ‘access prohibited’ error on libjpeg-turbo writing 2 pixels aligned to memory. Is this a memory overflow I’ve missed? I have 32mbyte or PSRAM, I doubt I am running out.