Skip to content

About

A Docker to automatically convert all your current and future Audiobooks within Audiobookshelf to the single file .m4b format.

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

abs-autoconverter

Automatically converts audiobooks in Audiobookshelf to single-file .m4b, using Audiobookshelf's own built-in encoder through its API. It can run on a different host than Audiobookshelf.

This is a hardened fork of cutzenfriend/docker-absautoconverter. It no longer tracks upstream: the code is split into modules with unit tests, the image runs as non-root on node:24-alpine, and configuration is strictly validated.

How it works

Each cycle (cron, default every hour at minute 20):

  1. Read Audiobookshelf's task list. If it can't be read, the whole cycle is skipped. Free slots are MAX_PARALLEL_CONVERSIONS minus the encodes already running.
  2. Resolve the outcome of encodes and embeds started in earlier cycles. Audiobookshelf drops finished tasks from its list, so the outcome is read from the item's files: a single .m4b means success. Successes are logged (and optionally written to CONVERSION_LOG_PATH); failures count toward MAX_CONVERSION_FAILURES.
  3. Page through each library's multi-file books and start merges until the slots are used. Items that are converting, awaiting an outcome check, or blocked by failures are skipped.
  4. Optionally, scan single-file books: re-encode them (CONVERT_SINGLE_FILES), convert non-m4b files (CONVERT_NON_M4B), or embed metadata (EMBED_METADATA).

Only one cycle runs at a time. If a cycle is still running when the next one is due, the new one is skipped.

Running

Images are built by the Build image workflow and pushed to ghcr.io/upmcplanetracker/docker-absautoconverter. Only linux/amd64 is built.

  • Manual (Actions → Build image → Run workflow): always builds; pushes latest, the short commit SHA, and an optional extra tag.
  • Tag push (git tag v2.1.0 && git push origin v2.1.0): builds only if 2.1.0 isn't already in GHCR; pushes 2.1.0, 2.1, latest and the short SHA. Re-pushing an existing version tag is a no-op.

Podman Quadlet

See quadlet/abs-autoconverter.container. It reads the token from a Podman secret (TOKEN_FILE), runs with a read-only root filesystem, maps the container user to your host user, and uses the built-in health check.

Docker Compose

See docker-compose.yml.

Mount /data if you use FAILURE_PERSIST_PATH or CONVERSION_LOG_PATH. The container runs as uid 1000 (node), so the host directory must be writable by that uid.

The API token must belong to an Audiobookshelf admin user. It is sent only in the Authorization: Bearer header, never in a URL.

Environment variables

Variable Default Description
DOMAIN required Audiobookshelf URL, e.g. https://abs.example.com (a trailing slash is fine)
LIBRARY_ID required Library ID(s), comma-separated
TOKEN required* Audiobookshelf API token
TOKEN_FILE — *Alternative to TOKEN: path to a file containing the token (Docker/Podman secrets). Set only one of the two
MAX_PARALLEL_CONVERSIONS 5 Maximum concurrent encodes, counting ones already running in Audiobookshelf
CRON_SETTING 20 * * * * Cron schedule (validated at startup)
RUN_ON_START false Also run one cycle immediately at startup
BITRATE 128k Encode bitrate (64k, 64 and 64K are all accepted), or source to match each book's source bitrate
BITRATE_CAP — Use the lower of the source bitrate and this cap; never upscales. Overrides BITRATE
CODEC Audiobookshelf default (aac) Codec passed to the encoder
MAX_CONVERSION_FAILURES 3 Failed attempts before a book is skipped
FAILURE_PERSIST_PATH — JSON file that keeps failure counts across restarts, e.g. /data/failures.json
SCAN_CACHE_PATH — JSON file that remembers books already checked and needing nothing, so a restart doesn't re-inspect the whole library, e.g. /data/scan-cache.json
CONVERSION_LOG_PATH — JSON-lines log of completed conversions and embeds, e.g. /data/conversions.log
CONVERT_SINGLE_FILES false Re-encode single-file books more than 10% above the target (BITRATE_CAP, else BITRATE). Disabled with BITRATE=source and no cap
CONVERT_NON_M4B false Convert single-file books that aren't .m4b, whatever their bitrate
EMBED_METADATA false Quick-embed Audiobookshelf metadata into single-file books whose tags differ
DO_NOT_MERGE_M4B false Skip multi-file books that contain any .m4b part
HTTP_TIMEOUT_MS 30000 Timeout for every Audiobookshelf API request
LOG_PROGRESS true Log live progress (33% and 66%) and report completions as soon as they happen, via Audiobookshelf's Socket.IO feed. Needs an admin user's API key
SINGLE_FILE_CHECK_BUDGET 500 Maximum single-file books inspected per cycle. Set it above your library size to check everything in one cycle
MAX_PENDING_EMBEDS 10 Maximum metadata embeds waiting in Audiobookshelf's queue at once
HEALTH_MAX_CYCLE_MINUTES 180 The health check fails if one cycle runs longer than this
TZ UTC Time zone for log timestamps and the cron schedule

Boolean variables accept true/1/yes/on and false/0/no/off. Any other value is a configuration error. All errors are reported together at startup, and the container exits with code 1.

Failure tracking

A book is skipped after MAX_CONVERSION_FAILURES failed attempts. An attempt counts as failed if:

  • the encode finished but the book doesn't have a single m4b afterwards, or
  • Audiobookshelf rejected the request with a 4xx error.

Network errors and 5xx responses don't count, so an Audiobookshelf outage can't block books.

To retry a skipped book, fix its metadata in Audiobookshelf. Each failure entry stores a fingerprint of the book's metadata. When the metadata changes, the count is reset automatically on the next cycle, and no restart is needed. A successful conversion clears the entry. You can also delete the entry, or the whole file.

{
  "li_abc123": { "title": "My Broken Audiobook", "count": 3, "metadataKey": "9f2c1e0a7b3d4c55" }
}

The file is written atomically (temp file, then rename). If it is ever unreadable, it is moved aside to failures.json.corrupt-<timestamp> and a warning is logged, rather than being silently reset. Files from older versions (plain numbers) still load.

Conversion log

With CONVERSION_LOG_PATH, each completed encode appends one line:

{"type":"encode","title":"My Audiobook","itemId":"li_abc123","startedAt":"2026-07-13T10:20:00.000Z","finishedAt":"2026-07-13T11:20:00.000Z","requestedBitrate":"64k","bitrateMatched":true,"before":{"fileCount":12,"path":"/audiobooks/Author/My Audiobook","codec":"mp3","bitrate":"128k","sizeBytes":412316860,"channels":2},"after":{"fileCount":1,"path":"/audiobooks/Author/My Audiobook/My Audiobook.m4b","codec":"aac","bitrate":"64k","sizeBytes":206158430,"channels":2}}
  • bitrateMatched is true when the result is within 10% (and at least 8 kbps) of the requested bitrate.
  • sizeBytes is the total size of the item's audio files as Audiobookshelf reports it, or null if any file's size is unknown.
  • Embeds are logged with "type":"embed-metadata" and updatedFields.
  • With LOG_PROGRESS=true, outcomes are checked as soon as Audiobookshelf reports the task finished; otherwise on the cycle after the task ends. Before judging an encode, the converter asks Audiobookshelf to rescan the item: ABS writes the new m4b over the original in place without rescanning, so its stored bitrate can otherwise still describe the old file. Pending outcomes are kept in memory, so a restart in the middle of an encode loses that one entry.

Single-file books

  • Multi-file books always get slots first; single-file conversions use whatever slots are left.
  • MAX_PARALLEL_CONVERSIONS counts only encodes (Audiobookshelf's running encode tasks plus those this converter starts). Metadata embeds don't use slots: at most MAX_PENDING_EMBEDS are queued at once, and Audiobookshelf runs them one at a time.
  • At most SINGLE_FILE_CHECK_BUDGET books are inspected per cycle. Books that need nothing are cached until they change in Audiobookshelf.
  • Without SCAN_CACHE_PATH that cache is in memory, so every restart (including AutoUpdate image pulls) re-inspects the library from the start. With it, the cache is saved once per cycle (atomically, like the failure file) and loaded at startup.
  • The cache file records a fingerprint of BITRATE, BITRATE_CAP, CODEC, CONVERT_SINGLE_FILES, CONVERT_NON_M4B, EMBED_METADATA and DO_NOT_MERGE_M4B. If any of these change, the cache is discarded at startup and every book is checked again. Deleting the file has the same effect.
  • A file's source bitrate is the lower of Audiobookshelf's stored bitRate and the file's average rate (size × 8 ÷ duration). Audiobookshelf's value can be stale after a re-encode. The average includes cover art and container overhead, so it never understates the audio. Log lines show both when they disagree, e.g. 66k (Audiobookshelf reports 126k).
  • Every book this converter encodes is recorded with the bitrate it asked for (encoded in the cache file). A recorded book is never converted again while that bitrate is at or below the current target (+10%), whatever Audiobookshelf reports, so books can't be re-encoded in a loop. The record is written when the encode starts and removed if the outcome check finds the encode failed. It survives setting changes, and lowering BITRATE_CAP below a recorded bitrate allows one re-encode at the new target. Without SCAN_CACHE_PATH the record is lost on restart.
  • If the container stops during an encode that then fails, its record stays and the book isn't retried. Remove its id from encoded in the cache file to retry it.
  • EMBED_METADATA compares title, author, album (title plus subtitle), narrator, genre, year and series. Fields that are empty in Audiobookshelf are ignored.
    • After an embed, the item is rescanned and compared again.
    • Books stored directly in the library root, not in their own folder, can't be rescanned, so they are skipped.
    • A book that gets converted isn't embedded separately, because the conversion writes its metadata.

Multiple libraries

Set LIBRARY_ID to a comma-separated list (LIBRARY_ID=id1,id2). Libraries are processed in that order, sharing the same conversion slots and check budget. Where the libraries live on disk doesn't matter: the converter only asks Audiobookshelf for each library's items by ID, and Audiobookshelf encodes the files in place.

To find an ID, open the library in the web UI (the URL is /library/<id>/...), or call GET /api/libraries.

Log lines about a library are prefixed with its name and the first 8 characters of its ID, e.g. [Audiobooks ed02e785]. The names are looked up once at startup. If a configured ID isn't visible to the API key, a warning is logged and the short ID is used instead.

Progress

Audiobookshelf doesn't include progress in its task list. It pushes task_progress and task_finished events over Socket.IO to admin users. With LOG_PROGRESS=true (the default), the converter keeps that connection open and logs four lines for each conversion or metadata embed it starts:

[Audiobooks ed02e785] Starting single-file conversion: Dracula (aac @ 196k -> m4b @ 64k)
[Audiobooks ed02e785] Encoding: Dracula ███░░░░░░░ 33% (~3m 29s left, ETA 12:12)
[Audiobooks ed02e785] Encoding: Dracula ███████░░░ 66% (~1m 45s left, ETA 12:12)
[Audiobooks ed02e785] Conversion completed: Dracula (1 file(s), aac @ 196k -> aac @ 65k), 548.2 MB -> 182.0 MB, 67% smaller, took 4m 53s

[Audiobooks ed02e785] Starting metadata embed: Crown of Midnight (differs in: title, album)
[Audiobooks ed02e785] Embedding metadata: Crown of Midnight ███░░░░░░░ 33%
[Audiobooks ed02e785] Embedding metadata: Crown of Midnight ███████░░░ 66%
[Audiobooks ed02e785] Metadata embedded: Crown of Midnight (updated: title, album)

The completion line is written as soon as Audiobookshelf reports the task finished, along with the CONVERSION_LOG_PATH entry, instead of on the next cycle. For an embed, the item is rescanned and its tags compared first, so "Metadata embedded" means the new tags were read back. If Audiobookshelf reports the task as failed, its reason is logged and the failure counts as usual. With LOG_PROGRESS=false, there are no progress lines and completions are reported on the next cycle.

The ETA on encode progress lines is linear: the time so far, scaled to the share still to do. It is usually within a minute or two, but it is rough. It leaves out the few seconds Audiobookshelf spends moving the m4b into place after 100%, and with several encodes running at once, the rest speed up as others finish, so it tends to run a little late. Embeds take seconds, so their lines have no ETA. ETAs past midnight include the date.

The completion line shows the size change (left out when Audiobookshelf doesn't report a file size) and how long the conversion took, from the moment Audiobookshelf accepted it.

When the last conversion or embed in flight finishes, one summary line covers everything started since the converter was last idle, followed by the next scheduled run:

All work finished: 5 converted (2.1 GB -> 1.0 GB, 52% smaller), 5 metadata embed(s), 0 failed
Next run: 2026-12-01 18:17:00

The total size is left out if any conversion in the batch had no size. Next run is also logged after every cycle.

Container logs aren't a terminal, so each step is a new line, not a bar redrawn in place. If the API key's user isn't an admin, the socket login is rejected: a warning is logged once, and progress is turned off while conversions carry on. Connection drops are logged once and retried in the background. A DOMAIN with a sub-path (https://host/audiobookshelf) connects to /audiobookshelf/socket.io.

Health check

The process writes a heartbeat to /tmp/abs-autoconverter-health.json every 30 seconds, and healthcheck.js reads it. The container is reported unhealthy when:

  • the heartbeat is more than 90 seconds old, or
  • a cycle has been running longer than HEALTH_MAX_CYCLE_MINUTES.

With a read-only root filesystem, /tmp must be a tmpfs. Podman does this by default; with Compose, add tmpfs: [/tmp].

Podman ignores a Dockerfile HEALTHCHECK for OCI images, so the Quadlet example sets HealthCmd itself.

Development

npm ci
npm run lint
npm test        # node:test unit tests, no network needed

Layout:

  • index.js: startup, scheduling, signals, heartbeat
  • healthcheck.js: container health check
  • src/config.js: environment parsing and validation
  • src/abs-client.js: Audiobookshelf API client
  • src/failures.js: failure tracking
  • src/media.js: pure helpers for bitrate choice, tag comparison and outcome evaluation
  • src/converter.js: the conversion cycle

Acknowledgements

About

A Docker to automatically convert all your current and future Audiobooks within Audiobookshelf to the single file .m4b format.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages