← back to blog

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.

Watch the video on YouTube.

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, an ebook reader for Nintendo 3DS

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:

ModuleLinesMain changes
book.cpp675Added cover fields (coverPixels, coverImagePath)
text.cpp728Rewrote BlitToFramebuffer() for rotated 90° RGB8 framebuffer
page.cpp225Rewrote DrawNumber() for dual screen with clock and % progress
epub.cpp416Added cover extraction (epub_extract_cover())
app.cpp338Completely rewritten for libctru
prefs.cpp289Added time24h field
font.cpp184Adapted paths to sdmc:/

Components written from scratch

  1. Entry point (main.cpp) — 3DS service initialization, directory creation, App instance and main loop with error handling.

  2. 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.

  3. 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.

  4. 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.

  5. Clock and reading percentage — At the bottom of the left screen, the current time and book reading percentage are displayed.

  6. stb_image — Sean Barrett’s public domain library embedded for JPEG and PNG decoding, configured with STBI_NO_STDIO and only the necessary decoders to minimize binary size.

Vendored libraries

ComponentLinesPurpose
Expat XML~15,000XML parsing (EPUB, preferences)
minizip~2,200Reading files inside EPUB ZIP
stb_image~8,000Image decoding for covers
libunibreak~10,000Unicode-aware line breaking (UAX #14)
utf8proc~8,000Unicode 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
3dslibris/
├── source/
│   ├── main.cpp                        # 3DS entry point
│   ├── app/                            # Main orchestrator
│   │   └── app.cpp                     # App::Run(), mode management, job queue
│   ├── library/                        # Library / book browser
│   │   └── app_browser.cpp             # Grid view, warmup, cover cache
│   ├── reader/                         # Reading view (reflowable text)
│   │   └── app_book.cpp                # Book mode, deferred reflow
│   ├── settings/                       # Preferences and fonts
│   │   ├── app_prefs.cpp               # Settings menu
│   │   ├── prefs.cpp                   # XML persistence
│   │   └── font.cpp                    # FreeType font loading
│   ├── book/                           # Book domain model
│   │   ├── book.cpp                    # Metadata, pages, chapters
│   │   ├── page.cpp                    # Individual text page
│   │   ├── book_fixed_layout.cpp       # Viewport and deferred work (PDF/CBZ)
│   │   ├── book_inline_image.cpp       # Inline image loading and caching
│   │   ├── heading_layout.cpp          # Keep-with-next for headings
│   │   ├── inline_image_layout.cpp     # Inline/band/page scheduler
│   │   ├── layout_reflow.cpp           # Deferred repagination
│   │   └── reflow_worker.cpp           # New 3DS worker thread
│   ├── formats/                        # Format parsers
│   │   ├── common/                     # Shared utilities
│   │   │   ├── book_io.cpp             # Generic book I/O
│   │   │   ├── buffered_status_log.cpp # Buffered logging
│   │   │   ├── epub_image_utils.cpp    # EPUB image utilities
│   │   │   ├── file_read_utils.cpp     # Safe file reading
│   │   │   ├── page_cache_utils.cpp    # Persistent page cache
│   │   │   └── xml_parse_utils.cpp     # Expat wrapper
│   │   ├── epub/                       # EPUB parser
│   │   ├── fb2/                        # FictionBook 2 parser
│   │   ├── mobi/                       # Full MOBI parser
│   │   │   ├── mobi.cpp                # Main MOBI pipeline
│   │   │   ├── mobi_record_decode.cpp  # Record decoding (HUFF/CDIC)
│   │   │   ├── mobi_record_scan.cpp    # Bounded record scanning
│   │   │   ├── mobi_text_cleanup.cpp   # Text cleanup and wrap fix
│   │   │   ├── mobi_heading_markers.cpp # Semantic heading markers
│   │   │   ├── mobi_cover_meta_cache.cpp # Cover metadata cache
│   │   │   ├── mobi_markup_tag.cpp     # MOBI markup tags
│   │   │   └── mobi_position_map.cpp   # Position mapping
│   │   ├── mupdf/                      # MuPDF backend (PDF/XPS)
│   │   │   ├── mupdf_common.cpp        # Shared context
│   │   │   ├── mupdf_document.cpp      # Document opening
│   │   │   ├── mupdf_render.cpp        # Page rendering
│   │   │   ├── mupdf_view.cpp          # Viewport and progressive rendering
│   │   │   └── mupdf_worker.cpp        # Rendering worker thread
│   │   ├── pdf/                        # PDF wrapper over MuPDF
│   │   ├── cbz/                        # Comic Book Archive
│   │   │   ├── cbz.cpp                 # Detection and entry
│   │   │   ├── cbz_archive.cpp         # ZIP archive management
│   │   │   ├── cbz_decode.cpp          # Image decoding
│   │   │   ├── cbz_document.cpp        # Document initialization
│   │   │   ├── cbz_view.cpp            # View and viewport
│   │   │   └── cbz_worker.cpp          # Rendering worker thread
│   ├── menus/                          # Paginated menus
│   │   ├── menu.cpp                    # Menu base
│   │   ├── chapter_menu.cpp            # Chapter index
│   │   ├── bookmark_menu.cpp           # Bookmarks
│   │   └── paged_list_menu.cpp         # Generic paginated list
│   ├── ui/                             # UI layer
│   │   ├── text.cpp                    # Text engine (FreeType + blit)
│   │   ├── button.cpp                  # UI buttons
│   │   ├── browser_nav.cpp             # Library navigation
│   │   ├── touch_utils.cpp             # Touch hit-testing
│   │   └── ui_button_skin.cpp          # Procedural button skin
│   ├── core/                           # Minimal core
│   │   ├── parse.cpp                   # XML parsing initialization
│   │   └── stb_image_impl.cpp          # stb_image implementation
│   └── shared/                         # Cross-cutting utilities
│       ├── app_flow_utils.cpp          # Flow control between modes
│       ├── utf8_utils.cpp              # UTF-8 conversion and repair
│       ├── text_unicode_utils.cpp      # Unicode-aware text runs
│       ├── text_layout_utils.cpp       # Text layout (pre/code, etc.)
│       ├── pdf_view_utils.cpp          # PDF view helpers
│       └── ...                         # (19 headers total)
├── include/                            # Headers (same structure)
├── third_party/                        # External dependencies
│   ├── libunibreak/                    # UAX #14 line breaking
│   └── utf8proc/                       # Unicode properties
└── tests/                              # Unit tests per module

Execution flow

  1. main() → init gfx, create directories, App::Run()
  2. App::Run() → load fonts, find books, parse metadata (+ extract covers), show library
  3. BROWSER mode (library/app_browser.cpp): Grid of books with covers. Touch/A opens book. SELECT/Y opens settings.
  4. BOOK mode (reader/app_book.cpp): Renders pages with FreeType. D-Pad/A/B turns pages. START returns to library.
  5. FIXED-LAYOUT mode (PDF/CBZ/XPS): MuPDF rendering with zoom, bottom screen preview, and outline navigation.
  6. PREFS mode (settings/app_prefs.cpp): Configuration buttons on the right screen. Controls on the left screen.
  7. Each frame: Text::BlitToFramebuffer() copies internal buffers to the real 3DS framebuffer.

The screen rendering system

Internal buffers

1
2
3
screenleft[400×400]   — Top screen, used as 400×240
screenright[400×400]  — Bottom screen, used as 320×240
offscreen[400×400]    — Temporary buffer

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

StageFormat
Internal bufferRGB565 (16 bits)
Real 3DS framebufferRGB8 (24 bits)
ConversionBlitToFramebuffer() 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

FormatSupport levelEngine
EPUB (2/3)StrongCustom parser + FreeType
FB2GoodCustom XML parser
TXT / RTF / ODTGoodCustom parser
MOBIExperimentalCustom parser with inline image pipeline
PDFViewerMuPDF
CBZViewerMuPDF
XPSViewerMuPDF

EPUB pipeline

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
EPUB (ZIP) → META-INF/container.xml → rootfile (.opf)
                                       │
                                ┌──────┴──────┐
                                │  Metadata    │
                                │  (title,     │
                                │   author,    │
                                │   cover)     │
                                └──────┬──────┘
                                       │
                                ┌──────┴──────┐
                                │  Manifest    │
                                │  (files)     │
                                └──────┬──────┘
                                       │
                                ┌──────┴──────┐
                                │  Spine       │
                                │  (order)     │
                                └──────┬──────┘
                                       │
                                       ▼
                                XHTML of each chapter
                                → XML parsing → Page objects

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 flow
  • band: wide image or block icon, consumes only the necessary height and text continues below
  • page: 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 spine parsing, an auxiliary unzFile is 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/B zoom, Left/Right change page, Up/Down navigate outline, touch to move viewport

The stack is divided into three layers:

  1. Document (mupdf_document.cpp): opening, context, outline
  2. Render (mupdf_render.cpp): page rendering to bitmap
  3. 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:

  1. A low-resolution version is shown immediately
  2. It’s refined in the background at higher quality
  3. 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

ComponentEstimated 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

OptimizationDetail
-O2Compilation with optimization level 2
-ffunction-sectionsDead code elimination per section
-fno-rtti -fno-exceptionsNo RTTI or C++ exceptions
-march=armv6k -mtune=mpcoreOptimized for 3DS ARM11
Lazy double bufferOnly redraws when view_dirty changes
Glyph advance cache (LRU)Glyph advance width cache to avoid repeated rasterization
EPUB page cachePersistent 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

ArtifactPurpose
3dslibris.3dsxHomebrew Launcher
3dslibris-debug.3dsxBuild with verbose logging (3dslibris.log)
3dslibris.ciaDirect install (includes fonts and resources via romfs)
3dslibris-sdmc.zipSD 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:

1
2
3
4
5
6
7
8
docker build -f docker/Dockerfile.cia -t 3dslibris-build .

docker run --rm \
  -v "$(pwd):/project" -w /project \
  -e DEVKITPRO=/opt/devkitpro \
  -e DEVKITARM=/opt/devkitpro/devkitARM \
  3dslibris-build \
  sh -lc 'make clean && make -j2 && make zip-sdmc && make debug-3dsx && make cia && make source-release'

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

MetricValue
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 stage9 (EPUB, FB2, TXT, RTF, ODT, MOBI, PDF, CBZ, XPS)
Total commits173+
Active development time~2 months intensive
Modules in shared/19 cross-cutting utility headers
Unit test suites20+ 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.