3dslibris: porting the EPUB reader to 3DS
How I built 3dslibris, the Nintendo 3DS ebook and manga reader: porting from DS, EPUB, PDF and MuPDF.
Watch 3dslibris in action
You can also explore the project in this video from my YouTube channel. The original audio is in Spanish, with English subtitles and automatic dubbing available. Choose subtitles or the English audio track in the YouTube player settings.
Explore the technical article
From DS to 3DS: why this project exists
In 2007, Ray Haleblian created dslibris, an EPUB reader for the Nintendo DS. Even then, it parsed EPUB 2.0, rendered text with FreeType2, saved preferences, and accessed DS VRAM directly. But development stalled in 2020, without support for other formats, and the repository was unmaintained and archived by 2025.
The 3dslibris project brings that reader to the Nintendo 3DS as homebrew. To do that, I had to rewrite the entire graphics layer and adapt the controls. Then I added other formats, with the memory and performance problems that come with doing this on a console like the 3DS. I also had to account for the hardware differences between the original 3DS and the New 3DS.
The project is available on GitHub. The latest downloads and current user guide are separate from this development “story”.

3dslibris banner — Ebook reader for Nintendo 3DS
What was reused and what was written from scratch
This post takes the 3dslibris 1.0.0 codebase as its starting point and also covers the integration of MuPDF in version 2.0.0. The project has changed and grown quite a bit since then. For installation and usage, see the current guide linked above.
Code inherited from the original DS
The following modules from the original dslibris were ported with modifications:
| Module | Lines | Main changes |
|---|---|---|
book.cpp | 675 | Added cover fields (coverPixels, coverImagePath) |
text.cpp | 728 | Rewrote BlitToFramebuffer() for rotated 90° RGB8 framebuffer |
page.cpp | 225 | Rewrote DrawNumber() for dual screen with clock and % progress |
epub.cpp | 416 | Added cover extraction (epub_extract_cover()) |
app.cpp | 338 | Completely rewritten for libctru |
prefs.cpp | 289 | Added time24h field |
font.cpp | 184 | Adapted paths to sdmc:/ |
Components written from scratch
Entry point (
main.cpp) — 3DS service initialization, directory creation, App instance and main loop with error handling.Blitting to 3DS framebuffer — The DS accessed VRAM directly in RGB555 format with normal orientation. The 3DS uses a software framebuffer in RGB8 format (24 bits) rotated 90°. The
BlitToFramebuffer()function converts RGB565 → RGB8 and applies rotation when copying pixels.Cover system — During OPF parsing, the cover image is located (EPUB 2:
<meta name="cover">, EPUB 3:<item properties="cover-image">). It’s extracted from the ZIP, decoded with stb_image, scaled to 95×55 pixels, and stored as an RGB565 buffer.Grid library — The original DS used a vertical list. The 3DS shows a 2×2 grid with covers, titles, progress indicators, and touch + D-Pad navigation.
Clock and reading percentage — At the bottom of the left screen, the current time and book reading percentage are displayed.
stb_image — Sean Barrett’s public domain library embedded for JPEG and PNG decoding, configured with
STBI_NO_STDIOand only the necessary decoders to minimize binary size.
Vendored libraries
| Component | Lines | Purpose |
|---|---|---|
| Expat XML | ~15,000 | XML parsing (EPUB, preferences) |
| minizip | ~2,200 | Reading files inside EPUB ZIP |
| stb_image | ~8,000 | Image decoding for covers |
| libunibreak | ~10,000 | Unicode-aware line breaking (UAX #14) |
| utf8proc | ~8,000 | Unicode normalization and properties |
Code architecture during the port
The original project had all its logic in source/core/. During the port, I split the library, reader, settings, and formats into their own directories so that each module had its own responsibility and was easier to maintain:
| |
Execution flow
main()→ init gfx, create directories,App::Run()App::Run()→ load fonts, find books, parse metadata (+ extract covers), show library- BROWSER mode (
library/app_browser.cpp): Grid of books with covers. Touch/A opens book. SELECT/Y opens settings. - BOOK mode (
reader/app_book.cpp): Renders pages with FreeType. D-Pad/A/B turns pages. START returns to library. - FIXED-LAYOUT mode (PDF/CBZ/XPS): MuPDF rendering with zoom, bottom screen preview, and outline navigation.
- PREFS mode (
settings/app_prefs.cpp): Configuration buttons on the right screen. Controls on the left screen. - Each frame:
Text::BlitToFramebuffer()copies internal buffers to the real 3DS framebuffer.
The screen rendering system
Internal buffers
| |
The buffers are square (400×400) for compatibility with the original DS indexing. About 40% of the space is wasted, but changing this would mean rewriting the entire text engine, which assumes square buffers, and the blitting system. At the time, I left it for later.
Pixel format and rotation
| Stage | Format |
|---|---|
| Internal buffer | RGB565 (16 bits) |
| Real 3DS framebuffer | RGB8 (24 bits) |
| Conversion | BlitToFramebuffer() does RGB565 → RGB8 + 90° rotation |
The 3DS stores the framebuffer rotated 90° from how we see it. A 400×240 screen is stored as a 240×400 buffer. BlitToFramebuffer() handles this transformation pixel by pixel.
Unicode-aware text runs
The original DS text engine worked byte by byte, which caused problems with multi-byte UTF-8 characters (accents, ñ, CJK characters). I integrated libunibreak (UAX #14 for line breaking) and utf8proc (Unicode properties) so the engine could work with codepoints instead of individual bytes. This directly affects line breaks, wrapping, and pagination in books with non-ASCII content.
Text size clamping
I limited the configurable text size in text_limits.h. Without this clamp, extreme font sizes could cause buffer overflows and visual corruption, as they did in older builds. The limits apply both in the preferences UI and in direct rendering.
EPUB parsing and format pipeline
Format support
| Format | Support level | Engine |
|---|---|---|
| EPUB (2/3) | Strong | Custom parser + FreeType |
| FB2 | Good | Custom XML parser |
| TXT / RTF / ODT | Good | Custom parser |
| MOBI | Experimental | Custom parser with inline image pipeline |
| Viewer | MuPDF | |
| CBZ | Viewer | MuPDF |
| XPS | Viewer | MuPDF |
EPUB pipeline
| |
Smart embedded image layout
Previously, any <img> embedded in EPUB/FB2 was displayed full screen. So if an EPUB contained, say, musical notation or a small separator icon, it took up an entire screen.
To fit the space to each image, pagination and rendering share a scheduler (inline_image_layout.cpp) that distinguishes three modes:
inline: very small image, behaves like a large glyph within the line flowband: wide image or block icon, consumes only the necessary height and text continues belowpage: large image, maintains the classic full-screen block behavior
The parser also marks when an image is the first element of a paragraph. This helps with EPUBs where an icon belongs to the same paragraph as the text.
Image probing optimization
With the first prototype, opening an EPUB with lots of images took about 50 seconds in my tests with Azahar, the emulator. To reduce that wait, I made these changes:
- A ZIP entry index per book is maintained
- During
spineparsing, an auxiliaryunzFileis reused - The metadata probe tries to read only a prefix of the image when sufficient
With these changes, the same EPUBs went from taking ~50 s to open to ~5 s.
<pre> and <code> blocks in XHTML
<pre> and <code> blocks in technical EPUBs need special handling: the text must not wrap like normal prose, but it must not overflow the page buffer either. I gave them a separate layout path that preserves literal line breaks without affecting the rest of the text.
MuPDF integration: PDF, CBZ, and XPS
In version 2.0.0, I added MuPDF to render fixed-layout formats. Until then, the reader was designed for text that could be repaginated. PDF, CBZ, and XPS needed whole pages that could be panned and zoomed, so I had to integrate a more capable rendering engine.
Fixed-layout stack architecture
I separated MuPDF into a backend with its own rendering process, although it shares the display infrastructure with the rest of the reader:
- Top screen: zoomed region of the current page
- Bottom screen: full-page preview with viewport box
- Unified controls:
A/Bzoom,Left/Rightchange page,Up/Downnavigate outline, touch to move viewport
The stack is divided into three layers:
- Document (
mupdf_document.cpp): opening, context, outline - Render (
mupdf_render.cpp): page rendering to bitmap - View (
mupdf_view.cpp): viewport, progressive rendering, touch interaction
Progressive rendering
To display something while the page is rendering, the reader works in several passes:
- A low-resolution version is shown immediately
- It’s refined in the background at higher quality
- The user can interact with the page while it refines
Worker thread on New 3DS
The New Nintendo 3DS has a second processor core. PDF/CBZ rendering is delegated to a dedicated thread on the second core (reflow_worker.cpp for text, mupdf_worker.cpp / cbz_worker.cpp for fixed-layout), keeping the UI responsive. The Old 3DS uses an automatic synchronous fallback.
Caching and page prefetch
- Page prefetch is deferred until the user turns a page, avoiding unnecessary work
- Render cache reuse was accelerated by stabilizing the viewport
- Dirty rectangles are tracked precisely to avoid unnecessary redraws
- Fixed-layout redraw artifacts that caused flickering during page navigation were fixed
MuPDF minimal generation serialization
To avoid race conditions during the build, MuPDF minimal file generation was serialized in the Makefile, ensuring dependencies resolve in the correct order even with parallel compilation (make -j2).
The MOBI format
MOBI was the format I found hardest to adapt. Unlike EPUB, which is essentially a ZIP with XHTML, MOBI uses a proprietary binary format with HUFF/CDIC compression, chained records, and a TOC structure that depends heavily on how the file was generated. There is no “universal parser” that works with every MOBI file.
Record decoding and HUFF/CDIC support
The original MOBI decoder had record-decoding bugs that corrupted books using HUFF/CDIC compression. I rewrote the decoding module (mobi_record_decode.cpp) to fix them:
- Bounded scanning of image records to avoid uncontrolled sweeps on large books
- Correct HUFF/CDIC table decoding
- RGB retry for certain inline JPEGs that fail on initial decode
Asynchronous opening (New 3DS)
In version 2.0.0, MOBI opening on New 3DS is asynchronous: the user can start reading while the rest of the book is paginated in the background. This eliminates the UI blocking that could previously last several seconds on large books.
Inline image pipeline
Inline images in MOBI (<img recindex="N">) use the same inline / band / page pipeline as EPUB/FB2, with:
- RGB retry for certain JPEGs that fail on initial decode
- Preservation of binary image tokens during text cleanup phases
- Persistent cover metadata cache
Per-book line wrap fix
Many poorly converted MOBI files have hard-wrapped lines: each line of “prose” ends with an actual line break. I added an optional per-book fix that removes these breaks without destroying inline image markers.
Additionally, the legacy plain-text wrap behavior for MOBI that had been lost during earlier refactorings was restored, ensuring that unmarked prose behaves correctly.
Heuristic MOBI index
MOBI TOC resolution uses an html→text→page mapping with two lookup tables. It’s heuristic and depends on the source file, but significantly more accurate than the initial approach.
Optimizations for real hardware
Memory
| Component | Estimated memory |
|---|---|
| Screen buffers (×3) | ~940 KB |
| FreeType fonts (×4) | ~800 KB |
| XML/EPUB buffers | ~200 KB |
| 20 books with covers | ~200 KB |
| 500 text pages | ~1 MB |
| Total estimated | ~3.1 MB |
Well below the 64 MB available on an Old 3DS, leaving room for temporary buffers, caches, and the MuPDF heap.
CPU
| Optimization | Detail |
|---|---|
-O2 | Compilation with optimization level 2 |
-ffunction-sections | Dead code elimination per section |
-fno-rtti -fno-exceptions | No RTTI or C++ exceptions |
-march=armv6k -mtune=mpcore | Optimized for 3DS ARM11 |
| Lazy double buffer | Only redraws when view_dirty changes |
| Glyph advance cache (LRU) | Glyph advance width cache to avoid repeated rasterization |
| EPUB page cache | Persistent page cache for fast reopens |
Deferred reflow
Changes to font, size, spacing, or orientation do not repaginate the open book. The setting is saved, the book is marked as outdated, and repagination is applied when reopening. This avoids inconsistent states and layout bugs.
Library optimizations
In the later stages, I also adjusted the book browser:
- Lazy cover loading: covers of non-visible books are not decoded until they enter the viewport
- Selective warmup: the selected book receives warmup priority after a brief idle period
- Job queue: metadata, cover extraction, and TOC resolution tasks are enqueued and executed with a time budget (
budget_ms), avoiding frame blocking - Cover cache pruning: non-visible covers are freed from memory to keep the footprint low
- Optimized framebuffer blit: copies to the 3DS framebuffer use precise dirty region tracking, avoiding unnecessary full copies
Reusing buffers
Parsing and rendering created and destroyed a lot of temporary buffers. I reduced those operations in several ways:
- Page buffers are reused through an owned buffer system (
page_buffer_utils.h) instead of allocating/deallocating on each parse - Buffer churn in book I/O flows was reduced with buffer aliasing instead of copies
- RTF text cleanup was optimized with a dedicated control word parser (
rtf_control_word_utils.h) that avoids creating intermediate strings
Buffered logging
In debug builds, parse logging is buffered in memory (buffered_status_log.cpp) instead of being written to a file line by line. This reduces state I/O and keeps logging from interfering with pagination.
UTF-8 optimization
UTF-8 decoding in text rendering flows was optimized, reducing conversion cost per frame. Mojibake repair (misencoded characters) was centralized in utf8_utils.cpp with optimized routes for the most common patterns (fullwidth bytes, soft-hyphen corruption).
Packaging and distribution
Distribution formats
| Artifact | Purpose |
|---|---|
3dslibris.3dsx | Homebrew Launcher |
3dslibris-debug.3dsx | Build with verbose logging (3dslibris.log) |
3dslibris.cia | Direct install (includes fonts and resources via romfs) |
3dslibris-sdmc.zip | SD package with directory structure |
Fonts and resources inside the .cia
Originally, the .cia required users to extract 3dslibris-sdmc.zip to the SD card manually to access fonts and UI resources. I packaged the required resources (font/, resources/) inside the application’s romfs so that installing the .cia would be enough.
The SD fallback still exists: if files are present at sdmc:/3ds/3dslibris/, those take priority over packaged ones, allowing customization.
.cia flow with Docker
The .cia packaging uses makerom and bannertool, aligned with the Universal-Updater flow. It’s built inside a Docker container to avoid permission issues:
| |
CI/CD with GitHub Actions
When pushing a v* tag, the release.yml workflow automatically compiles and attaches all artifacts to GitHub Releases.
Development statistics
| Metric | Value |
|---|---|
| Lines of own code (C/C++) | ~7,000 |
| Vendored libraries | ~43,000 (Expat + minizip + stb_image + libunibreak + utf8proc) |
| Binary size (.3dsx) | ~1.44 MB |
| Formats supported at this stage | 9 (EPUB, FB2, TXT, RTF, ODT, MOBI, PDF, CBZ, XPS) |
| Total commits | 173+ |
| Active development time | ~2 months intensive |
Modules in shared/ | 19 cross-cutting utility headers |
| Unit test suites | 20+ with validation scripts |
What I take away from this
About constrained hardware
The 3DS has no garbage collector, virtual memory, or swap. Allocating 2 MB too much can stop the system from booting, or make it crash. That led me to revisit things that had seemed minor at first, such as reusing ZIP state or buffering logs in memory before writing them to a file. Opening times and memory usage let me check whether each change helped.
About legacy code
The original dslibris assumed direct VRAM access, specific buttons, and a 256×192 screen. Before changing each part, I had to understand where it relied on those assumptions, especially to preserve the pagination logic when adapting it to the 3DS.
Honestly, maybe rewriting the whole thing from scratch would have been better.
About code architecture
Splitting the 20+ files in source/core/ into directories by function (app/, library/, reader/, book/, formats/, ui/, shared/) helped me find the code I needed to change. Moving it also meant reviewing dependencies between modules and putting utilities used by several parts into shared/.
About licenses
When I integrated MuPDF, I had to review what the AGPL required to distribute the application. That included documenting the source release, separating components, and explaining which obligations applied to each build.
Links
- GitHub Repository
- Releases
- Contribution Guide
- Original dslibris by Ray Haleblian