When downloading audiobooks in MP3 format (either via mp3_only or when m4b_mp3_fallback falls back to MP3), the extracted files have generic names like Track - 1.mp3, track01.mp3, or similar names assigned by Libro.fm's CDN packaging. These names carry no semantic information — you can't tell what a file contains without playing it.
The reference implementation (burntcookie90/librofm-downloader) solves this by renaming files using chapter titles that Libro.fm's Download Manifest API already provides.
Solution
After all ZIP parts are downloaded and extracted for an MP3-format book, rename each .mp3 file to include its chapter name from Libro.fm's track metadata. The new filename format is:
This runs as a post-processing step after extraction — no changes to download logic, no new API calls.
User Stories
As a user who downloads audiobooks in MP3 format, I want each MP3 file renamed to its chapter name, so I can navigate my audiobook collection by chapter without needing to open files.
As a user whose book has 100+ tracks, I want track numbers zero-padded to the correct width (e.g., 001 through 105), so alphabetical file sort matches chronological order.
As a user with a book where some tracks lack chapter titles in Libro.fm's data, I want those tracks to fall back to "Chapter N" rather than breaking the entire rename batch.
As a user who prefers the original filenames, I want to opt out via --no-rename-chapters CLI flag or rename_chapters: false in config.
As a user running in m4b_mp3_fallback mode, I want chapter renaming applied when the tool falls back to MP3 downloads, so fallback behavior produces the same quality output as mp3_only.
As a user with special characters in chapter titles (colons, slashes, quotes, etc.), I want filenames sanitized using the existing sanitization rules, so filenames are valid across filesystems.
As a user whose extracted MP3 count doesn't exactly match the API track count (e.g., extra playlist file), I want the tool to rename what it can and warn about the mismatch, rather than failing silently or skipping entirely.
As a user with a book whose ZIPs contain non-zero-padded filenames like Track - 1.mp3, Track - 2.mp3, ..., Track - 10.mp3, I want natural/numeric sorting applied so track alignment is correct regardless of Libro.fm's naming convention.
As a user reading verbose output, I want to see which chapters were renamed and to what, so I can verify correctness.
As a user of this tool, I want this feature enabled by default because chapter names are strictly more useful than generic track names, but I also want the ability to disable it if it causes problems for my workflow.
Implementation Decisions
Data Source
The Download Manifest API (GET /api/v10/download-manifest?isbn=) already returns a tracks array alongside parts. Each track has:
number (int, 1-based)
chapter_title (string or null)
The client module already calls this endpoint and returns the full response dict. The tracks field is currently ignored after extracting parts. No new API calls are needed.
Config & CLI
New boolean field on Config: rename_chapters — defaults to True
tracks: list of dicts from manifest, each with number and chapter_title
book_title: str — the book's title for filename composition
Returns: int — count of files renamed
Placement in pipeline: Called by download_book() after _download_mp3() returns successfully, when config.rename_chapters is truthy and the format strategy produced MP3 files. Not called for M4B downloads.
Padding width = number of digits in the track count (9 tracks → width 1, 10 → width 2, 100+ → width 3)
Both book title and chapter title pass through the existing sanitize() function
Extension preserved from original file (always .mp3)
File-to-Track Matching Algorithm
List all .mp3 files in the output directory
Sort by natural order: extract leading numeric prefix (or first sequence of digits) from each filename stem; sort numerically. Falls back to alphabetic sort if no digits found.
Sort tracks by number field
Pair by index: files[i] ↔ tracks[i]
If counts differ: process min(len(files), len(tracks)) pairs, log warning about the gap
Null/Blank Handling
For any track where chapter_title is None, empty string, or whitespace-only:
Use fallback string: "Chapter {n}" where n is the track's number field
This applies per-track — one missing title does not skip the batch
Sanitization
Reuse the existing sanitize() function from the downloader module. It handles colons, illegal characters, control chars, trailing dots, whitespace, and length capping.
Modules Changed
Module
Change
Config dataclass
Add rename_chapters: bool = True field
Config loader
Read rename_chapters from merged YAML
CLI argument parser
Add --rename-chapters / --no-rename-chapters flag
Downloader module
Add rename_chapters() standalone function + wire into download_book()
No New Dependencies
Pure Python filesystem operations only. No ID3 tag writing in this scope (can be added later via mutagen if desired).
Testing Decisions
What makes a good test here
Tests should verify external behavior: given a set of extracted MP3 files and a tracks list, calling rename_chapters() produces correctly-named files on disk. Tests should NOT depend on internal implementation details like the exact sorting algorithm intermediate state.
Modules to test
Primary: rename_chapters() function
Test scenarios:
Basic rename: N files, N tracks with titles → all renamed correctly
Sanitization: chapter title with colons, slashes, quotes → cleaned in filename
Empty directory / no MP3 files → no-op, no error
Empty tracks list → no-op, no error
Idempotency: running twice on same dir doesn't break anything
Secondary: Config wiring
rename_chapters defaults to True
rename_chapters: false in config prevents rename
--no-rename-chapters CLI flag overrides config
Env var RENAME_CHAPTERS=false respected
Tertiary: Integration in download_book()
m4b_mp3_fallback falling back to MP3 triggers rename when enabled
mp3_only triggers rename when enabled
m4b_only never calls rename (no MP3s produced)
M4B success path does not call rename
Prior art
Existing tests follow the pattern: temp directory, construct mock manifest/ZIP data, call function, assert file existence/names/content. See TestFormatStrategy class in test_downloader.py for MP3 mock patterns, and test_returns_config_dataclass in test_config.py for config field tests.
Out of Scope
ID3 tag writing — not writing metadata inside MP3 files. Can be a follow-up feature using mutagen. The reference implementation supports this via WRITE_TITLE_TAG=true with jaudiotagger.
M4B chapter metadata — not embedding chapter markers into M4B containers. The reference implementation does this during ffmpeg conversion (FFMETADATA chapters), but our tool doesn't do ffmpeg conversion.
Customizable filename templates — not supporting user-configurable rename patterns (e.g., {author} - {chapter}). The format is fixed as {num} - {book} - {chapter}.
Undo/rename-back — not providing a mechanism to restore original filenames.
RENAME_CHAPTERS — file renaming (equivalent to our feature)
WRITE_TITLE_TAG — ID3 title tag writing via jaudiotagger (out of scope)
Their code lives in App.kt:downloadMp3sAndRename() → Utils.kt:createFilenames(). Their sanitization strips < > : / \ | ? *, control chars, trailing dots, caps at 255 chars. Our existing sanitize() is equivalent or stricter.
Risk Assessment
The main risk is file-to-track misalignment if Libro.fm's ZIP internal ordering doesn't match the tracks[] array ordering. Mitigated by natural sort + count-mismatch warning. In practice, both orderings follow track sequence number, so alignment should be reliable.
# PRD: Chapter-Based MP3 File Renaming
## Problem Statement
When downloading audiobooks in MP3 format (either via `mp3_only` or when `m4b_mp3_fallback` falls back to MP3), the extracted files have generic names like `Track - 1.mp3`, `track01.mp3`, or similar names assigned by Libro.fm's CDN packaging. These names carry no semantic information — you can't tell what a file contains without playing it.
The reference implementation ([burntcookie90/librofm-downloader](https://github.com/burntcookie90/librofm-downloader)) solves this by renaming files using chapter titles that Libro.fm's Download Manifest API already provides.
## Solution
After all ZIP parts are downloaded and extracted for an MP3-format book, rename each `.mp3` file to include its chapter name from Libro.fm's track metadata. The new filename format is:
```
{zero-padded-number} - {Book Title} - {Chapter Title}.mp3
```
Example: `01 - Project Hail Mary - The Rock.mp3`
This runs as a post-processing step after extraction — no changes to download logic, no new API calls.
## User Stories
1. As a user who downloads audiobooks in MP3 format, I want each MP3 file renamed to its chapter name, so I can navigate my audiobook collection by chapter without needing to open files.
2. As a user whose book has 100+ tracks, I want track numbers zero-padded to the correct width (e.g., `001` through `105`), so alphabetical file sort matches chronological order.
3. As a user with a book where some tracks lack chapter titles in Libro.fm's data, I want those tracks to fall back to `"Chapter N"` rather than breaking the entire rename batch.
4. As a user who prefers the original filenames, I want to opt out via `--no-rename-chapters` CLI flag or `rename_chapters: false` in config.
5. As a user running in `m4b_mp3_fallback` mode, I want chapter renaming applied when the tool falls back to MP3 downloads, so fallback behavior produces the same quality output as `mp3_only`.
6. As a user with special characters in chapter titles (colons, slashes, quotes, etc.), I want filenames sanitized using the existing sanitization rules, so filenames are valid across filesystems.
7. As a user whose extracted MP3 count doesn't exactly match the API track count (e.g., extra playlist file), I want the tool to rename what it can and warn about the mismatch, rather than failing silently or skipping entirely.
8. As a user with a book whose ZIPs contain non-zero-padded filenames like `Track - 1.mp3`, `Track - 2.mp3`, ..., `Track - 10.mp3`, I want natural/numeric sorting applied so track alignment is correct regardless of Libro.fm's naming convention.
9. As a user reading verbose output, I want to see which chapters were renamed and to what, so I can verify correctness.
10. As a user of this tool, I want this feature enabled by default because chapter names are strictly more useful than generic track names, but I also want the ability to disable it if it causes problems for my workflow.
## Implementation Decisions
### Data Source
The **Download Manifest** API (`GET /api/v10/download-manifest?isbn=`) already returns a `tracks` array alongside `parts`. Each track has:
- `number` (int, 1-based)
- `chapter_title` (string or null)
The client module already calls this endpoint and returns the full response dict. The `tracks` field is currently ignored after extracting `parts`. No new API calls are needed.
### Config & CLI
- New boolean field on `Config`: `rename_chapters` — defaults to `True`
- Env var: `RENAME_CHAPTERS`
- CLI flag: `--rename-chapters` / `--no-rename-chapters`
- Follows the established pattern used by `download_extras` and `download_covers`
### Architecture
A standalone function `rename_chapters()` in the downloader module:
**Signature:** `rename_chapters(output_dir, tracks, book_title) -> int`
- `output_dir`: Path — directory containing extracted MP3 files
- `tracks`: list of dicts from manifest, each with `number` and `chapter_title`
- `book_title`: str — the book's title for filename composition
- Returns: int — count of files renamed
**Placement in pipeline:** Called by `download_book()` after `_download_mp3()` returns successfully, when `config.rename_chapters` is truthy and the format strategy produced MP3 files. Not called for M4B downloads.
### Filename Format
```
{padded_number} - {sanitized_book_title} - {sanitized_chapter_title}.mp3
```
- Padding width = number of digits in the track count (9 tracks → width 1, 10 → width 2, 100+ → width 3)
- Both book title and chapter title pass through the existing `sanitize()` function
- Extension preserved from original file (always `.mp3`)
### File-to-Track Matching Algorithm
1. List all `.mp3` files in the output directory
2. Sort by **natural order**: extract leading numeric prefix (or first sequence of digits) from each filename stem; sort numerically. Falls back to alphabetic sort if no digits found.
3. Sort `tracks` by `number` field
4. Pair by index: `files[i]` ↔ `tracks[i]`
5. If counts differ: process `min(len(files), len(tracks))` pairs, log warning about the gap
### Null/Blank Handling
For any track where `chapter_title` is `None`, empty string, or whitespace-only:
- Use fallback string: `"Chapter {n}"` where `n` is the track's `number` field
- This applies per-track — one missing title does not skip the batch
### Sanitization
Reuse the existing `sanitize()` function from the downloader module. It handles colons, illegal characters, control chars, trailing dots, whitespace, and length capping.
### Modules Changed
| Module | Change |
|--------|--------|
| Config dataclass | Add `rename_chapters: bool = True` field |
| Config loader | Read `rename_chapters` from merged YAML |
| CLI argument parser | Add `--rename-chapters` / `--no-rename-chapters` flag |
| Downloader module | Add `rename_chapters()` standalone function + wire into `download_book()` |
### No New Dependencies
Pure Python filesystem operations only. No ID3 tag writing in this scope (can be added later via `mutagen` if desired).
## Testing Decisions
### What makes a good test here
Tests should verify external behavior: given a set of extracted MP3 files and a tracks list, calling `rename_chapters()` produces correctly-named files on disk. Tests should NOT depend on internal implementation details like the exact sorting algorithm intermediate state.
### Modules to test
**Primary: `rename_chapters()` function**
Test scenarios:
- Basic rename: N files, N tracks with titles → all renamed correctly
- Zero-padding: 5 tracks → no padding (`1`-`5`); 12 tracks → 2-digit padding (`01`-`12`)
- Fallback for null/blank titles: some tracks missing `chapter_title` → `"Chapter N"` used
- All titles blank/null → all get `"Chapter N"` fallback
- Natural sort: files named `Track - 1.mp3` through `Track - 10.mp3` sorted numerically, not alphabetically
- Count mismatch: fewer files than tracks → rename what we can, rest untouched
- Count mismatch: extra non-MP3 files present → filtered out, MP3s renamed correctly
- Sanitization: chapter title with colons, slashes, quotes → cleaned in filename
- Empty directory / no MP3 files → no-op, no error
- Empty tracks list → no-op, no error
- Idempotency: running twice on same dir doesn't break anything
**Secondary: Config wiring**
- `rename_chapters` defaults to `True`
- `rename_chapters: false` in config prevents rename
- `--no-rename-chapters` CLI flag overrides config
- Env var `RENAME_CHAPTERS=false` respected
**Tertiary: Integration in `download_book()`**
- `m4b_mp3_fallback` falling back to MP3 triggers rename when enabled
- `mp3_only` triggers rename when enabled
- `m4b_only` never calls rename (no MP3s produced)
- M4B success path does not call rename
### Prior art
Existing tests follow the pattern: temp directory, construct mock manifest/ZIP data, call function, assert file existence/names/content. See `TestFormatStrategy` class in test_downloader.py for MP3 mock patterns, and `test_returns_config_dataclass` in test_config.py for config field tests.
## Out of Scope
- **ID3 tag writing** — not writing metadata inside MP3 files. Can be a follow-up feature using `mutagen`. The reference implementation supports this via `WRITE_TITLE_TAG=true` with jaudiotagger.
- **M4B chapter metadata** — not embedding chapter markers into M4B containers. The reference implementation does this during ffmpeg conversion (FFMETADATA chapters), but our tool doesn't do ffmpeg conversion.
- **Customizable filename templates** — not supporting user-configurable rename patterns (e.g., `{author} - {chapter}`). The format is fixed as `{num} - {book} - {chapter}`.
- **Undo/rename-back** — not providing a mechanism to restore original filenames.
## Further Notes
### Reference Implementation Details
The reference implementation ([burntcookie90/librofm-downloader](https://github.com/burntcookie90/librofm-downloader)) implements this in Kotlin with two toggles:
- `RENAME_CHAPTERS` — file renaming (equivalent to our feature)
- `WRITE_TITLE_TAG` — ID3 title tag writing via jaudiotagger (out of scope)
Their code lives in `App.kt:downloadMp3sAndRename()` → `Utils.kt:createFilenames()`. Their sanitization strips `< > : / \ | ? *`, control chars, trailing dots, caps at 255 chars. Our existing `sanitize()` is equivalent or stricter.
### Risk Assessment
The main risk is file-to-track misalignment if Libro.fm's ZIP internal ordering doesn't match the `tracks[]` array ordering. Mitigated by natural sort + count-mismatch warning. In practice, both orderings follow track sequence number, so alignment should be reliable.
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
PRD: Chapter-Based MP3 File Renaming
Problem Statement
When downloading audiobooks in MP3 format (either via
mp3_onlyor whenm4b_mp3_fallbackfalls back to MP3), the extracted files have generic names likeTrack - 1.mp3,track01.mp3, or similar names assigned by Libro.fm's CDN packaging. These names carry no semantic information — you can't tell what a file contains without playing it.The reference implementation (burntcookie90/librofm-downloader) solves this by renaming files using chapter titles that Libro.fm's Download Manifest API already provides.
Solution
After all ZIP parts are downloaded and extracted for an MP3-format book, rename each
.mp3file to include its chapter name from Libro.fm's track metadata. The new filename format is:Example:
01 - Project Hail Mary - The Rock.mp3This runs as a post-processing step after extraction — no changes to download logic, no new API calls.
User Stories
001through105), so alphabetical file sort matches chronological order."Chapter N"rather than breaking the entire rename batch.--no-rename-chaptersCLI flag orrename_chapters: falsein config.m4b_mp3_fallbackmode, I want chapter renaming applied when the tool falls back to MP3 downloads, so fallback behavior produces the same quality output asmp3_only.Track - 1.mp3,Track - 2.mp3, ...,Track - 10.mp3, I want natural/numeric sorting applied so track alignment is correct regardless of Libro.fm's naming convention.Implementation Decisions
Data Source
The Download Manifest API (
GET /api/v10/download-manifest?isbn=) already returns atracksarray alongsideparts. Each track has:number(int, 1-based)chapter_title(string or null)The client module already calls this endpoint and returns the full response dict. The
tracksfield is currently ignored after extractingparts. No new API calls are needed.Config & CLI
Config:rename_chapters— defaults toTrueRENAME_CHAPTERS--rename-chapters/--no-rename-chaptersdownload_extrasanddownload_coversArchitecture
A standalone function
rename_chapters()in the downloader module:Signature:
rename_chapters(output_dir, tracks, book_title) -> intoutput_dir: Path — directory containing extracted MP3 filestracks: list of dicts from manifest, each withnumberandchapter_titlebook_title: str — the book's title for filename compositionPlacement in pipeline: Called by
download_book()after_download_mp3()returns successfully, whenconfig.rename_chaptersis truthy and the format strategy produced MP3 files. Not called for M4B downloads.Filename Format
sanitize()function.mp3)File-to-Track Matching Algorithm
.mp3files in the output directorytracksbynumberfieldfiles[i]↔tracks[i]min(len(files), len(tracks))pairs, log warning about the gapNull/Blank Handling
For any track where
chapter_titleisNone, empty string, or whitespace-only:"Chapter {n}"wherenis the track'snumberfieldSanitization
Reuse the existing
sanitize()function from the downloader module. It handles colons, illegal characters, control chars, trailing dots, whitespace, and length capping.Modules Changed
rename_chapters: bool = Truefieldrename_chaptersfrom merged YAML--rename-chapters/--no-rename-chaptersflagrename_chapters()standalone function + wire intodownload_book()No New Dependencies
Pure Python filesystem operations only. No ID3 tag writing in this scope (can be added later via
mutagenif desired).Testing Decisions
What makes a good test here
Tests should verify external behavior: given a set of extracted MP3 files and a tracks list, calling
rename_chapters()produces correctly-named files on disk. Tests should NOT depend on internal implementation details like the exact sorting algorithm intermediate state.Modules to test
Primary:
rename_chapters()functionTest scenarios:
1-5); 12 tracks → 2-digit padding (01-12)chapter_title→"Chapter N"used"Chapter N"fallbackTrack - 1.mp3throughTrack - 10.mp3sorted numerically, not alphabeticallySecondary: Config wiring
rename_chaptersdefaults toTruerename_chapters: falsein config prevents rename--no-rename-chaptersCLI flag overrides configRENAME_CHAPTERS=falserespectedTertiary: Integration in
download_book()m4b_mp3_fallbackfalling back to MP3 triggers rename when enabledmp3_onlytriggers rename when enabledm4b_onlynever calls rename (no MP3s produced)Prior art
Existing tests follow the pattern: temp directory, construct mock manifest/ZIP data, call function, assert file existence/names/content. See
TestFormatStrategyclass in test_downloader.py for MP3 mock patterns, andtest_returns_config_dataclassin test_config.py for config field tests.Out of Scope
mutagen. The reference implementation supports this viaWRITE_TITLE_TAG=truewith jaudiotagger.{author} - {chapter}). The format is fixed as{num} - {book} - {chapter}.Further Notes
Reference Implementation Details
The reference implementation (burntcookie90/librofm-downloader) implements this in Kotlin with two toggles:
RENAME_CHAPTERS— file renaming (equivalent to our feature)WRITE_TITLE_TAG— ID3 title tag writing via jaudiotagger (out of scope)Their code lives in
App.kt:downloadMp3sAndRename()→Utils.kt:createFilenames(). Their sanitization strips< > : / \ | ? *, control chars, trailing dots, caps at 255 chars. Our existingsanitize()is equivalent or stricter.Risk Assessment
The main risk is file-to-track misalignment if Libro.fm's ZIP internal ordering doesn't match the
tracks[]array ordering. Mitigated by natural sort + count-mismatch warning. In practice, both orderings follow track sequence number, so alignment should be reliable.