djdembeck/m4b-merge
About
A high-performance Rust CLI to merge audiobooks into consistently tagged M4B files. Zero runtime deps, native chapter embedding, and 10x faster processing.
Developer ToolsMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- +2
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
Originalm4b-merge
A blazing fast CLI tool for merging audiobook files into sorted, tagged M4B files.
m4b-merge takes split audio files (MP3, M4A, or M4B) and merges them into a single, consistently tagged M4B file. Originally written in Python and rewritten in Rust, it provides high-performance processing with zero-copy merging for files of the same format, ensuring the original bitrate and sample rate are preserved.
The tool automates metadata lookup by ASIN or AudiobookDB book ID through AudiobookDB — a community-maintained audiobook metadata database with proper book/release separation and moderated contributions — embeds high-resolution cover art, and maintains chapter markers. The looked-up provider's chapters are preferred, the first input file's own chapters are used when the provider has none, and only when both are empty is one chapter per input track generated instead.
Install
Docker (Fastest Path)
Choose a published vX.Y.Z tag or digest from the release you intend to run, and set IMAGE to its full GHCR reference. The workflow does not maintain a rolling Docker latest alias, so pin an explicit tag. GitHub's Latest release label is independent: it tracks the highest published stable version and is not advanced by lower-version delayed completions.
: "${IMAGE:?Set IMAGE to a published GHCR version tag or digest}"
docker run --rm \
-v /path/to/input:/input \
-v /path/to/output:/output \
"$IMAGE" \
-i /input/book_folder/ -o /output
Pre-built Binaries
Download the release for your platform from the releases page. Select the asset by its exact full name — never by the first asset containing linux:
| Asset | Platform | Linkage | Runtime prerequisites |
|---|---|---|---|
m4b-merge-linux |
Linux x86-64 | static musl | FFmpeg, CA roots, resolver files |
m4b-merge-linux-arm64 |
Linux ARM64 | static musl | FFmpeg, CA roots, resolver files |
m4b-merge-macos |
macOS | — | FFmpeg (CA roots and name resolution come from the platform) |
m4b-merge-windows.exe |
Windows | — | FFmpeg (CA roots and name resolution come from the platform) |
From this release forward no GNU-linked Linux asset is produced. For
v2.0.0 only, m4b-merge-linux is the original GNU binary; the assets
added to that release are the static-musl x86-64 asset
m4b-merge-linux-musl and the ARM64 asset
m4b-merge-linux-arm64.
From Source
Requires FFmpeg installed and available in your PATH.
cargo install --path .
Usage
Basic CLI interaction. Use m4b-merge --help for all available flags.
Basic Merging
Merge all audio files in a directory into a single M4B.
m4b-merge -i input/book_folder/
Metadata & High-Resolution Covers
Provide a metadata ID (ASIN or AudiobookDB book ID) to automatically fetch metadata from AudiobookDB. (--metadata-source audnexus remains available for the legacy Audnexus API.)
m4b-merge -i input/book_folder/ -a B012345678
The looked-up edition is release-first: the selected release's title, subtitle,
and release date win when present, and the book-level title/subtitle are the
fallback (year falls back to the book copyright, then original publication; the
subtitle falls back to the book subtitle, then the book's disambiguation). This
applies to the legacy --metadata-id CLI path as well as the --job
input_provider path, so for reissued editions the embedded title and year are
the release's. An explicit release_id that the book does not carry is a
diagnosed failure — never a silent fall back to the book's first release.
Non-US Audible books need --region with --metadata-source audnexus (default us; accepted: au ca de es fr in it jp us uk).
Custom Output & Organization
Specify a custom output directory and organization template.
m4b-merge -i input/book_folder/ \
-o /my/library \
-p "{author}/{series_name} {series_position} - {title}"
Advanced Processing
Use --dry-run to preview operations, --num-cpus to control parallelism, and --completed-directory to move processed files.
m4b-merge -i input/book_folder/ \
--dry-run \
--num-cpus 8 \
--completed-directory /path/to/done
Authoritative Job File
Process a book from a versioned JSON job file. The job is the single source
of truth for the metadata base, the manual overrides, and the output; it is
mutually exclusive with -i, -o, -p, -a, and --completed-directory.
m4b-merge --job job.json
The job selects its metadata base exactly one of two ways:
input_provider— an explicit catalog id (book_id, plus an exactrelease_idforaudiobookdb). The catalog is the authority; an unresolvable id, a release the book does not carry, or a missing client fails the job before any file is touched.input_supplied— the values are authoritative as-is; no catalog lookup is attempted and the job runs fully offline. An optionalbook_idnames the canonical AudiobookDB book id for the{book_id}token when the caller already knows it; it is used as-is, never authenticated against a catalog, and a blank value is treated as absent. Optionalasin,release_id, andmetadata_idwork the same way: they name the book's Audible ASIN, the selected AudiobookDB release id, and the book's identifier for the{asin},{release_id}, and{metadata_id}tokens. They are naming data only — used as-is, never looked up, with no authentication — and a blank value is treated as absent (the token contributes no path segment).
On top of the base, an optional overrides object replaces individual
fields; present non-blank values win over the base. overrides.book_id
applies only to a supplied base: in provider mode the catalog-resolved
book id is authoritative and a conflicting override is ignored.
{
"schema_version": 1,
"inputs": ["/data/book/track1.m4a"],
"input_supplied": {
"title": "The Great Gatsby",
"authors": ["F. Scott Fitzgerald"]
},
"output_root": "/library",
"path_format": "{author}/{title}",
"processing_stamp": "bragibooks_v1",
"title": "write",
"subtitle": "preserve",
"authors": "write",
"year": "clear",
"cover": "write_url",
"chapters": "write"
}
Field semantics:
inputs(required, non-empty) — the audio files to merge.output_root(required) — the output directory root; created if missing.path_format(optional) — output template inside the root; default{author}/{title}(see Path Format Variables).source(optional) —{"source": "audiobookdb" | "audnexus", "api_url": "…", "region": "…"}; defaults to the CLI defaults when omitted in provider mode, and is irrelevant in supplied mode.completed_directory(optional) — after successful processing, the source files are moved here. In job mode the CLI--completed-directoryflag is rejected (the job file owns it), so omitting this field means the sources are not moved.overrides(optional) — same shape asinput_supplied; present non-blank values win over the base.title/subtitle—preserve(default),clear, orwrite. Awritewrites the effective metadata's value (the title, and the subtitle when one is present) — the same strings that name the output path, so the tag cannot diverge from the file name — and fails the job if that value is blank. Title and subtitle share the©nam/©albatom pair: a write of one component preserves the other, andclearof one removes only that component. Clearing the title while the subtitle survives is the subtitle-only state: the subtitle is written alone to©namand©albis removed (a base title no longer exists). A re-run that preserves both components leaves the subtitle-only file unchanged, and a job that preserves the title while writing or clearing the subtitle is refused with a diagnosed error before mutation, because the state has no base title to preserve.preserverecovers the component from the existing tags; a file whose tags cannot establish it fails before mutation rather than erasing data. A decorated album is still understood when the title is written: a recognized leading series bracket ("[Series 02] - Title") or trailing parenthetical qualifier ("Title (Unabridged)") is stripped, and the base must then equal©nam(no subtitle) or extend it by" - "(the subtitle). Parens inside the title do not block the qualifier strip: a stray)such as the one in"Smile :-) Today (Unabridged)"is title text, not a group. A terminal qualifier that is itself unbalanced, or a title portion that opens a(it never closes, is not a recognized decoration and still refuses. A preserved subtitle paired with a written title is absent when the existing atoms carry none (the decorated base equals©nam, or the album has no©nam); the written title becomes both©namand©alb. A pair that stays ambiguous fails before mutation instead of dropping tag data.authors,narrators,series,description,genres,year—preserve(default),write, orclear. Awriterequires the effective value to be non-blank, and fails the job if it is not.preservefields keep the file's existing values even when the effective metadata lacks them.processing_stamp— optional. Omit it or set it tonullto keep the current behavior. The only accepted non-null value is"bragibooks_v1", which--capabilitiesadvertises. An unsupported value fails while the engine loads the job, before it changes source media or creates output files. The preset replaces one UTF-8, file-level MP4 freeform atom for each ofBRAGIBOOKS_PROCESSORandBRAGIBOOKS_AUDIO_ACTIONundermean=org.bragibooks. It writes both atoms to staging before publication. The action isstream_copywhen processing keeps the encoded audio andtranscodewhen processing encodes output audio. When it is the only stamp request and the other policies preserve, it changes only these two atoms. Stamp writes use metadata-only I/O, so they do not rewrite chapters. Embedded cover data is retained.engine_stamp— optional boolean, defaultfalse. Whentrue, the engine replacesM4B_MERGE_PROCESSOR,M4B_MERGE_VERSION, andM4B_MERGE_AUDIO_ACTIONundermean=org.m4b-merge. The processor ism4b-merge, the version matches--version, and the action describes the audio operation this run used. This option is separate fromprocessing_stamp; both can be requested. The machine result reports anengine_stampobject on the published audio artifact only when this job wrote it and the published file still matches at final reporting. Existing engine atoms on inputs do not produce a result. The stamp records historical run attribution. It does not prove provenance or file authenticity.custom_stamps— optional array, default empty. Each entry has string fieldsnamespace,name, andvalue. The namespace must use reverse-DNS style ASCII labels. The namespace and name are each limited to 128 bytes; the name must be nonblank and contain no control characters. The value is limited to 4096 UTF-8 bytes and cannot contain NUL. The list accepts at most 64 entries. Exact(namespace, name)pairs must be unique.org.m4b-mergeandorg.bragibooksare reserved, with case-insensitive matching. A request replaces only that exact freeform key. Other values remain unchanged. Custom values are caller-supplied strings; the engine does not verify their claims or include them in machine results or logs. Invalid stamp requests fail before output creation or media changes.
engine_stamp and custom_stamps are new job keys. Older job readers reject
unknown fields. Read --capabilities first and include each key only when its
capability is true.
cover—write_url(default; embeds the provider cover URL when the resolved metadata carries one — the legacy baseline),{"write": "/absolute/path"}(local file; the path must lie inside the job'soutput_root, which is the only asset area the job owns, and must be at most 5 MiB — a path that escapes the root, including via a symlink, is rejected before any read),{"write_url": "https://…"}(override, under the existing SSRF guards),preserve(a single natively-copyable input file only; keeps the source M4B's embedded cover without a download), orclear(removes the cover). Apreservecover policy on a multi-file group is rejected; a strict preserve promise is only possible with a single natively-copyable input file.chapters—write(default; embeds chapters and writes thechapters.txtsidecar: an explicit{"write": {"chapters": [{"title", "start_millis", "duration_millis"}]}}list when given, otherwise the resolved chapters; an empty explicit list clears, while a list that resolved to nothing leaves the source chapters untouched),preserve(a single natively-copyable input file only; skips all chapter mutation so the source chapters survive), orclear(removes existing chapters, no sidecar). Apreservechapters policy on a multi-file group is rejected; a strict preserve promise is only possible with a single natively-copyable input file.
The output path is output_root + the (sanitized) template, so the same job
against the same book always lands on the same path — no worker-time catalog
rematching is needed by callers.
Preview (--job-preview)
A non-mutating preview of a job:
m4b-merge --job job.json --job-preview
It resolves the effective metadata exactly as execution does (base + overrides; a supplied job performs no catalog request) and the same parsed template with the same resolver, printing the exact sanitized relative output path (plus the effective metadata) as JSON. It creates no directories, writes no media, reserves no names, and makes no success promise: collisions and media errors are execution-time. The previewed path is the path execution produces, provided the metadata is the same — a provider preview that refetches at execution is advisory unless the caller captures the supplied resolved metadata (supplied mode has no fetch, so its preview is exact).
Machine results (--machine)
Machine-readable execution results for a job:
m4b-merge --job job.json --machine
Stable JSON on stdout only — all logs and progress go to stderr, so the
document parses cleanly on success and on failure. Three rejections exit with
a human error on stderr and empty stdout before the document is guaranteed:
malformed arguments, --dry-run combined with --machine or
--job-preview, and --check-ffmpeg, which exits before the machine path;
every setup and run-level failure of a machine-accepted invocation
(--machine --job without --dry-run) emits a failed document:
{ "schema_version": 1, "resolver_version": "3",
"status": "succeeded | partial_failure | failed",
"groups": [{ "group": "job", "outcome": "succeeded", "input_files": ["track1.m4b"],
"artifacts": [ { "relative_path": "Author/Title.m4b", "kind": "audio", "exists": true },
{ "relative_path": "Author/Title.chapters.txt", "kind": "sidecar", "exists": true } ],
"files_moved": false } ] }
Every produced output and sidecar is enumerated; artifact paths are
relative to the job's output_root and validated to lie inside it (no
absolute-path fallback). input_files are relative to that root when they
lie inside it and [redacted] otherwise; they are not artifacts. Errors use
output_root in place of the root and redact other absolute filesystem paths.
When the job requests a processing stamp, a successfully published audio
artifact includes processing_stamp. Its value is
{"processor":"BragiBooks","audio_action":"stream_copy"} or
{"processor":"BragiBooks","audio_action":"transcode"}. Unstamped jobs do
not report it, even when an input already has these atoms. Sidecars and staged
or failed artifacts do not include it. This records this run's operation. It
does not describe later changes made by another tool.
When engine_stamp is true, the published audio artifact also includes
engine_stamp with processor, version, and audio_action. The object has
shape {"processor":"m4b-merge","version":"<--version>","audio_action":"stream_copy"};
audio_action is "transcode" when the engine encodes output audio. The version
is the value printed by --version. The result appears only for the output
produced by this job. Inherited engine atoms do not create a result. A later
sidecar failure does not suppress it when the stamped audio remains at the
published path. A failed or missing audio output, or a replaced file, does not
receive one. Custom stamp values are not returned or logged. They are
caller-supplied claims, not verified provenance.
On job failure, preserved_artifacts lists recoverable non-empty staging
files retained on disk, also relative to the validated root. Empty or invalid
stages remain on disk but are not reported as recoverable artifacts. A
failed group carries a diagnosed error (omitted when the group
succeeded). status
never claims success for a failed group; a partial or
total failure exits 1 after the document is printed, and setup/run-level
failures emit a failed document with a top-level error and empty
groups. A job run is one book: one group named "job", so
partial_failure cannot occur from --machine --job; it is reserved for
multi-group library consumers of Processor::run.
No-clobber
Job execution reserves no name at the final output path. An advisory precheck reports an already-taken final name early and validates the created parent directories against the canonical output root, and the parent is re-validated immediately before the merge. The binding guarantee is the atomic no-replace publication: the final name is created only by that step, and a foreign entry, including a late arrival, fails with a diagnosed collision.
The caller-facing guarantees:
- No overwrite: an existing final name is never read, renamed, or
replaced; a collision leaves it untouched and retains the completed
stage in
preserved_artifacts. - No suffixing, no rename: a taken name is never silently suffixed, renamed, or overwritten, at any point.
- Staging entries are never deleted by the engine: on success, each
staging entry remains as a hard link alongside the published output,
owned by the job's staging-tree cleanup, which the caller performs; on
failure, the completed media stage is retained and reported in
preserved_artifacts. Callers must clean their job-owned staging tree, accepting retained entries to avoid deleting another writer's replacement. An occupied staging name is a collision, even if it carries this attempt's visible token. - Stale sidecars are removed only after the media publication has won the final name: a sidecar that cannot be removed fails the run with a diagnosed cleanup error, while the already-published media is retained and reported in the machine result, so a surviving entry never contradicts the requested policy.
Source files and a winning job's final names are never discarded. Each job attempt gets a fresh staging token, so retries do not collide with retained entries.
Verify Environment
Check FFmpeg installation and version.
m4b-merge --check-ffmpeg
Embedded Tags
| Atom | Source |
|---|---|
©nam |
Title; subtitle appended as title - subtitle when present; the subtitle alone when no base title exists |
©ART |
All authors, joined by , |
©aART |
Same as ©ART (album artist) |
©alb |
Base title only (never the subtitle); removed when a base title does not exist (the subtitle-only state) |
©gen |
All genres, joined by / (single ©gen value) |
©day |
Release year |
©cmt |
Description |
©wrt |
All narrators, joined by , |
©grp |
Series: <name>, with #<position> appended when a position exists; multiple kept segments joined with ` |
A tag with no corresponding metadata is removed, so retagging from a different
source cannot leave stale values behind. The one exception is ©grp: the group
is rebuilt only when the metadata carries a narrator or a series name; when it
carries neither, the existing group is left as is (on a rebuild, legacy
Narrator: and Series: segments are dropped, a new series entry is added
when series metadata is present, and unrelated segments are kept, so a group
holding only legacy content is cleared entirely).
When a job file drives processing, only the fields whose policy is write or
clear are touched; preserve fields keep the file's existing values even
when the effective metadata lacks them.
Path Format Variables
The output path is generated from a template. Two template conventions exist:
- Legacy CLI (
-p/--path-format): the historical string-replacement behavior. The template is expanded, then split on/, and each resulting piece is sanitized. - Job file (
path_formaton--job): a parsed-template resolver (identity:resolver_versionfrom--capabilities). Only template separators create directories; a token's value is substituted as component data and sanitized in place, so a value can never introduce a directory, re-substitute another token, traverse (..), address a drive, or escapeoutput_root.
| Variable | Description |
|---|---|
{author} |
First ordered author name (empty: Unknown) |
{narrator} |
First ordered narrator name (empty: Unknown) |
{authors} |
All ordered authors, joined by , (empty: Unknown) |
{narrators} |
All ordered narrators, joined by , (empty: Unknown) |
{title} |
Book title |
{subtitle} |
Book subtitle |
{series_name} |
Series name |
{series_position} |
Series position number |
{year} |
Release year |
{genre} |
First genre |
{metadata_id} |
Provider-dependent looked-up ID (ASIN for audnexus, resolved catalog ID for audiobookdb), or the supplied metadata_id in supplied mode (used as-is, never looked up); empty when neither is present |
{book_id} |
Canonical AudiobookDB catalog book ID; from the catalog-resolved id in audiobookdb provider mode (a conflicting override is ignored), or from a supplied/override book_id in supplied mode (used as-is, never catalog-authenticated). Distinct from {metadata_id}; job-resolver-only |
{asin} |
The book's Audible ASIN; the supplied asin in supplied mode (used as-is, never looked up), the response ASIN for audnexus, and the external-ASIN-resolved id for audiobookdb (absent when the id fell through to the internal book endpoint). Distinct from {metadata_id} and {book_id}; job-resolver-only |
{release_id} |
The selected AudiobookDB release ID: an explicit release_id pin, else the matched/first-release fallback in audiobookdb provider mode, else the supplied release_id in supplied mode (used as-is). Job-resolver-only |
In the table above, {book_id}, {asin}, and {release_id} are
job-resolver-only tokens: the legacy CLI -p/--path-format template
does not substitute them (an unmatched placeholder is left as literal text by
the legacy path). All other tokens are shared by both conventions.
A token whose value is missing or empty does not contribute a path segment
(empty segments are stripped). A segment that exists only for its tokens is
dropped as well. If every token in a segment resolves empty, the literal text
around them leaves no segment either, so ({metadata_id}) does not become
(). Literal text in a segment that another token fills stays. The only
exceptions are {author}, {authors}, {narrator}, and {narrators}, which
substitute Unknown when no person is known. Unknown tokens in a job
path_format are rejected with an actionable diagnostic (the token, its
position, and the supported list) before any file is touched. A job
path_format that resolves to no components at all (for example {subtitle}
on a book with no subtitle) fails the group with an EmptyPath error before
any file is touched; the legacy CLI path has no such case because it falls
back to output.m4b.
Default: {author}/{title}
Capabilities
m4b-merge --capabilities prints the build's machine-readable identity and
vocabulary as JSON: the accepted schema_version, the output-path
resolver_version, the default template, every supported path token with its
substitution semantics, the field, cover, and chapter policies, and the
supported processing-stamp presets. The processing_stamps array includes
"bragibooks_v1". Boolean engine_stamp and custom_stamps fields show
whether this build accepts those optional job inputs. Older job readers reject
unknown fields, so callers should check these flags before sending the new
keys.
Callers build pickers, examples, and validation from this document instead of
maintaining their own registry, and reject protocol/resolver versions they do
not understand. The command is self-contained (no FFmpeg, job, or network).
The --job-preview and --machine surfaces carry the same
schema_version/resolver_version identity, so a caller can verify that a
path came from the resolver version it validated.
Exit Codes
| Code | Description |
|---|---|
0 |
Success (in --machine mode: every group succeeded) |
1 |
Error (missing input, FFmpeg not found, processing failed; in --machine mode: partial or total failure) |
Contributing
See CONTRIBUTING.md for guidelines on contributing to this project.
License
GPL-3.0
Explore related projects
Loading…