You've already forked crosspoint-reader
mirror of
https://github.com/crosspoint-reader/crosspoint-reader.git
synced 2026-04-29 10:26:52 -07:00
Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56ec3dfb6d | |||
| e517945aaa | |||
| 489220832f | |||
| 3ee10b31ab | |||
| a946c83a07 | |||
| 847786e342 | |||
| c2fb8ce55d | |||
| ed05554d74 | |||
| 9a9dc044ce | |||
| 1c027ce2cd | |||
| 49f97b69ca | |||
| 14643d0225 | |||
| fecd1849b9 | |||
| 2040e088e7 | |||
| 65d23910a3 | |||
| 52995fa722 | |||
| d4f8eda154 | |||
| 33b8fa0e19 | |||
| 16c760b2d2 | |||
| 8f3df7e10e | |||
| 0165fab581 | |||
| 66b100c6ca | |||
| 41bda43899 | |||
| 82f21f3c1d | |||
| a9242fe61f | |||
| 88d0d90471 | |||
| 97c4871316 | |||
| 66811bf50b | |||
| 87287012ba | |||
| d4ae108d9b | |||
| 7240cd52a9 | |||
| 0bae3bbf64 | |||
| 2b12a65011 | |||
| 46fa186b82 | |||
| 0cc2c64df2 | |||
| 1f956e972b | |||
| 9c573e6f7f | |||
| 0edb2baced | |||
| b792b792bf | |||
| afe9672156 | |||
| 9f95b31de5 | |||
| c76507c937 | |||
| 881aa2e005 | |||
| 14972b34cb | |||
| c8f4870d7c |
@@ -1,9 +1,18 @@
|
||||
## Summary
|
||||
|
||||
* **What is the goal of this PR?** (e.g., Fixes a bug in the user authentication module, Implements the new feature for
|
||||
file uploading.)
|
||||
* **What is the goal of this PR?** (e.g., Implements the new feature for file uploading.)
|
||||
* **What changes are included?**
|
||||
|
||||
## Additional Context
|
||||
|
||||
* Add any other information that might be helpful for the reviewer (e.g., performance implications, potential risks, specific areas to focus on).
|
||||
* Add any other information that might be helpful for the reviewer (e.g., performance implications, potential risks,
|
||||
specific areas to focus on).
|
||||
|
||||
---
|
||||
|
||||
### AI Usage
|
||||
|
||||
While CrossPoint doesn't have restrictions on AI tools in contributing, please be transparent about their usage as it
|
||||
helps set the right context for reviewers.
|
||||
|
||||
Did you use AI tools to help write this code? _**< YES | PARTIALLY | NO >**_
|
||||
|
||||
@@ -7,11 +7,11 @@ name: CI
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
name: "PR Formatting"
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
- edited
|
||||
|
||||
permissions:
|
||||
statuses: write
|
||||
|
||||
jobs:
|
||||
title-check:
|
||||
name: Title Check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Check PR Title
|
||||
uses: amannn/action-semantic-pull-request@v6
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -7,17 +7,18 @@ on:
|
||||
jobs:
|
||||
build-release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cache/pip
|
||||
~/.platformio/.cache
|
||||
key: ${{ runner.os }}-pio
|
||||
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
+55
-37
@@ -1,17 +1,16 @@
|
||||
# CrossPoint User Guide
|
||||
|
||||
Welcome to the **CrossPoint** firmware. This guide outlines the hardware controls, navigation, and reading features of
|
||||
the device.
|
||||
Welcome to the **CrossPoint** firmware. This guide outlines the hardware controls, navigation, and reading features of the device.
|
||||
|
||||
## 1. Hardware Overview
|
||||
|
||||
The device utilises the standard buttons on the Xtink X4 (in the same layout as the manufacturer firmware, by default):
|
||||
|
||||
### Button Layout
|
||||
| Location | Buttons |
|
||||
|-----------------|--------------------------------------------|
|
||||
| **Bottom Edge** | **Back**, **Confirm**, **Left**, **Right** |
|
||||
| **Right Side** | **Power**, **Volume Up**, **Volume Down** |
|
||||
| Location | Buttons |
|
||||
| --------------- | ---------------------------------------------------- |
|
||||
| **Bottom Edge** | **Back**, **Confirm**, **Left**, **Right** |
|
||||
| **Right Side** | **Power**, **Volume Up**, **Volume Down**, **Reset** |
|
||||
|
||||
Button layout can be customized in **[Settings](#35-settings)**.
|
||||
|
||||
@@ -21,8 +20,10 @@ Button layout can be customized in **[Settings](#35-settings)**.
|
||||
|
||||
### Power On / Off
|
||||
|
||||
To turn the device on or off, **press and hold the Power button for half a second**. In **[Settings](#35-settings)** you can configure
|
||||
the power button to trigger on a short press instead of a long one.
|
||||
To turn the device on or off, **press and hold the Power button for approximately half a second**.
|
||||
In **[Settings](#35-settings)** you can configure the power button to turn the device off with a short press instead of a long one.
|
||||
|
||||
To reboot the device (for example if it's frozen, or after a firmware update), press and release the Reset button, and then quickly press and hold the Power button for a few seconds.
|
||||
|
||||
### First Launch
|
||||
|
||||
@@ -37,15 +38,13 @@ Upon turning the device on for the first time, you will be placed on the **[Home
|
||||
|
||||
### 3.1 Home Screen
|
||||
|
||||
The Home Screen is the main entry point to the firmware. From here you can navigate to **[Reading Mode](#4-reading-mode)** with the most recently read book, **[Book Selection](#32-book-selection)**,
|
||||
**[Settings](#35-settings)**, or the **[File Upload](#34-file-upload-screen)** screen.
|
||||
The Home Screen is the main entry point to the firmware. From here you can navigate to **[Reading Mode](#4-reading-mode)** with the most recently read book, **[Book Selection](#32-book-selection)**, **[Settings](#35-settings)**, or the **[File Upload](#34-file-upload-screen)** screen.
|
||||
|
||||
### 3.2 Book Selection
|
||||
|
||||
The Book Selection acts as a folder and file browser.
|
||||
|
||||
* **Navigate List:** Use **Left** (or **Volume Up**), or **Right** (or **Volume Down**) to move the selection cursor up
|
||||
and down through folders and books.
|
||||
* **Navigate List:** Use **Left** (or **Volume Up**), or **Right** (or **Volume Down**) to move the selection cursor up and down through folders and books. You can also long-press these buttons to scroll a full page up or down.
|
||||
* **Open Selection:** Press **Confirm** to open a folder or read a selected book.
|
||||
|
||||
### 3.3 Reading Mode
|
||||
@@ -54,42 +53,60 @@ See [Reading Mode](#4-reading-mode) below for more information.
|
||||
|
||||
### 3.4 File Upload Screen
|
||||
|
||||
The File Upload screen allows you to upload new e-books to the device. When you enter the screen, you'll be prompted with
|
||||
a WiFi selection dialog and then your X4 will start hosting a web server.
|
||||
The File Upload screen allows you to upload new e-books to the device. When you enter the screen, you'll be prompted with a WiFi selection dialog and then your X4 will start hosting a web server.
|
||||
|
||||
See the [webserver docs](./docs/webserver.md) for more information on how to connect to the web server and upload files.
|
||||
|
||||
> [!TIP]
|
||||
> Advanced users can also manage files programmatically or via the command line using `curl`. See the [webserver docs](./docs/webserver.md) for details.
|
||||
|
||||
### 3.5 Settings
|
||||
|
||||
The Settings screen allows you to configure the device's behavior. There are a few settings you can adjust:
|
||||
- **Sleep Screen**: Which sleep screen to display when the device sleeps, options are:
|
||||
- "Dark" (default) - The default dark sleep screen
|
||||
- **Sleep Screen**: Which sleep screen to display when the device sleeps:
|
||||
- "Dark" (default) - The default dark Crosspoint logo sleep screen
|
||||
- "Light" - The same default sleep screen, on a white background
|
||||
- "Custom" - Custom images from the SD card, see [Sleep Screen](#36-sleep-screen) below for more information
|
||||
- "Custom" - Custom images from the SD card; see [Sleep Screen](#36-sleep-screen) below for more information
|
||||
- "Cover" - The book cover image (Note: this is experimental and may not work as expected)
|
||||
- **Status Bar**: Configure the status bar displayed while reading, options are:
|
||||
- "None" - A blank screen
|
||||
- **Sleep Screen Cover Mode**: How to display the book cover when "Cover" sleep screen is selected:
|
||||
- "Fit" (default) - Scale the image down to fit centered on the screen, padding with white borders as necessary
|
||||
- "Crop" - Scale the image down and crop as necessary to try to to fill the screen (Note: this is experimental and may not work as expected)
|
||||
- **Status Bar**: Configure the status bar displayed while reading:
|
||||
- "None" - No status bar
|
||||
- "No Progress" - Show status bar without reading progress
|
||||
- "Full" - Show status bar with reading progress
|
||||
- **Extra Paragraph Spacing**: If enabled, vertical space will be added between paragraphs in the book, if disabled,
|
||||
paragraphs will not have vertical space between them, but will have first word indentation.
|
||||
- **Short Power Button Click**: Whether to trigger the power button on a short press or a long press.
|
||||
- **Reading Orientation**: Set the screen orientation for reading, options are:
|
||||
- **Hide Battery %**: Configure where to suppress the battery pecentage display in the status bar; the battery icon will still be shown:
|
||||
- "Never" - Always show battery percentage (default)
|
||||
- "In Reader" - Show battery percentage everywhere except in reading mode
|
||||
- "Always" - Always hide battery percentage
|
||||
- **Extra Paragraph Spacing**: If enabled, vertical space will be added between paragraphs in the book. If disabled, paragraphs will not have vertical space between them, but will have first-line indentation.
|
||||
- **Text Anti-Aliasing**: Whether to show smooth grey edges (anti-aliasing) on text in reading mode. Note this slows down page turns slightly.
|
||||
- **Short Power Button Click**: Controls the effect of a short click of the power button:
|
||||
- "Ignore" - Require a long press to turn off the device
|
||||
- "Sleep" - A short press powers the device off
|
||||
- "Page Turn" - A short press in reading mode turns to the next page; a long press turns the device off
|
||||
- **Reading Orientation**: Set the screen orientation for reading EPUB files:
|
||||
- "Portrait" (default) - Standard portrait orientation
|
||||
- "Landscape CW" - Landscape, rotated clockwise
|
||||
- "Inverted" - Portrait, upside down
|
||||
- "Landscape CCW" - Landscape, rotated counter-clockwise
|
||||
- **Front Button Layout**: Configure the order of the bottom edge buttons, options are:
|
||||
- "Bck, Cnfrm, Lft, Rght" (default) - Back, Confirm, Left, Right
|
||||
- "Lft, Rght, Bck, Cnfrm" - Left, Right, Back, Confirm
|
||||
- "Lft, Bck, Cnfrm, Rght" - Left, Back, Confirm, Right
|
||||
- **Side Button Layout**: Swap the order of the volume buttons from Previous/Next to Next/Previous. This change is only in effect when reading.
|
||||
- **Reader Font Family**: Choose the font used for reading, options are:
|
||||
- **Front Button Layout**: Configure the order of the bottom edge buttons:
|
||||
- Back, Confirm, Left, Right (default)
|
||||
- Left, Right, Back, Confirm
|
||||
- Left, Back, Confirm, Right
|
||||
- **Side Button Layout (reader)**: Swap the order of the up and down volume buttons from Previous/Next to Next/Previous. This change is only in effect when reading.
|
||||
- **Reader Font Family**: Choose the font used for reading:
|
||||
- "Bookerly" (default) - Amazon's reading font
|
||||
- "Noto Sans" - Google's sans-serif font
|
||||
- "Open Dyslexic" - Font designed for readers with dyslexia
|
||||
- **Reader Font Size**: Adjust the text size for reading, options are "Small", "Medium", "Large", or "X Large".
|
||||
- **Reader Line Spacing**: Adjust the spacing between lines, options are "Tight", "Normal", or "Wide".
|
||||
- **Reader Font Size**: Adjust the text size for reading; options are "Small", "Medium", "Large", or "X Large".
|
||||
- **Reader Line Spacing**: Adjust the spacing between lines; options are "Tight", "Normal", or "Wide".
|
||||
- **Reader Screen Margin**: Controls the screen margins in reader mode between 5 and 40 pixels in 5 pixel increments.
|
||||
- **Reader Paragraph Alignment**: Set the alignment of paragraphs; options are "Justified" (default), "Left", "Center", or "Right".
|
||||
- **Time to Sleep**: Set the duration of inactivity before the device automatically goes to sleep.
|
||||
- **Refresh Frequency**: Set how often the screen does a full refresh while reading to reduce ghosting.
|
||||
- **Calibre Settings**: Set up integration for accessing a Calibre web library or connecting to Calibre as a wireless device.
|
||||
- **Check for updates**: Check for firmware updates over WiFi.
|
||||
|
||||
### 3.6 Sleep Screen
|
||||
@@ -97,9 +114,7 @@ The Settings screen allows you to configure the device's behavior. There are a f
|
||||
You can customize the sleep screen by placing custom images in specific locations on the SD card:
|
||||
|
||||
- **Single Image:** Place a file named `sleep.bmp` in the root directory.
|
||||
- **Multiple Images:** Create a `sleep` directory in the root of the SD card and place any number of `.bmp` images
|
||||
inside. If images are found in this directory, they will take priority over the `sleep.bmp` file, and one will be
|
||||
randomly selected each time the device sleeps.
|
||||
- **Multiple Images:** Create a `sleep` directory in the root of the SD card and place any number of `.bmp` images inside. If images are found in this directory, they will take priority over the `sleep.bmp` file, and one will be randomly selected each time the device sleeps.
|
||||
|
||||
> [!NOTE]
|
||||
> You'll need to set the **Sleep Screen** setting to **Custom** in order to use these images.
|
||||
@@ -117,17 +132,21 @@ Once you have opened a book, the button layout changes to facilitate reading.
|
||||
|
||||
### Page Turning
|
||||
| Action | Buttons |
|
||||
|-------------------|--------------------------------------|
|
||||
| ----------------- | ------------------------------------ |
|
||||
| **Previous Page** | Press **Left** _or_ **Volume Up** |
|
||||
| **Next Page** | Press **Right** _or_ **Volume Down** |
|
||||
|
||||
The role of the volume (side) buttons can be swapped in **[Settings](#35-settings)**.
|
||||
|
||||
If the **Short Power Button Click** setting is set to "Page Turn", you can also turn to the next page by briefly pressing the Power button.
|
||||
|
||||
### Chapter Navigation
|
||||
* **Next Chapter:** Press and **hold** the **Right** (or **Volume Down**) button briefly, then release.
|
||||
* **Previous Chapter:** Press and **hold** the **Left** (or **Volume Up**) button briefly, then release.
|
||||
|
||||
### System Navigation
|
||||
* **Return to Book Selection:** Press **Back** to close the book and return to the **[Book Selection](#32-book-selection)** screen.
|
||||
* **Return to Home:** Press and hold **Back** to close the book and return to the **[Home](#31-home-screen)** screen.
|
||||
* **Return to Home:** Press and **hold** the **Back** button to close the book and return to the **[Home](#31-home-screen)** screen.
|
||||
* **Chapter Menu:** Press **Confirm** to open the **[Table of Contents/Chapter Selection](#5-chapter-selection-screen)**.
|
||||
|
||||
---
|
||||
@@ -144,7 +163,6 @@ Accessible by pressing **Confirm** while inside a book.
|
||||
|
||||
## 6. Current Limitations & Roadmap
|
||||
|
||||
Please note that this firmware is currently in active development. The following features are **not yet supported** but
|
||||
are planned for future updates:
|
||||
Please note that this firmware is currently in active development. The following features are **not yet supported** but are planned for future updates:
|
||||
|
||||
* **Images:** Embedded images in e-books will not render.
|
||||
|
||||
@@ -170,6 +170,40 @@ This is useful for organizing your ebooks by genre, author, or series.
|
||||
|
||||
---
|
||||
|
||||
## Command Line File Management
|
||||
|
||||
For power users, you can manage files directly from your terminal using `curl` while the device is in File Upload mode.
|
||||
|
||||
### Uploading a File
|
||||
To upload a file to the root directory, use the following command:
|
||||
```bash
|
||||
curl -F "file=@book.epub" "http://crosspoint.local/upload?path=/"
|
||||
```
|
||||
|
||||
* **`-F "file=@filename"`**: Points to the local file on your computer.
|
||||
* **`path=/`**: The destination folder on the device SD card.
|
||||
|
||||
### Deleting a File
|
||||
|
||||
To delete a specific file, provide the full path on the SD card:
|
||||
|
||||
```bash
|
||||
curl -F "path=/folder/file.epub" "http://crosspoint.local/delete"
|
||||
```
|
||||
|
||||
### Advanced Flags
|
||||
|
||||
For more reliable transfers of large EPUB files, consider adding these flags:
|
||||
|
||||
* `-#`: Shows a simple progress bar.
|
||||
* `--connect-timeout 30`: Limits how long curl waits to establish a connection (in seconds).
|
||||
* `--max-time 300`: Sets a maximum duration for the entire transfer (5 minutes).
|
||||
|
||||
> [!NOTE]
|
||||
> These examples use `crosspoint.local`. If your network does not support mDNS or the address does not resolve, replace it with the specific **IP Address** displayed on your device screen (e.g., `http://192.168.1.102/`).
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Cannot See the Device on the Network
|
||||
|
||||
+76
-6
@@ -167,7 +167,10 @@ bool Epub::parseTocNavFile() const {
|
||||
}
|
||||
const auto navSize = tempNavFile.size();
|
||||
|
||||
TocNavParser navParser(contentBasePath, navSize, bookMetadataCache.get());
|
||||
// Note: We can't use `contentBasePath` here as the nav file may be in a different folder to the content.opf
|
||||
// and the HTMLX nav file will have hrefs relative to itself
|
||||
const std::string navContentBasePath = tocNavItem.substr(0, tocNavItem.find_last_of('/') + 1);
|
||||
TocNavParser navParser(navContentBasePath, navSize, bookMetadataCache.get());
|
||||
|
||||
if (!navParser.setup()) {
|
||||
Serial.printf("[%lu] [EBP] Could not setup toc nav parser\n", millis());
|
||||
@@ -345,11 +348,14 @@ const std::string& Epub::getAuthor() const {
|
||||
return bookMetadataCache->coreMetadata.author;
|
||||
}
|
||||
|
||||
std::string Epub::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
|
||||
std::string Epub::getCoverBmpPath(bool cropped) const {
|
||||
const auto coverFileName = "cover" + cropped ? "_crop" : "";
|
||||
return cachePath + "/" + coverFileName + ".bmp";
|
||||
}
|
||||
|
||||
bool Epub::generateCoverBmp() const {
|
||||
bool Epub::generateCoverBmp(bool cropped) const {
|
||||
// Already generated, return true
|
||||
if (SdMan.exists(getCoverBmpPath().c_str())) {
|
||||
if (SdMan.exists(getCoverBmpPath(cropped).c_str())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -381,7 +387,7 @@ bool Epub::generateCoverBmp() const {
|
||||
}
|
||||
|
||||
FsFile coverBmp;
|
||||
if (!SdMan.openFileForWrite("EBP", getCoverBmpPath(), coverBmp)) {
|
||||
if (!SdMan.openFileForWrite("EBP", getCoverBmpPath(cropped), coverBmp)) {
|
||||
coverJpg.close();
|
||||
return false;
|
||||
}
|
||||
@@ -392,7 +398,7 @@ bool Epub::generateCoverBmp() const {
|
||||
|
||||
if (!success) {
|
||||
Serial.printf("[%lu] [EBP] Failed to generate BMP from JPG cover image\n", millis());
|
||||
SdMan.remove(getCoverBmpPath().c_str());
|
||||
SdMan.remove(getCoverBmpPath(cropped).c_str());
|
||||
}
|
||||
Serial.printf("[%lu] [EBP] Generated BMP from JPG cover image, success: %s\n", millis(), success ? "yes" : "no");
|
||||
return success;
|
||||
@@ -403,6 +409,70 @@ bool Epub::generateCoverBmp() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string Epub::getThumbBmpPath() const { return cachePath + "/thumb.bmp"; }
|
||||
|
||||
bool Epub::generateThumbBmp() const {
|
||||
// Already generated, return true
|
||||
if (SdMan.exists(getThumbBmpPath().c_str())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||
Serial.printf("[%lu] [EBP] Cannot generate thumb BMP, cache not loaded\n", millis());
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto coverImageHref = bookMetadataCache->coreMetadata.coverItemHref;
|
||||
if (coverImageHref.empty()) {
|
||||
Serial.printf("[%lu] [EBP] No known cover image for thumbnail\n", millis());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (coverImageHref.substr(coverImageHref.length() - 4) == ".jpg" ||
|
||||
coverImageHref.substr(coverImageHref.length() - 5) == ".jpeg") {
|
||||
Serial.printf("[%lu] [EBP] Generating thumb BMP from JPG cover image\n", millis());
|
||||
const auto coverJpgTempPath = getCachePath() + "/.cover.jpg";
|
||||
|
||||
FsFile coverJpg;
|
||||
if (!SdMan.openFileForWrite("EBP", coverJpgTempPath, coverJpg)) {
|
||||
return false;
|
||||
}
|
||||
readItemContentsToStream(coverImageHref, coverJpg, 1024);
|
||||
coverJpg.close();
|
||||
|
||||
if (!SdMan.openFileForRead("EBP", coverJpgTempPath, coverJpg)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
FsFile thumbBmp;
|
||||
if (!SdMan.openFileForWrite("EBP", getThumbBmpPath(), thumbBmp)) {
|
||||
coverJpg.close();
|
||||
return false;
|
||||
}
|
||||
// Use smaller target size for Continue Reading card (half of screen: 240x400)
|
||||
// Generate 1-bit BMP for fast home screen rendering (no gray passes needed)
|
||||
constexpr int THUMB_TARGET_WIDTH = 240;
|
||||
constexpr int THUMB_TARGET_HEIGHT = 400;
|
||||
const bool success = JpegToBmpConverter::jpegFileTo1BitBmpStreamWithSize(coverJpg, thumbBmp, THUMB_TARGET_WIDTH,
|
||||
THUMB_TARGET_HEIGHT);
|
||||
coverJpg.close();
|
||||
thumbBmp.close();
|
||||
SdMan.remove(coverJpgTempPath.c_str());
|
||||
|
||||
if (!success) {
|
||||
Serial.printf("[%lu] [EBP] Failed to generate thumb BMP from JPG cover image\n", millis());
|
||||
SdMan.remove(getThumbBmpPath().c_str());
|
||||
}
|
||||
Serial.printf("[%lu] [EBP] Generated thumb BMP from JPG cover image, success: %s\n", millis(),
|
||||
success ? "yes" : "no");
|
||||
return success;
|
||||
} else {
|
||||
Serial.printf("[%lu] [EBP] Cover image is not a JPG, skipping thumbnail\n", millis());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size, const bool trailingNullByte) const {
|
||||
if (itemHref.empty()) {
|
||||
Serial.printf("[%lu] [EBP] Failed to read item, empty href\n", millis());
|
||||
|
||||
+4
-2
@@ -44,8 +44,10 @@ class Epub {
|
||||
const std::string& getPath() const;
|
||||
const std::string& getTitle() const;
|
||||
const std::string& getAuthor() const;
|
||||
std::string getCoverBmpPath() const;
|
||||
bool generateCoverBmp() const;
|
||||
std::string getCoverBmpPath(bool cropped = false) const;
|
||||
bool generateCoverBmp(bool cropped = false) const;
|
||||
std::string getThumbBmpPath() const;
|
||||
bool generateThumbBmp() const;
|
||||
uint8_t* readItemContentsToBytes(const std::string& itemHref, size_t* size = nullptr,
|
||||
bool trailingNullByte = false) const;
|
||||
bool readItemContentsToStream(const std::string& itemHref, Print& out, size_t chunkSize) const;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
#include "FsHelpers.h"
|
||||
|
||||
namespace {
|
||||
constexpr uint8_t BOOK_CACHE_VERSION = 3;
|
||||
constexpr uint8_t BOOK_CACHE_VERSION = 4;
|
||||
constexpr char bookBinFile[] = "/book.bin";
|
||||
constexpr char tmpSpineBinFile[] = "/spine.bin.tmp";
|
||||
constexpr char tmpTocBinFile[] = "/toc.bin.tmp";
|
||||
|
||||
@@ -43,7 +43,7 @@ std::vector<uint16_t> ParsedText::calculateWordWidths(const GfxRenderer& rendere
|
||||
wordWidths.reserve(totalWordCount);
|
||||
|
||||
// add em-space at the beginning of first word in paragraph to indent
|
||||
if (!extraParagraphSpacing) {
|
||||
if ((style == TextBlock::JUSTIFIED || style == TextBlock::LEFT_ALIGN) && !extraParagraphSpacing) {
|
||||
std::string& first_word = words.front();
|
||||
first_word.insert(0, "\xe2\x80\x83");
|
||||
}
|
||||
|
||||
@@ -1,163 +0,0 @@
|
||||
// from
|
||||
// https://github.com/atomic14/diy-esp32-epub-reader/blob/2c2f57fdd7e2a788d14a0bcb26b9e845a47aac42/lib/Epub/RubbishHtmlParser/htmlEntities.cpp
|
||||
|
||||
#include "htmlEntities.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
|
||||
const int MAX_ENTITY_LENGTH = 10;
|
||||
|
||||
// Use book: entities_ww2.epub to test this (Page 7: Entities parser test)
|
||||
// Note the supported keys are only in lowercase
|
||||
// Store the mappings in a unordered hash map
|
||||
static std::unordered_map<std::string, std::string> entity_lookup(
|
||||
{{""", "\""}, {"⁄", "⁄"}, {"&", "&"}, {"<", "<"}, {">", ">"},
|
||||
{"À", "À"}, {"Á", "Á"}, {"Â", "Â"}, {"Ã", "Ã"}, {"Ä", "Ä"},
|
||||
{"Å", "Å"}, {"Æ", "Æ"}, {"Ç", "Ç"}, {"È", "È"}, {"É", "É"},
|
||||
{"Ê", "Ê"}, {"Ë", "Ë"}, {"Ì", "Ì"}, {"Í", "Í"}, {"Î", "Î"},
|
||||
{"Ï", "Ï"}, {"Ð", "Ð"}, {"Ñ", "Ñ"}, {"Ò", "Ò"}, {"Ó", "Ó"},
|
||||
{"Ô", "Ô"}, {"Õ", "Õ"}, {"Ö", "Ö"}, {"Ø", "Ø"}, {"Ù", "Ù"},
|
||||
{"Ú", "Ú"}, {"Û", "Û"}, {"Ü", "Ü"}, {"Ý", "Ý"}, {"Þ", "Þ"},
|
||||
{"ß", "ß"}, {"à", "à"}, {"á", "á"}, {"â", "â"}, {"ã", "ã"},
|
||||
{"ä", "ä"}, {"å", "å"}, {"æ", "æ"}, {"ç", "ç"}, {"è", "è"},
|
||||
{"é", "é"}, {"ê", "ê"}, {"ë", "ë"}, {"ì", "ì"}, {"í", "í"},
|
||||
{"î", "î"}, {"ï", "ï"}, {"ð", "ð"}, {"ñ", "ñ"}, {"ò", "ò"},
|
||||
{"ó", "ó"}, {"ô", "ô"}, {"õ", "õ"}, {"ö", "ö"}, {"ø", "ø"},
|
||||
{"ù", "ù"}, {"ú", "ú"}, {"û", "û"}, {"ü", "ü"}, {"ý", "ý"},
|
||||
{"þ", "þ"}, {"ÿ", "ÿ"}, {" ", " "}, {"¡", "¡"}, {"¢", "¢"},
|
||||
{"£", "£"}, {"¤", "¤"}, {"¥", "¥"}, {"¦", "¦"}, {"§", "§"},
|
||||
{"¨", "¨"}, {"©", "©"}, {"ª", "ª"}, {"«", "«"}, {"¬", "¬"},
|
||||
{"­", ""}, {"®", "®"}, {"¯", "¯"}, {"°", "°"}, {"±", "±"},
|
||||
{"²", "²"}, {"³", "³"}, {"´", "´"}, {"µ", "µ"}, {"¶", "¶"},
|
||||
{"¸", "¸"}, {"¹", "¹"}, {"º", "º"}, {"»", "»"}, {"¼", "¼"},
|
||||
{"½", "½"}, {"¾", "¾"}, {"¿", "¿"}, {"×", "×"}, {"÷", "÷"},
|
||||
{"∀", "∀"}, {"∂", "∂"}, {"∃", "∃"}, {"∅", "∅"}, {"∇", "∇"},
|
||||
{"∈", "∈"}, {"∉", "∉"}, {"∋", "∋"}, {"∏", "∏"}, {"∑", "∑"},
|
||||
{"−", "−"}, {"∗", "∗"}, {"√", "√"}, {"∝", "∝"}, {"∞", "∞"},
|
||||
{"∠", "∠"}, {"∧", "∧"}, {"∨", "∨"}, {"∩", "∩"}, {"∪", "∪"},
|
||||
{"∫", "∫"}, {"∴", "∴"}, {"∼", "∼"}, {"≅", "≅"}, {"≈", "≈"},
|
||||
{"≠", "≠"}, {"≡", "≡"}, {"≤", "≤"}, {"≥", "≥"}, {"⊂", "⊂"},
|
||||
{"⊃", "⊃"}, {"⊄", "⊄"}, {"⊆", "⊆"}, {"⊇", "⊇"}, {"⊕", "⊕"},
|
||||
{"⊗", "⊗"}, {"⊥", "⊥"}, {"⋅", "⋅"}, {"Α", "Α"}, {"Β", "Β"},
|
||||
{"Γ", "Γ"}, {"Δ", "Δ"}, {"Ε", "Ε"}, {"Ζ", "Ζ"}, {"Η", "Η"},
|
||||
{"Θ", "Θ"}, {"Ι", "Ι"}, {"Κ", "Κ"}, {"Λ", "Λ"}, {"Μ", "Μ"},
|
||||
{"Ν", "Ν"}, {"Ξ", "Ξ"}, {"Ο", "Ο"}, {"Π", "Π"}, {"Ρ", "Ρ"},
|
||||
{"Σ", "Σ"}, {"Τ", "Τ"}, {"Υ", "Υ"}, {"Φ", "Φ"}, {"Χ", "Χ"},
|
||||
{"Ψ", "Ψ"}, {"Ω", "Ω"}, {"α", "α"}, {"β", "β"}, {"γ", "γ"},
|
||||
{"δ", "δ"}, {"ε", "ε"}, {"ζ", "ζ"}, {"η", "η"}, {"θ", "θ"},
|
||||
{"ι", "ι"}, {"κ", "κ"}, {"λ", "λ"}, {"μ", "μ"}, {"ν", "ν"},
|
||||
{"ξ", "ξ"}, {"ο", "ο"}, {"π", "π"}, {"ρ", "ρ"}, {"ς", "ς"},
|
||||
{"σ", "σ"}, {"τ", "τ"}, {"υ", "υ"}, {"φ", "φ"}, {"χ", "χ"},
|
||||
{"ψ", "ψ"}, {"ω", "ω"}, {"ϑ", "ϑ"}, {"ϒ", "ϒ"}, {"ϖ", "ϖ"},
|
||||
{"Œ", "Œ"}, {"œ", "œ"}, {"Š", "Š"}, {"š", "š"}, {"Ÿ", "Ÿ"},
|
||||
{"ƒ", "ƒ"}, {"ˆ", "ˆ"}, {"˜", "˜"}, {" ", ""}, {" ", ""},
|
||||
{" ", ""}, {"‌", ""}, {"‍", ""}, {"‎", ""}, {"‏", ""},
|
||||
{"–", "–"}, {"—", "—"}, {"‘", "‘"}, {"’", "’"}, {"‚", "‚"},
|
||||
{"“", "“"}, {"”", "”"}, {"„", "„"}, {"†", "†"}, {"‡", "‡"},
|
||||
{"•", "•"}, {"…", "…"}, {"‰", "‰"}, {"′", "′"}, {"″", "″"},
|
||||
{"‹", "‹"}, {"›", "›"}, {"‾", "‾"}, {"€", "€"}, {"™", "™"},
|
||||
{"←", "←"}, {"↑", "↑"}, {"→", "→"}, {"↓", "↓"}, {"↔", "↔"},
|
||||
{"↵", "↵"}, {"⌈", "⌈"}, {"⌉", "⌉"}, {"⌊", "⌊"}, {"⌋", "⌋"},
|
||||
{"◊", "◊"}, {"♠", "♠"}, {"♣", "♣"}, {"♥", "♥"}, {"♦", "♦"}});
|
||||
|
||||
// converts from a unicode code point to the utf8 equivalent
|
||||
void convert_to_utf8(const int code, std::string& res) {
|
||||
// convert to a utf8 sequence
|
||||
if (code < 0x80) {
|
||||
res += static_cast<char>(code);
|
||||
} else if (code < 0x800) {
|
||||
res += static_cast<char>(0xc0 | (code >> 6));
|
||||
res += static_cast<char>(0x80 | (code & 0x3f));
|
||||
} else if (code < 0x10000) {
|
||||
res += static_cast<char>(0xe0 | (code >> 12));
|
||||
res += static_cast<char>(0x80 | ((code >> 6) & 0x3f));
|
||||
res += static_cast<char>(0x80 | (code & 0x3f));
|
||||
} else if (code < 0x200000) {
|
||||
res += static_cast<char>(0xf0 | (code >> 18));
|
||||
res += static_cast<char>(0x80 | ((code >> 12) & 0x3f));
|
||||
res += static_cast<char>(0x80 | ((code >> 6) & 0x3f));
|
||||
res += static_cast<char>(0x80 | (code & 0x3f));
|
||||
} else if (code < 0x4000000) {
|
||||
res += static_cast<char>(0xf8 | (code >> 24));
|
||||
res += static_cast<char>(0x80 | ((code >> 18) & 0x3f));
|
||||
res += static_cast<char>(0x80 | ((code >> 12) & 0x3f));
|
||||
res += static_cast<char>(0x80 | ((code >> 6) & 0x3f));
|
||||
res += static_cast<char>(0x80 | (code & 0x3f));
|
||||
} else if (code < 0x80000000) {
|
||||
res += static_cast<char>(0xfc | (code >> 30));
|
||||
res += static_cast<char>(0x80 | ((code >> 24) & 0x3f));
|
||||
res += static_cast<char>(0x80 | ((code >> 18) & 0x3f));
|
||||
res += static_cast<char>(0x80 | ((code >> 12) & 0x3f));
|
||||
res += static_cast<char>(0x80 | ((code >> 6) & 0x3f));
|
||||
}
|
||||
}
|
||||
|
||||
// handles numeric entities - e.g. Ӓ or ሴ
|
||||
bool process_numeric_entity(const std::string& entity, std::string& res) {
|
||||
int code = 0;
|
||||
// is it hex?
|
||||
if (entity[2] == 'x' || entity[2] == 'X') {
|
||||
// parse the hex code
|
||||
code = strtol(entity.substr(3, entity.size() - 3).c_str(), nullptr, 16);
|
||||
} else {
|
||||
code = strtol(entity.substr(2, entity.size() - 3).c_str(), nullptr, 10);
|
||||
}
|
||||
if (code != 0) {
|
||||
// special handling for nbsp
|
||||
if (code == 0xA0) {
|
||||
res += " ";
|
||||
} else {
|
||||
convert_to_utf8(code, res);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// handles named entities - e.g. &
|
||||
bool process_string_entity(const std::string& entity, std::string& res) {
|
||||
// it's a named entity - find it in the lookup table
|
||||
// find it in the map
|
||||
const auto it = entity_lookup.find(entity);
|
||||
if (it != entity_lookup.end()) {
|
||||
res += it->second;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// replace all the entities in the string
|
||||
std::string replaceHtmlEntities(const char* text) {
|
||||
std::string res;
|
||||
res.reserve(strlen(text));
|
||||
for (int i = 0; i < strlen(text); ++i) {
|
||||
bool flag = false;
|
||||
// do we have a potential entity?
|
||||
if (text[i] == '&') {
|
||||
// find the end of the entity
|
||||
int j = i + 1;
|
||||
while (j < strlen(text) && text[j] != ';' && j - i < MAX_ENTITY_LENGTH) {
|
||||
j++;
|
||||
}
|
||||
if (j - i > 2) {
|
||||
char entity[j - i + 1];
|
||||
strncpy(entity, text + i, j - i);
|
||||
// is it a numeric code?
|
||||
if (entity[1] == '#') {
|
||||
flag = process_numeric_entity(entity, res);
|
||||
} else {
|
||||
flag = process_string_entity(entity, res);
|
||||
}
|
||||
// skip past the entity if we successfully decoded it
|
||||
if (flag) {
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!flag) {
|
||||
res += text[i];
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// from
|
||||
// https://github.com/atomic14/diy-esp32-epub-reader/blob/2c2f57fdd7e2a788d14a0bcb26b9e845a47aac42/lib/Epub/RubbishHtmlParser/htmlEntities.cpp
|
||||
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
std::string replaceHtmlEntities(const char* text);
|
||||
@@ -6,7 +6,6 @@
|
||||
#include <expat.h>
|
||||
|
||||
#include "../Page.h"
|
||||
#include "../htmlEntities.h"
|
||||
|
||||
const char* HEADER_TAGS[] = {"h1", "h2", "h3", "h4", "h5", "h6"};
|
||||
constexpr int NUM_HEADER_TAGS = sizeof(HEADER_TAGS) / sizeof(HEADER_TAGS[0]);
|
||||
@@ -98,6 +97,9 @@ void XMLCALL ChapterHtmlSlimParser::startElement(void* userData, const XML_Char*
|
||||
self->startNewTextBlock(self->currentTextBlock->getStyle());
|
||||
} else {
|
||||
self->startNewTextBlock((TextBlock::Style)self->paragraphAlignment);
|
||||
if (strcmp(name, "li") == 0) {
|
||||
self->currentTextBlock->addWord("\xe2\x80\xa2", EpdFontFamily::REGULAR);
|
||||
}
|
||||
}
|
||||
} else if (matches(name, BOLD_TAGS, NUM_BOLD_TAGS)) {
|
||||
self->boldUntilDepth = std::min(self->boldUntilDepth, self->depth);
|
||||
@@ -130,7 +132,7 @@ void XMLCALL ChapterHtmlSlimParser::characterData(void* userData, const XML_Char
|
||||
// Currently looking at whitespace, if there's anything in the partWordBuffer, flush it
|
||||
if (self->partWordBufferIndex > 0) {
|
||||
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
||||
self->currentTextBlock->addWord(std::move(replaceHtmlEntities(self->partWordBuffer)), fontStyle);
|
||||
self->currentTextBlock->addWord(self->partWordBuffer, fontStyle);
|
||||
self->partWordBufferIndex = 0;
|
||||
}
|
||||
// Skip the whitespace char
|
||||
@@ -152,10 +154,24 @@ void XMLCALL ChapterHtmlSlimParser::characterData(void* userData, const XML_Char
|
||||
}
|
||||
}
|
||||
|
||||
// Skip Zero Width No-Break Space / BOM (U+FEFF) = 0xEF 0xBB 0xBF
|
||||
const XML_Char FEFF_BYTE_1 = static_cast<XML_Char>(0xEF);
|
||||
const XML_Char FEFF_BYTE_2 = static_cast<XML_Char>(0xBB);
|
||||
const XML_Char FEFF_BYTE_3 = static_cast<XML_Char>(0xBF);
|
||||
|
||||
if (s[i] == FEFF_BYTE_1) {
|
||||
// Check if the next two bytes complete the 3-byte sequence
|
||||
if ((i + 2 < len) && (s[i + 1] == FEFF_BYTE_2) && (s[i + 2] == FEFF_BYTE_3)) {
|
||||
// Sequence 0xEF 0xBB 0xBF found!
|
||||
i += 2; // Skip the next two bytes
|
||||
continue; // Move to the next iteration
|
||||
}
|
||||
}
|
||||
|
||||
// If we're about to run out of space, then cut the word off and start a new one
|
||||
if (self->partWordBufferIndex >= MAX_WORD_SIZE) {
|
||||
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
||||
self->currentTextBlock->addWord(std::move(replaceHtmlEntities(self->partWordBuffer)), fontStyle);
|
||||
self->currentTextBlock->addWord(self->partWordBuffer, fontStyle);
|
||||
self->partWordBufferIndex = 0;
|
||||
}
|
||||
|
||||
@@ -197,7 +213,7 @@ void XMLCALL ChapterHtmlSlimParser::endElement(void* userData, const XML_Char* n
|
||||
}
|
||||
|
||||
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
||||
self->currentTextBlock->addWord(std::move(replaceHtmlEntities(self->partWordBuffer)), fontStyle);
|
||||
self->currentTextBlock->addWord(self->partWordBuffer, fontStyle);
|
||||
self->partWordBufferIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
||||
if (strcmp(atts[i], "id") == 0) {
|
||||
itemId = atts[i + 1];
|
||||
} else if (strcmp(atts[i], "href") == 0) {
|
||||
href = self->baseContentPath + atts[i + 1];
|
||||
href = FsHelpers::normalisePath(self->baseContentPath + atts[i + 1]);
|
||||
} else if (strcmp(atts[i], "media-type") == 0) {
|
||||
mediaType = atts[i + 1];
|
||||
} else if (strcmp(atts[i], "properties") == 0) {
|
||||
@@ -243,7 +243,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
||||
break;
|
||||
}
|
||||
} else if (strcmp(atts[i], "href") == 0) {
|
||||
textHref = self->baseContentPath + atts[i + 1];
|
||||
textHref = FsHelpers::normalisePath(self->baseContentPath + atts[i + 1]);
|
||||
}
|
||||
}
|
||||
if ((type == "text" || (type == "start" && !self->textReferenceHref.empty())) && (textHref.length() > 0)) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "TocNavParser.h"
|
||||
|
||||
#include <FsHelpers.h>
|
||||
#include <HardwareSerial.h>
|
||||
|
||||
#include "../BookMetadataCache.h"
|
||||
@@ -140,7 +141,7 @@ void XMLCALL TocNavParser::endElement(void* userData, const XML_Char* name) {
|
||||
if (strcmp(name, "a") == 0 && self->state == IN_ANCHOR) {
|
||||
// Create TOC entry when closing anchor tag (we have all data now)
|
||||
if (!self->currentLabel.empty() && !self->currentHref.empty()) {
|
||||
std::string href = self->baseContentPath + self->currentHref;
|
||||
std::string href = FsHelpers::normalisePath(self->baseContentPath + self->currentHref);
|
||||
std::string anchor;
|
||||
|
||||
const size_t pos = href.find('#');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "TocNcxParser.h"
|
||||
|
||||
#include <FsHelpers.h>
|
||||
#include <HardwareSerial.h>
|
||||
|
||||
#include "../BookMetadataCache.h"
|
||||
@@ -159,7 +160,7 @@ void XMLCALL TocNcxParser::endElement(void* userData, const XML_Char* name) {
|
||||
// This is the safest place to push the data, assuming <navLabel> always comes before <content>.
|
||||
// NCX spec says navLabel comes before content.
|
||||
if (!self->currentLabel.empty() && !self->currentSrc.empty()) {
|
||||
std::string href = self->baseContentPath + self->currentSrc;
|
||||
std::string href = FsHelpers::normalisePath(self->baseContentPath + self->currentSrc);
|
||||
std::string anchor;
|
||||
|
||||
const size_t pos = href.find('#');
|
||||
|
||||
+37
-145
@@ -8,119 +8,15 @@
|
||||
// ============================================================================
|
||||
// Note: For cover images, dithering is done in JpegToBmpConverter.cpp
|
||||
// This file handles BMP reading - use simple quantization to avoid double-dithering
|
||||
constexpr bool USE_FLOYD_STEINBERG = false; // Disabled - dithering done at JPEG conversion
|
||||
constexpr bool USE_NOISE_DITHERING = false; // Hash-based noise dithering
|
||||
// Brightness adjustments:
|
||||
constexpr bool USE_BRIGHTNESS = false; // true: apply brightness/gamma adjustments
|
||||
constexpr int BRIGHTNESS_BOOST = 20; // Brightness offset (0-50), only if USE_BRIGHTNESS=true
|
||||
constexpr bool GAMMA_CORRECTION = false; // Gamma curve, only if USE_BRIGHTNESS=true
|
||||
constexpr bool USE_ATKINSON = true; // Use Atkinson dithering instead of Floyd-Steinberg
|
||||
// ============================================================================
|
||||
|
||||
// Integer approximation of gamma correction (brightens midtones)
|
||||
static inline int applyGamma(int gray) {
|
||||
if (!GAMMA_CORRECTION) return gray;
|
||||
const int product = gray * 255;
|
||||
int x = gray;
|
||||
if (x > 0) {
|
||||
x = (x + product / x) >> 1;
|
||||
x = (x + product / x) >> 1;
|
||||
}
|
||||
return x > 255 ? 255 : x;
|
||||
}
|
||||
|
||||
// Simple quantization without dithering - just divide into 4 levels
|
||||
static inline uint8_t quantizeSimple(int gray) {
|
||||
if (USE_BRIGHTNESS) {
|
||||
gray += BRIGHTNESS_BOOST;
|
||||
if (gray > 255) gray = 255;
|
||||
gray = applyGamma(gray);
|
||||
}
|
||||
return static_cast<uint8_t>(gray >> 6);
|
||||
}
|
||||
|
||||
// Hash-based noise dithering - survives downsampling without moiré artifacts
|
||||
static inline uint8_t quantizeNoise(int gray, int x, int y) {
|
||||
if (USE_BRIGHTNESS) {
|
||||
gray += BRIGHTNESS_BOOST;
|
||||
if (gray > 255) gray = 255;
|
||||
gray = applyGamma(gray);
|
||||
}
|
||||
|
||||
uint32_t hash = static_cast<uint32_t>(x) * 374761393u + static_cast<uint32_t>(y) * 668265263u;
|
||||
hash = (hash ^ (hash >> 13)) * 1274126177u;
|
||||
const int threshold = static_cast<int>(hash >> 24);
|
||||
|
||||
const int scaled = gray * 3;
|
||||
if (scaled < 255) {
|
||||
return (scaled + threshold >= 255) ? 1 : 0;
|
||||
} else if (scaled < 510) {
|
||||
return ((scaled - 255) + threshold >= 255) ? 2 : 1;
|
||||
} else {
|
||||
return ((scaled - 510) + threshold >= 255) ? 3 : 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Main quantization function
|
||||
static inline uint8_t quantize(int gray, int x, int y) {
|
||||
if (USE_NOISE_DITHERING) {
|
||||
return quantizeNoise(gray, x, y);
|
||||
} else {
|
||||
return quantizeSimple(gray);
|
||||
}
|
||||
}
|
||||
|
||||
// Floyd-Steinberg quantization with error diffusion and serpentine scanning
|
||||
// Returns 2-bit value (0-3) and updates error buffers
|
||||
static inline uint8_t quantizeFloydSteinberg(int gray, int x, int width, int16_t* errorCurRow, int16_t* errorNextRow,
|
||||
bool reverseDir) {
|
||||
// Add accumulated error to this pixel
|
||||
int adjusted = gray + errorCurRow[x + 1];
|
||||
|
||||
// Clamp to valid range
|
||||
if (adjusted < 0) adjusted = 0;
|
||||
if (adjusted > 255) adjusted = 255;
|
||||
|
||||
// Quantize to 4 levels (0, 85, 170, 255)
|
||||
uint8_t quantized;
|
||||
int quantizedValue;
|
||||
if (adjusted < 43) {
|
||||
quantized = 0;
|
||||
quantizedValue = 0;
|
||||
} else if (adjusted < 128) {
|
||||
quantized = 1;
|
||||
quantizedValue = 85;
|
||||
} else if (adjusted < 213) {
|
||||
quantized = 2;
|
||||
quantizedValue = 170;
|
||||
} else {
|
||||
quantized = 3;
|
||||
quantizedValue = 255;
|
||||
}
|
||||
|
||||
// Calculate error
|
||||
int error = adjusted - quantizedValue;
|
||||
|
||||
// Distribute error to neighbors (serpentine: direction-aware)
|
||||
if (!reverseDir) {
|
||||
// Left to right
|
||||
errorCurRow[x + 2] += (error * 7) >> 4; // Right: 7/16
|
||||
errorNextRow[x] += (error * 3) >> 4; // Bottom-left: 3/16
|
||||
errorNextRow[x + 1] += (error * 5) >> 4; // Bottom: 5/16
|
||||
errorNextRow[x + 2] += (error) >> 4; // Bottom-right: 1/16
|
||||
} else {
|
||||
// Right to left (mirrored)
|
||||
errorCurRow[x] += (error * 7) >> 4; // Left: 7/16
|
||||
errorNextRow[x + 2] += (error * 3) >> 4; // Bottom-right: 3/16
|
||||
errorNextRow[x + 1] += (error * 5) >> 4; // Bottom: 5/16
|
||||
errorNextRow[x] += (error) >> 4; // Bottom-left: 1/16
|
||||
}
|
||||
|
||||
return quantized;
|
||||
}
|
||||
|
||||
Bitmap::~Bitmap() {
|
||||
delete[] errorCurRow;
|
||||
delete[] errorNextRow;
|
||||
|
||||
delete atkinsonDitherer;
|
||||
delete fsDitherer;
|
||||
}
|
||||
|
||||
uint16_t Bitmap::readLE16(FsFile& f) {
|
||||
@@ -244,40 +140,25 @@ BmpReaderError Bitmap::parseHeaders() {
|
||||
return BmpReaderError::SeekPixelDataFailed;
|
||||
}
|
||||
|
||||
// Allocate Floyd-Steinberg error buffers if enabled
|
||||
if (USE_FLOYD_STEINBERG) {
|
||||
delete[] errorCurRow;
|
||||
delete[] errorNextRow;
|
||||
errorCurRow = new int16_t[width + 2](); // +2 for boundary handling
|
||||
errorNextRow = new int16_t[width + 2]();
|
||||
lastRowY = -1;
|
||||
// Create ditherer if enabled (only for 2-bit output)
|
||||
// Use OUTPUT dimensions for dithering (after prescaling)
|
||||
if (bpp > 2 && dithering) {
|
||||
if (USE_ATKINSON) {
|
||||
atkinsonDitherer = new AtkinsonDitherer(width);
|
||||
} else {
|
||||
fsDitherer = new FloydSteinbergDitherer(width);
|
||||
}
|
||||
}
|
||||
|
||||
return BmpReaderError::Ok;
|
||||
}
|
||||
|
||||
// packed 2bpp output, 0 = black, 1 = dark gray, 2 = light gray, 3 = white
|
||||
BmpReaderError Bitmap::readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) const {
|
||||
BmpReaderError Bitmap::readNextRow(uint8_t* data, uint8_t* rowBuffer) const {
|
||||
// Note: rowBuffer should be pre-allocated by the caller to size 'rowBytes'
|
||||
if (file.read(rowBuffer, rowBytes) != rowBytes) return BmpReaderError::ShortReadRow;
|
||||
|
||||
// Handle Floyd-Steinberg error buffer progression
|
||||
const bool useFS = USE_FLOYD_STEINBERG && errorCurRow && errorNextRow;
|
||||
if (useFS) {
|
||||
// Check if we need to advance to next row (or reset if jumping)
|
||||
if (rowY != lastRowY + 1 && rowY != 0) {
|
||||
// Non-sequential row access - reset error buffers
|
||||
memset(errorCurRow, 0, (width + 2) * sizeof(int16_t));
|
||||
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||
} else if (rowY > 0) {
|
||||
// Sequential access - swap buffers
|
||||
int16_t* temp = errorCurRow;
|
||||
errorCurRow = errorNextRow;
|
||||
errorNextRow = temp;
|
||||
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||
}
|
||||
lastRowY = rowY;
|
||||
}
|
||||
prevRowY += 1;
|
||||
|
||||
uint8_t* outPtr = data;
|
||||
uint8_t currentOutByte = 0;
|
||||
@@ -287,12 +168,18 @@ BmpReaderError Bitmap::readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) cons
|
||||
// Helper lambda to pack 2bpp color into the output stream
|
||||
auto packPixel = [&](const uint8_t lum) {
|
||||
uint8_t color;
|
||||
if (useFS) {
|
||||
// Floyd-Steinberg error diffusion
|
||||
color = quantizeFloydSteinberg(lum, currentX, width, errorCurRow, errorNextRow, false);
|
||||
if (atkinsonDitherer) {
|
||||
color = atkinsonDitherer->processPixel(adjustPixel(lum), currentX);
|
||||
} else if (fsDitherer) {
|
||||
color = fsDitherer->processPixel(adjustPixel(lum), currentX);
|
||||
} else {
|
||||
// Simple quantization or noise dithering
|
||||
color = quantize(lum, currentX, rowY);
|
||||
if (bpp > 2) {
|
||||
// Simple quantization or noise dithering
|
||||
color = quantize(adjustPixel(lum), currentX, prevRowY);
|
||||
} else {
|
||||
// do not quantize 2bpp image
|
||||
color = static_cast<uint8_t>(lum >> 6);
|
||||
}
|
||||
}
|
||||
currentOutByte |= (color << bitShift);
|
||||
if (bitShift == 0) {
|
||||
@@ -341,7 +228,10 @@ BmpReaderError Bitmap::readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) cons
|
||||
}
|
||||
case 1: {
|
||||
for (int x = 0; x < width; x++) {
|
||||
lum = (rowBuffer[x >> 3] & (0x80 >> (x & 7))) ? 0xFF : 0x00;
|
||||
// Get palette index (0 or 1) from bit at position x
|
||||
const uint8_t palIndex = (rowBuffer[x >> 3] & (0x80 >> (x & 7))) ? 1 : 0;
|
||||
// Use palette lookup for proper black/white mapping
|
||||
lum = paletteLum[palIndex];
|
||||
packPixel(lum);
|
||||
}
|
||||
break;
|
||||
@@ -350,6 +240,11 @@ BmpReaderError Bitmap::readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) cons
|
||||
return BmpReaderError::UnsupportedBpp;
|
||||
}
|
||||
|
||||
if (atkinsonDitherer)
|
||||
atkinsonDitherer->nextRow();
|
||||
else if (fsDitherer)
|
||||
fsDitherer->nextRow();
|
||||
|
||||
// Flush remaining bits if width is not a multiple of 4
|
||||
if (bitShift != 6) *outPtr = currentOutByte;
|
||||
|
||||
@@ -361,12 +256,9 @@ BmpReaderError Bitmap::rewindToData() const {
|
||||
return BmpReaderError::SeekPixelDataFailed;
|
||||
}
|
||||
|
||||
// Reset Floyd-Steinberg error buffers when rewinding
|
||||
if (USE_FLOYD_STEINBERG && errorCurRow && errorNextRow) {
|
||||
memset(errorCurRow, 0, (width + 2) * sizeof(int16_t));
|
||||
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||
lastRowY = -1;
|
||||
}
|
||||
// Reset dithering when rewinding
|
||||
if (fsDitherer) fsDitherer->reset();
|
||||
if (atkinsonDitherer) atkinsonDitherer->reset();
|
||||
|
||||
return BmpReaderError::Ok;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
#include <SdFat.h>
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
#include "BitmapHelpers.h"
|
||||
|
||||
enum class BmpReaderError : uint8_t {
|
||||
Ok = 0,
|
||||
FileInvalid,
|
||||
@@ -28,22 +32,25 @@ class Bitmap {
|
||||
public:
|
||||
static const char* errorToString(BmpReaderError err);
|
||||
|
||||
explicit Bitmap(FsFile& file) : file(file) {}
|
||||
explicit Bitmap(FsFile& file, bool dithering = false) : file(file), dithering(dithering) {}
|
||||
~Bitmap();
|
||||
BmpReaderError parseHeaders();
|
||||
BmpReaderError readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) const;
|
||||
BmpReaderError readNextRow(uint8_t* data, uint8_t* rowBuffer) const;
|
||||
BmpReaderError rewindToData() const;
|
||||
int getWidth() const { return width; }
|
||||
int getHeight() const { return height; }
|
||||
bool isTopDown() const { return topDown; }
|
||||
bool hasGreyscale() const { return bpp > 1; }
|
||||
int getRowBytes() const { return rowBytes; }
|
||||
bool is1Bit() const { return bpp == 1; }
|
||||
uint16_t getBpp() const { return bpp; }
|
||||
|
||||
private:
|
||||
static uint16_t readLE16(FsFile& f);
|
||||
static uint32_t readLE32(FsFile& f);
|
||||
|
||||
FsFile& file;
|
||||
bool dithering = false;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
bool topDown = false;
|
||||
@@ -55,5 +62,8 @@ class Bitmap {
|
||||
// Floyd-Steinberg dithering state (mutable for const methods)
|
||||
mutable int16_t* errorCurRow = nullptr;
|
||||
mutable int16_t* errorNextRow = nullptr;
|
||||
mutable int lastRowY = -1; // Track row progression for error propagation
|
||||
mutable int prevRowY = -1; // Track row progression for error propagation
|
||||
|
||||
mutable AtkinsonDitherer* atkinsonDitherer = nullptr;
|
||||
mutable FloydSteinbergDitherer* fsDitherer = nullptr;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
#include "BitmapHelpers.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Brightness/Contrast adjustments:
|
||||
constexpr bool USE_BRIGHTNESS = false; // true: apply brightness/gamma adjustments
|
||||
constexpr int BRIGHTNESS_BOOST = 10; // Brightness offset (0-50)
|
||||
constexpr bool GAMMA_CORRECTION = false; // Gamma curve (brightens midtones)
|
||||
constexpr float CONTRAST_FACTOR = 1.15f; // Contrast multiplier (1.0 = no change, >1 = more contrast)
|
||||
constexpr bool USE_NOISE_DITHERING = false; // Hash-based noise dithering
|
||||
|
||||
// Integer approximation of gamma correction (brightens midtones)
|
||||
// Uses a simple curve: out = 255 * sqrt(in/255) ≈ sqrt(in * 255)
|
||||
static inline int applyGamma(int gray) {
|
||||
if (!GAMMA_CORRECTION) return gray;
|
||||
// Fast integer square root approximation for gamma ~0.5 (brightening)
|
||||
// This brightens dark/mid tones while preserving highlights
|
||||
const int product = gray * 255;
|
||||
// Newton-Raphson integer sqrt (2 iterations for good accuracy)
|
||||
int x = gray;
|
||||
if (x > 0) {
|
||||
x = (x + product / x) >> 1;
|
||||
x = (x + product / x) >> 1;
|
||||
}
|
||||
return x > 255 ? 255 : x;
|
||||
}
|
||||
|
||||
// Apply contrast adjustment around midpoint (128)
|
||||
// factor > 1.0 increases contrast, < 1.0 decreases
|
||||
static inline int applyContrast(int gray) {
|
||||
// Integer-based contrast: (gray - 128) * factor + 128
|
||||
// Using fixed-point: factor 1.15 ≈ 115/100
|
||||
constexpr int factorNum = static_cast<int>(CONTRAST_FACTOR * 100);
|
||||
int adjusted = ((gray - 128) * factorNum) / 100 + 128;
|
||||
if (adjusted < 0) adjusted = 0;
|
||||
if (adjusted > 255) adjusted = 255;
|
||||
return adjusted;
|
||||
}
|
||||
// Combined brightness/contrast/gamma adjustment
|
||||
int adjustPixel(int gray) {
|
||||
if (!USE_BRIGHTNESS) return gray;
|
||||
|
||||
// Order: contrast first, then brightness, then gamma
|
||||
gray = applyContrast(gray);
|
||||
gray += BRIGHTNESS_BOOST;
|
||||
if (gray > 255) gray = 255;
|
||||
if (gray < 0) gray = 0;
|
||||
gray = applyGamma(gray);
|
||||
|
||||
return gray;
|
||||
}
|
||||
// Simple quantization without dithering - divide into 4 levels
|
||||
// The thresholds are fine-tuned to the X4 display
|
||||
uint8_t quantizeSimple(int gray) {
|
||||
if (gray < 45) {
|
||||
return 0;
|
||||
} else if (gray < 70) {
|
||||
return 1;
|
||||
} else if (gray < 140) {
|
||||
return 2;
|
||||
} else {
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
|
||||
// Hash-based noise dithering - survives downsampling without moiré artifacts
|
||||
// Uses integer hash to generate pseudo-random threshold per pixel
|
||||
static inline uint8_t quantizeNoise(int gray, int x, int y) {
|
||||
uint32_t hash = static_cast<uint32_t>(x) * 374761393u + static_cast<uint32_t>(y) * 668265263u;
|
||||
hash = (hash ^ (hash >> 13)) * 1274126177u;
|
||||
const int threshold = static_cast<int>(hash >> 24);
|
||||
|
||||
const int scaled = gray * 3;
|
||||
if (scaled < 255) {
|
||||
return (scaled + threshold >= 255) ? 1 : 0;
|
||||
} else if (scaled < 510) {
|
||||
return ((scaled - 255) + threshold >= 255) ? 2 : 1;
|
||||
} else {
|
||||
return ((scaled - 510) + threshold >= 255) ? 3 : 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Main quantization function - selects between methods based on config
|
||||
uint8_t quantize(int gray, int x, int y) {
|
||||
if (USE_NOISE_DITHERING) {
|
||||
return quantizeNoise(gray, x, y);
|
||||
} else {
|
||||
return quantizeSimple(gray);
|
||||
}
|
||||
}
|
||||
|
||||
// 1-bit noise dithering for fast home screen rendering
|
||||
// Uses hash-based noise for consistent dithering that works well at small sizes
|
||||
uint8_t quantize1bit(int gray, int x, int y) {
|
||||
gray = adjustPixel(gray);
|
||||
|
||||
// Generate noise threshold using integer hash (no regular pattern to alias)
|
||||
uint32_t hash = static_cast<uint32_t>(x) * 374761393u + static_cast<uint32_t>(y) * 668265263u;
|
||||
hash = (hash ^ (hash >> 13)) * 1274126177u;
|
||||
const int threshold = static_cast<int>(hash >> 24); // 0-255
|
||||
|
||||
// Simple threshold with noise: gray >= (128 + noise offset) -> white
|
||||
// The noise adds variation around the 128 midpoint
|
||||
const int adjustedThreshold = 128 + ((threshold - 128) / 2); // Range: 64-192
|
||||
return (gray >= adjustedThreshold) ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring>
|
||||
|
||||
// Helper functions
|
||||
uint8_t quantize(int gray, int x, int y);
|
||||
uint8_t quantizeSimple(int gray);
|
||||
uint8_t quantize1bit(int gray, int x, int y);
|
||||
int adjustPixel(int gray);
|
||||
|
||||
// 1-bit Atkinson dithering - better quality than noise dithering for thumbnails
|
||||
// Error distribution pattern (same as 2-bit but quantizes to 2 levels):
|
||||
// X 1/8 1/8
|
||||
// 1/8 1/8 1/8
|
||||
// 1/8
|
||||
class Atkinson1BitDitherer {
|
||||
public:
|
||||
explicit Atkinson1BitDitherer(int width) : width(width) {
|
||||
errorRow0 = new int16_t[width + 4](); // Current row
|
||||
errorRow1 = new int16_t[width + 4](); // Next row
|
||||
errorRow2 = new int16_t[width + 4](); // Row after next
|
||||
}
|
||||
|
||||
~Atkinson1BitDitherer() {
|
||||
delete[] errorRow0;
|
||||
delete[] errorRow1;
|
||||
delete[] errorRow2;
|
||||
}
|
||||
|
||||
// EXPLICITLY DELETE THE COPY CONSTRUCTOR
|
||||
Atkinson1BitDitherer(const Atkinson1BitDitherer& other) = delete;
|
||||
|
||||
// EXPLICITLY DELETE THE COPY ASSIGNMENT OPERATOR
|
||||
Atkinson1BitDitherer& operator=(const Atkinson1BitDitherer& other) = delete;
|
||||
|
||||
uint8_t processPixel(int gray, int x) {
|
||||
// Apply brightness/contrast/gamma adjustments
|
||||
gray = adjustPixel(gray);
|
||||
|
||||
// Add accumulated error
|
||||
int adjusted = gray + errorRow0[x + 2];
|
||||
if (adjusted < 0) adjusted = 0;
|
||||
if (adjusted > 255) adjusted = 255;
|
||||
|
||||
// Quantize to 2 levels (1-bit): 0 = black, 1 = white
|
||||
uint8_t quantized;
|
||||
int quantizedValue;
|
||||
if (adjusted < 128) {
|
||||
quantized = 0;
|
||||
quantizedValue = 0;
|
||||
} else {
|
||||
quantized = 1;
|
||||
quantizedValue = 255;
|
||||
}
|
||||
|
||||
// Calculate error (only distribute 6/8 = 75%)
|
||||
int error = (adjusted - quantizedValue) >> 3; // error/8
|
||||
|
||||
// Distribute 1/8 to each of 6 neighbors
|
||||
errorRow0[x + 3] += error; // Right
|
||||
errorRow0[x + 4] += error; // Right+1
|
||||
errorRow1[x + 1] += error; // Bottom-left
|
||||
errorRow1[x + 2] += error; // Bottom
|
||||
errorRow1[x + 3] += error; // Bottom-right
|
||||
errorRow2[x + 2] += error; // Two rows down
|
||||
|
||||
return quantized;
|
||||
}
|
||||
|
||||
void nextRow() {
|
||||
int16_t* temp = errorRow0;
|
||||
errorRow0 = errorRow1;
|
||||
errorRow1 = errorRow2;
|
||||
errorRow2 = temp;
|
||||
memset(errorRow2, 0, (width + 4) * sizeof(int16_t));
|
||||
}
|
||||
|
||||
void reset() {
|
||||
memset(errorRow0, 0, (width + 4) * sizeof(int16_t));
|
||||
memset(errorRow1, 0, (width + 4) * sizeof(int16_t));
|
||||
memset(errorRow2, 0, (width + 4) * sizeof(int16_t));
|
||||
}
|
||||
|
||||
private:
|
||||
int width;
|
||||
int16_t* errorRow0;
|
||||
int16_t* errorRow1;
|
||||
int16_t* errorRow2;
|
||||
};
|
||||
|
||||
// Atkinson dithering - distributes only 6/8 (75%) of error for cleaner results
|
||||
// Error distribution pattern:
|
||||
// X 1/8 1/8
|
||||
// 1/8 1/8 1/8
|
||||
// 1/8
|
||||
// Less error buildup = fewer artifacts than Floyd-Steinberg
|
||||
class AtkinsonDitherer {
|
||||
public:
|
||||
explicit AtkinsonDitherer(int width) : width(width) {
|
||||
errorRow0 = new int16_t[width + 4](); // Current row
|
||||
errorRow1 = new int16_t[width + 4](); // Next row
|
||||
errorRow2 = new int16_t[width + 4](); // Row after next
|
||||
}
|
||||
|
||||
~AtkinsonDitherer() {
|
||||
delete[] errorRow0;
|
||||
delete[] errorRow1;
|
||||
delete[] errorRow2;
|
||||
}
|
||||
// **1. EXPLICITLY DELETE THE COPY CONSTRUCTOR**
|
||||
AtkinsonDitherer(const AtkinsonDitherer& other) = delete;
|
||||
|
||||
// **2. EXPLICITLY DELETE THE COPY ASSIGNMENT OPERATOR**
|
||||
AtkinsonDitherer& operator=(const AtkinsonDitherer& other) = delete;
|
||||
|
||||
uint8_t processPixel(int gray, int x) {
|
||||
// Add accumulated error
|
||||
int adjusted = gray + errorRow0[x + 2];
|
||||
if (adjusted < 0) adjusted = 0;
|
||||
if (adjusted > 255) adjusted = 255;
|
||||
|
||||
// Quantize to 4 levels
|
||||
uint8_t quantized;
|
||||
int quantizedValue;
|
||||
if (false) { // original thresholds
|
||||
if (adjusted < 43) {
|
||||
quantized = 0;
|
||||
quantizedValue = 0;
|
||||
} else if (adjusted < 128) {
|
||||
quantized = 1;
|
||||
quantizedValue = 85;
|
||||
} else if (adjusted < 213) {
|
||||
quantized = 2;
|
||||
quantizedValue = 170;
|
||||
} else {
|
||||
quantized = 3;
|
||||
quantizedValue = 255;
|
||||
}
|
||||
} else { // fine-tuned to X4 eink display
|
||||
if (adjusted < 30) {
|
||||
quantized = 0;
|
||||
quantizedValue = 15;
|
||||
} else if (adjusted < 50) {
|
||||
quantized = 1;
|
||||
quantizedValue = 30;
|
||||
} else if (adjusted < 140) {
|
||||
quantized = 2;
|
||||
quantizedValue = 80;
|
||||
} else {
|
||||
quantized = 3;
|
||||
quantizedValue = 210;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate error (only distribute 6/8 = 75%)
|
||||
int error = (adjusted - quantizedValue) >> 3; // error/8
|
||||
|
||||
// Distribute 1/8 to each of 6 neighbors
|
||||
errorRow0[x + 3] += error; // Right
|
||||
errorRow0[x + 4] += error; // Right+1
|
||||
errorRow1[x + 1] += error; // Bottom-left
|
||||
errorRow1[x + 2] += error; // Bottom
|
||||
errorRow1[x + 3] += error; // Bottom-right
|
||||
errorRow2[x + 2] += error; // Two rows down
|
||||
|
||||
return quantized;
|
||||
}
|
||||
|
||||
void nextRow() {
|
||||
int16_t* temp = errorRow0;
|
||||
errorRow0 = errorRow1;
|
||||
errorRow1 = errorRow2;
|
||||
errorRow2 = temp;
|
||||
memset(errorRow2, 0, (width + 4) * sizeof(int16_t));
|
||||
}
|
||||
|
||||
void reset() {
|
||||
memset(errorRow0, 0, (width + 4) * sizeof(int16_t));
|
||||
memset(errorRow1, 0, (width + 4) * sizeof(int16_t));
|
||||
memset(errorRow2, 0, (width + 4) * sizeof(int16_t));
|
||||
}
|
||||
|
||||
private:
|
||||
int width;
|
||||
int16_t* errorRow0;
|
||||
int16_t* errorRow1;
|
||||
int16_t* errorRow2;
|
||||
};
|
||||
|
||||
// Floyd-Steinberg error diffusion dithering with serpentine scanning
|
||||
// Serpentine scanning alternates direction each row to reduce "worm" artifacts
|
||||
// Error distribution pattern (left-to-right):
|
||||
// X 7/16
|
||||
// 3/16 5/16 1/16
|
||||
// Error distribution pattern (right-to-left, mirrored):
|
||||
// 1/16 5/16 3/16
|
||||
// 7/16 X
|
||||
class FloydSteinbergDitherer {
|
||||
public:
|
||||
explicit FloydSteinbergDitherer(int width) : width(width), rowCount(0) {
|
||||
errorCurRow = new int16_t[width + 2](); // +2 for boundary handling
|
||||
errorNextRow = new int16_t[width + 2]();
|
||||
}
|
||||
|
||||
~FloydSteinbergDitherer() {
|
||||
delete[] errorCurRow;
|
||||
delete[] errorNextRow;
|
||||
}
|
||||
|
||||
// **1. EXPLICITLY DELETE THE COPY CONSTRUCTOR**
|
||||
FloydSteinbergDitherer(const FloydSteinbergDitherer& other) = delete;
|
||||
|
||||
// **2. EXPLICITLY DELETE THE COPY ASSIGNMENT OPERATOR**
|
||||
FloydSteinbergDitherer& operator=(const FloydSteinbergDitherer& other) = delete;
|
||||
|
||||
// Process a single pixel and return quantized 2-bit value
|
||||
// x is the logical x position (0 to width-1), direction handled internally
|
||||
uint8_t processPixel(int gray, int x) {
|
||||
// Add accumulated error to this pixel
|
||||
int adjusted = gray + errorCurRow[x + 1];
|
||||
|
||||
// Clamp to valid range
|
||||
if (adjusted < 0) adjusted = 0;
|
||||
if (adjusted > 255) adjusted = 255;
|
||||
|
||||
// Quantize to 4 levels (0, 85, 170, 255)
|
||||
uint8_t quantized;
|
||||
int quantizedValue;
|
||||
if (false) { // original thresholds
|
||||
if (adjusted < 43) {
|
||||
quantized = 0;
|
||||
quantizedValue = 0;
|
||||
} else if (adjusted < 128) {
|
||||
quantized = 1;
|
||||
quantizedValue = 85;
|
||||
} else if (adjusted < 213) {
|
||||
quantized = 2;
|
||||
quantizedValue = 170;
|
||||
} else {
|
||||
quantized = 3;
|
||||
quantizedValue = 255;
|
||||
}
|
||||
} else { // fine-tuned to X4 eink display
|
||||
if (adjusted < 30) {
|
||||
quantized = 0;
|
||||
quantizedValue = 15;
|
||||
} else if (adjusted < 50) {
|
||||
quantized = 1;
|
||||
quantizedValue = 30;
|
||||
} else if (adjusted < 140) {
|
||||
quantized = 2;
|
||||
quantizedValue = 80;
|
||||
} else {
|
||||
quantized = 3;
|
||||
quantizedValue = 210;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate error
|
||||
int error = adjusted - quantizedValue;
|
||||
|
||||
// Distribute error to neighbors (serpentine: direction-aware)
|
||||
if (!isReverseRow()) {
|
||||
// Left to right: standard distribution
|
||||
// Right: 7/16
|
||||
errorCurRow[x + 2] += (error * 7) >> 4;
|
||||
// Bottom-left: 3/16
|
||||
errorNextRow[x] += (error * 3) >> 4;
|
||||
// Bottom: 5/16
|
||||
errorNextRow[x + 1] += (error * 5) >> 4;
|
||||
// Bottom-right: 1/16
|
||||
errorNextRow[x + 2] += (error) >> 4;
|
||||
} else {
|
||||
// Right to left: mirrored distribution
|
||||
// Left: 7/16
|
||||
errorCurRow[x] += (error * 7) >> 4;
|
||||
// Bottom-right: 3/16
|
||||
errorNextRow[x + 2] += (error * 3) >> 4;
|
||||
// Bottom: 5/16
|
||||
errorNextRow[x + 1] += (error * 5) >> 4;
|
||||
// Bottom-left: 1/16
|
||||
errorNextRow[x] += (error) >> 4;
|
||||
}
|
||||
|
||||
return quantized;
|
||||
}
|
||||
|
||||
// Call at the end of each row to swap buffers
|
||||
void nextRow() {
|
||||
// Swap buffers
|
||||
int16_t* temp = errorCurRow;
|
||||
errorCurRow = errorNextRow;
|
||||
errorNextRow = temp;
|
||||
// Clear the next row buffer
|
||||
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||
rowCount++;
|
||||
}
|
||||
|
||||
// Check if current row should be processed in reverse
|
||||
bool isReverseRow() const { return (rowCount & 1) != 0; }
|
||||
|
||||
// Reset for a new image or MCU block
|
||||
void reset() {
|
||||
memset(errorCurRow, 0, (width + 2) * sizeof(int16_t));
|
||||
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||
rowCount = 0;
|
||||
}
|
||||
|
||||
private:
|
||||
int width;
|
||||
int rowCount;
|
||||
int16_t* errorCurRow;
|
||||
int16_t* errorNextRow;
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user