Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Conversion rules

What the converter does with a source, from the first byte to the finished Book. The rules of Assembling the book are the same for every format; Rules per format says what each front end hands over, and What is implemented what it cannot do yet.

Sources and memory

The converter accepts a forward-only Read and a slice.

  • A Read is read to its end into memory before anything else happens, bounded by ConvertLimits::max_source_bytes. Three things need all of it: the format is detected from the content, an id may be computed from every byte, and most front-end crates want the whole source.
  • A slice is used in place. No copy of the source is made by this crate. A front-end crate may still make one: rbook wants an owned source.
  • After that, every front end starts from the same thing, the bytes of the source.

Consequences that hold for every format:

  • Peak memory is about the source plus the converted book. The result is a Book, and a Book holds every chapter and picture (mbook, Drawbacks). Conversion is streaming at its edges, a Read in and a Write out; it is not a constant-memory pipeline.
  • The pictures of the source are held, as the front end extracted them, until the book is assembled.

Detection

When ConvertOptions::format is None, the format is taken from the content.

FormatRecognised by
PDF%PDF- within the first 1,024 bytes
EPUBA ZIP whose mimetype entry is application/epub+zip, or that contains META-INF/container.xml
DOCXA ZIP that contains word/document.xml
FB2 in a ZIPA ZIP with exactly one entry whose name ends in .fb2
CBZAny other ZIP in which every entry is a picture, a folder or ComicInfo.xml
FB2An XML document whose root element is FictionBook
HTMLA document that starts with <!DOCTYPE html or <html, in any letter case
Markdown, textNever detected; only when named
  • Rows are tried in this order; the first match wins.
  • A file name is never used: a stream has none.
  • A source that matches no row fails with Error::UnknownFormat. A source that matches a format whose feature is off fails with Error::FormatDisabled.

The draft

A front end is private code. It produces the same things for every format, and nothing else crosses into the assembler:

PartContent
MetadataValues for the keys of meta, unchecked
SectionsMarkdown in reading order; each section has the source's name for it (a file of an EPUB, a section of an FB2 document) and may contain raw HTML and destinations in the source's own terms
MarksAn element of the source that a link may lead to is marked in the Markdown of its section with an anchor definition in front of its block, named by the identifier it has in the source
PicturesFor each source name: the picture as the source has it
CoverThe source name of the picture that is the cover
OutlineOptional: level, title and a destination in the source's own terms
LandmarksOptional: a kind of RFC 0001, a title and a destination in the source's own terms
WarningsWhat the front end itself could not keep

A front end must not build chapters, paths or tables itself.

Assembling the book

The steps below are the conversion rules of this crate. They do not depend on the source format.

Chapters and paths

  • One section becomes one chapter. A front end chooses its sections so that each starts at a top-level division of the source (Rules per format).
  • A chapter above 256 KiB must be split, as RFC 0001 recommends: at its top-level headings first, then at the paragraph boundary nearest to the limit.
  • A section without text and without a picture produces no chapter.
  • Chapters are named ch0001.md, ch0002.md, … in reading order. Pictures are named img/0001.avif, img/0002.avif, … in the order of their first use, and the cover img/cover.avif.

Markdown

Every chapter is parsed with markdown 1.0.0, configured for the dialect as in mbook, and changed at the positions the parser reports:

FoundBecomesWarning
Inline <br>A hard line break, written \ and a line feedNo
Any other raw inline HTML tagNothing; the text between the tags staysMarkupDropped, once per tag name
An HTML blockNothingMarkupDropped
A picture whose source name the draft knowsA picture with the new pathNo
A picture the draft does not have, cannot decode, or that names a network addressIts alternative textPictureDropped
A link with scheme http, https or mailtoUnchangedNo
A link with any other schemeIts textLinkDropped
A link into the bookSee Links and footnotes
A character below U+0020 other than line feed and tabNothingNo

Text is normalised to Unicode NFC.

Source formats link to any element. mbook names a heading by itself and any other line through an anchor definition in front of it (ADR-0009), so the target of a link is kept to the line.

Target in the sourceDestination after conversionWarning
A file, a section or a pageThe chapter that starts thereNo
A headingThat heading: the chapter's path and the anchor mbook computedNo
Any other block: a paragraph, a figure, a list item, a block quote, a tableThat block, named by an anchor definition in front of itNo
An element inside a block, such as a word of a paragraph or a row of a tableThe block that contains it, named the same wayNo
Nothing that was convertedThe link becomes its textLinkDropped
  • A front end marks every element that has an identifier. The assembler keeps a mark only when a link of the book, or an entry of the contents, leads to it, and removes the others. mbook finds the definitions that are kept and fills the anchor table of the chapter; the converter handles no byte offsets.
  • The name is the identifier of the source, with everything but letters, digits, -, _ and . replaced by -. When the chapter already has an anchor with that name, of a heading for example, -2, -3, … is appended; every link is rewritten anyway, so a name need not survive.
  • When an identifier is used twice in a section, the first element that carries it is the target.
  • Links are re-targeted after every chapter has its final text: the anchor of a heading is known only then.
  • A link that the source marks as a note reference (epub:type="noteref" in EPUB, <a type="note"> in FB2) becomes a footnote: [^n] at the reference and [^n]: text at the end of the same chapter, as RFC 0001 requires. The text of the note is copied into every chapter that refers to it and is removed from where it stood.

Pictures

Source pictureStored as
An AVIF file that Book::add_picture acceptsThe same bytes
JPEG, PNG, GIF, WebP, BMPDecoded, turned upright by its orientation tag, encoded as AVIF
An animated GIF or WebPIts first frame, encoded the same way
Anything else (SVG, JPEG 2000, TIFF, WMF)Not stored; see Markdown
  • A picture is stored once, however often it is used. Two source names with the same bytes share one resource.
  • A picture that no chapter shows and that is not the cover is not stored.
  • Before decoding, the pixel count declared by the picture must be compared with ConvertLimits::max_picture_pixels.
  • Encoding uses PictureOptions::quality and PictureOptions::speed.
  • Without the rayon feature, a picture is encoded when a chapter first shows it. With it, the cover and every picture a chapter shows are encoded before the chapters are rewritten, on all cores of the rayon pool that rav1e encodes on as well; the chapters then take the finished files. The pictures go in runs whose declared pixels add up to at most 32,000,000, so that memory stays close to that of one large picture; a picture with more is encoded alone. Paths are given in the order of first use either way, and the files are the same.

Metadata

Values come from the front end and are passed to the setters of Meta. A value that a setter refuses is dropped with a MetadataDropped warning; it does not fail the conversion.

KeyRule
titleThe source's title; otherwise the text of the first top-level heading; otherwise Untitled, with a MetadataMissing warning
langThe source's language tags; otherwise und, with a MetadataMissing warning
idThe source's identifier: a UUID becomes urn:uuid: and the UUID in lower case, anything else is kept. Without one: a UUID version 5 computed from the source bytes, so that converting the same file twice gives the same id
dateShortened to YYYY, YYYY-MM or YYYY-MM-DD
isbnDigits only; an identifier of the source that is a valid ISBN also fills this key
annotationPlain text: markup is removed and paragraphs are separated by an empty line
coverSet by Book::set_cover when the source names a cover picture that could be stored

Where each key comes from:

KeyEPUBFB2PDFCBZ (ComicInfo.xml)DOCXHTML
titledc:titlebook-titleTitleTitleTitletitle
langdc:languagelangLanguageISOdc:languagelang of html
idThe unique dc:identifierdocument-info/id
authordc:creatortitle-info/authorAuthorWriterCreatormeta author
translatordc:contributor with role trltranslatorTranslator
series, series-indexbelongs-to-collection and group-position, or calibre:seriessequenceSeries, Number
publisherdc:publisherpublish-info/publisherPublisher
datedc:datepublish-info/year, otherwise title-info/dateYear, Month, Day
isbnAn identifier that is an ISBNpublish-info/isbn
genredc:subjectgenreKeywordsGenreKeywordsmeta keywords
annotationdc:descriptionannotationSubjectSummarySubject and descriptionmeta description
coverThe manifest's cover imagecoverpageThe first page of a scanThe first page

Markdown and plain text carry no metadata that is read.

A cell is filled only as far as the front-end crate exposes the field.

Contents

  • With an outline in the draft, the contents are Toc::Explicit: one item per outline entry. An entry leads to a chapter or to a heading, because a contents item cannot name an extra anchor (mbook, Extra anchors): an entry whose target is another element leads to the nearest heading above it, or to the start of its chapter, with a LinkRetargeted warning.
  • An entry whose target was not converted is left out with a LinkDropped warning.
  • Without one, the contents are Toc::FromHeadings.

Landmarks

A landmark of the draft becomes one of the book.

  • Its destination is re-targeted like a link, to the line: a landmark may lead to an extra anchor, so nothing is moved to a heading.
  • A landmark whose target was not converted is left out with a LinkDropped warning, and so is a second start.

Only EPUB has landmarks of its own: the landmarks navigation of EPUB 3, otherwise the guide of EPUB 2. Their types are mapped to the kinds of RFC 0001 (bodymatter becomes start, loi becomes list-of-figures, copyright-page becomes copyright, and so on). Three sorts of entry produce no landmark: the cover, which is a picture in mbook; a table of contents set in the text (toc), which the contents of the book replace; and types without a counterpart.

The final check

The assembled book must pass Book::check before it is returned or written. A failure is reported as Error::Book and means a defect of this crate, not of the source.

Rules per format

FormatSectionsOutlineNotes
EPUBOne per spine item, in spine orderThe navigation document, otherwise the NCXA page that only shows the cover picture is skipped. A picture in the spine is a figure. The landmarks of the book are carried over.
FB2One per top-level section of the main body; what stands between them gets sections of its ownNone; headings are usedSee the table below. The main body is the first one not named notes or comments.
PDFOne per first-level entry of the document outline, rendered from its pages; otherwise cut at top-level headingsThe document outlineMarkdown is rendered by unpdf with Markdown tables, without front matter and page markers. A document without a text layer becomes one section in which every page is a figure, rendered at 150 dpi or less.
CBZOne per folder of the archive, headed by the name of the folder; one for an archive without foldersNone; headings are usedEntries in natural order of their names; every page is a figure, and the first page is the cover. ComicInfo.xml fills the metadata.
DOCXCut at top-level headingsNone; headings are usedMarkdown is rendered by undoc. A numbered or bulleted paragraph is an item of a list, and an item of a deeper level of Word is nested in the item before it. A footnote is moved into the section that refers to it.
HTMLCut at top-level headingsNone; headings are usedThe encoding is taken from a byte order mark, from the document, or guessed. Only pictures given as data: addresses can be stored.
MarkdownCut at top-level headingsNone; headings are usedThe encoding is detected. Every heading is marked with the name GitHub derives from it, so that [see](#the-heading) keeps working across chapters. A metadata block at the start (front matter) is removed with MarkupDropped. Pictures cannot be found from a stream and become their alternative text.
TextOneNoneThe encoding is detected; paragraphs are separated by empty lines; Markdown punctuation is escaped.

HTML, and the HTML inside an EPUB, is converted the same way: script, style, forms and embedded objects are dropped; sub, sup and u keep their text and are reported once as MarkupDropped; a table with merged cells is flattened and reported; every element with an id is marked; a note reference of EPUB (epub:type="noteref") whose note is in the same document becomes a footnote.

FictionBook is converted element by element by this crate:

FB2Markdown
title of a section at depth nA heading of level n, at most 6
subtitleA heading one level below its section's
pA paragraph
emphasis, strong, strikethrough, codeThe matching inline markup
sub, sup, styleThe text alone, with MarkupDropped
epigraph, cite, the annotation of a sectionA block quote; text-author is its last paragraph
poemOne paragraph per stanza, with a hard line break after every v; its title is a bold line
empty-lineA paragraph boundary
tableA table; merged cells are split, with MarkupDropped
imageA picture; alone in a paragraph, it is a figure
aA link, or a footnote when its type is note or its target is in the notes body
body named notes or commentsThe source of footnote texts; it produces no section
binaryA picture
An element the format does not defineIts text

A source that is protected, with a password or by rights management, fails with Error::Protected for every format. A source with no text and no picture that could be stored fails with Error::Empty.

What is implemented

Every format of Formats and features is implemented and tested against sources built in memory by its tests. What each front end does not do:

FormatLimits of the front end
EPUBXHTML in an encoding other than UTF-8 and UTF-16 is read as UTF-8. A plain-text description loses its paragraph breaks, because rbook joins its lines. A note in another file than its reference stays a link. An archive entry declared larger than the resource limit refuses the book, even an entry the book does not use.
FB2A table keeps no alignment. The style and lang attributes are ignored. The document is decoded as a whole before it is parsed. Elements nested deeper than 256 levels are refused with Error::Limit.
PDFHeadings are what unpdf finds: per page, by font size, at most four levels. A picture stands at the end of its page, not where it is drawn, and one narrower or lower than 64 pixels is left out. An outline entry with a named destination has no page and joins the entry before it. A scanned document has no contents. Every page of a scan is held as pixels until the book is assembled. Whether unpdf escapes a lone ~ was not verified.
CBZComicInfo.xml is read in UTF-8 only; of its fields the title, series, number, writer, translator, publisher, date, language, genre and summary are used.
DOCXA link to a bookmark of the document becomes its text: undoc does not read bookmarks. A heading is found only when its style has an outline level. A note is plain text. Letters and Roman numerals of a list become decimal numbers. A paragraph with text between two items ends their list, so the item after it starts a new one, at its own number; an empty paragraph does not. An item more than one level deeper than the item before it is nested one level. Underline, superscript and subscript reach the assembler as raw HTML and are removed with MarkupDropped. The language is read from the core properties only. undoc unpacks entries under its own bound, 100 times their packed size, not under the limits of this crate.
HTMLA form and what it contains is dropped. CDATA sections of XHTML are not read. A document nested deeper than 128 levels becomes one paragraph of text, with MarkupDropped: htmd walks the tree recursively. An element with a name HTML does not define cannot be a link target.
MarkdownFront matter is removed, not read. Pictures are dropped: a stream has no folder to find them in.
TextNo structure is recognised: no headings, no lists.

The assembler implements every rule of Assembling the book.

Security considerations

  • A source is untrusted input to this crate, to its front-end crate and to the picture decoders. The converter has no unsafe code of its own; its dependencies are not covered by that statement.
  • Limits cover what the converter allocates: the buffered source, unpacked entries, decoded pictures and the book. Memory that a front-end crate allocates while it parses is bounded only through the size of the source handed to it.
  • Archives. An entry is unpacked only up to its limit, whatever size its header declares.
  • Nothing is fetched. Network addresses in a source are never opened.
  • No path of the source reaches the book. Chapters and pictures get generated names, so a hostile entry name cannot become a resource path.
  • No active content survives. Scripts and styles are dropped with the raw HTML, and the final check rejects a book that still contains any.