convert

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package convert turns source formats the device cannot render into EPUB.

The CrossPoint firmware has no PDF engine. PDF is therefore a source format only: it lives in the library and is indexed, but something has to convert it before it can reach a device. On a 4-to-7 inch e-ink panel a reflowed EPUB beats a scaled PDF page anyway, so this is the right answer rather than a workaround.

Conversion runs in-process. shelf shells out to nothing and requires nothing on PATH: a PDF converts on a machine with no Calibre, no Java, and no mupdf-tools, which is what makes the single static binary actually single.

This is narrower than the spec's "pluggable external converters" and deliberately so. shelf indexes four formats — epub, txt, xtc, pdf — and the firmware renders three of them directly, so PDF is the only thing that ever needs converting. The external converters were carrying formats shelf cannot even index, in exchange for a PATH dependency, a subprocess lifetime to manage, and a shell-injection surface to defend. Deleting them removed all three and cost nothing shelf's scope actually used.

Index

Constants

View Source
const DefaultPreset = "decant"

DefaultPreset is used when config names none. It is also the only preset: the name is kept so config files stay valid and a second compiled-in converter can be added without changing the shape of anything.

View Source
const DefaultTimeout = 10 * time.Minute

DefaultTimeout bounds a single conversion. A large PDF is genuinely slow to reconstruct, so this is generous.

Variables

View Source
var (
	// ErrTimeout means the converter exceeded its budget.
	ErrTimeout = errors.New("convert: converter timed out")

	// ErrConversionFailed means the converter ran and reported failure.
	ErrConversionFailed = errors.New("convert: conversion failed")

	// ErrUnsupported means no converter is configured for this input format.
	ErrUnsupported = errors.New("convert: unsupported input format")

	// ErrEmptyOutput means the converter claimed success but produced nothing
	// usable. Treated as failure: a zero-byte EPUB on the device is worse than
	// an error here.
	ErrEmptyOutput = errors.New("convert: converter produced no usable output")

	// ErrEncryptedPDF means the source carries an /Encrypt dictionary.
	ErrEncryptedPDF = errors.New("convert: PDF is encrypted")

	// ErrNoTextLayer means the source is a scanned page image with no
	// extractable text. Converting it anyway produces garbage, so shelf fails
	// and points at OCR instead.
	ErrNoTextLayer = errors.New("convert: PDF has no text layer (scanned)")

	// ErrMalformedPDF means the source could not be parsed as a PDF.
	ErrMalformedPDF = errors.New("convert: PDF is malformed")
)

Errors callers distinguish.

View Source
var Presets = map[string]Preset{

	"decant": {
		Name:    "decant",
		Args:    []string{"--profile=crosspoint"},
		Formats: []string{"pdf"},
		Notes:   "Reflowable EPUB 3 from a text-layer PDF, targeted at CrossPoint.",
		Version: decantVersion(),
	},
}

Presets are the compiled-in converters.

Functions

func HashFile

func HashFile(path string) (string, error)

HashFile computes the SHA-256 of a file.

func PresetNames

func PresetNames() []string

PresetNames lists available converter names, sorted for stable output.

func ProfileNames

func ProfileNames() []string

ProfileNames lists the built-in profiles in a stable order.

Types

type Assessment

type Assessment struct {
	Quality Quality `json:"quality"`
	// Reasons are human-readable, and are the whole point: a bare verdict is
	// not actionable.
	Reasons []string `json:"reasons,omitempty"`

	TextChars  int   `json:"text_chars"`
	Images     int   `json:"images"`
	Documents  int   `json:"documents"`
	ImageBytes int64 `json:"image_bytes"`
	TextPerDoc int   `json:"text_per_document"`
}

Assessment is what inspection found.

func Assess

func Assess(epubPath string) Assessment

Assess inspects a converted EPUB and reports whether it looks readable.

It never fails: an unreadable archive yields QualityUnknown rather than an error, because assessment is advisory and must not turn a successful conversion into a failed one.

func (Assessment) OK

func (a Assessment) OK() bool

OK reports whether the output is worth syncing without comment.

func (Assessment) Summary

func (a Assessment) Summary() string

Summary renders a one-line verdict.

type Cache

type Cache struct {
	Root string
}

Cache stores converted artifacts under a root directory.

func NewCache

func NewCache(dir string) *Cache

NewCache returns a cache rooted at dir.

func (*Cache) Convert

func (c *Cache) Convert(ctx context.Context, conv *Converter, src string, opts Options) (string, *Entry, bool, error)

Convert returns a converted EPUB for src, reusing the cache when possible.

This is the entry point callers should use; it hashes the source, checks the cache, and converts only on a miss.

func (*Cache) Lookup

func (c *Cache) Lookup(sourceSHA string, p Preset) (string, *Entry, bool)

Lookup returns the cached artifact for a source, if present and intact.

func (*Cache) Prune

func (c *Cache) Prune(maxAge time.Duration) (int, error)

Prune removes cached artifacts older than maxAge, reporting how many went.

func (*Cache) Put

func (c *Cache) Put(sourceSHA string, p Preset, result *Result, sourceSize int64) (string, error)

Put stores a converted artifact, moving it into the cache.

type Converter

type Converter struct {
	Preset  Preset
	Timeout time.Duration
}

Converter is a resolved, runnable converter.

func New

func New(name string, timeout time.Duration) (*Converter, error)

New resolves a converter by name.

func NewForFile

func NewForFile(configured, src string, timeout time.Duration) (*Converter, error)

NewForFile resolves a converter able to handle src's format.

There is no fallback chain any more, because there is nothing to fall back to: one converter is compiled in and it reads PDF. The value this still adds is the error for everything else, which has to distinguish two very different situations — a format the device already renders, where converting would be pointless, and a format shelf simply does not handle.

func (*Converter) Convert

func (c *Converter) Convert(ctx context.Context, src, dst string, opts Options) (*Result, error)

Convert produces an EPUB at dst from the source file at src.

The output is written to a temporary file and renamed into place only on success, so an interrupted or failed conversion never leaves a half-written EPUB that a later scan would index as a real book.

func (*Converter) Supports

func (c *Converter) Supports(ext string) bool

Supports reports whether this converter accepts the given file extension.

type Entry

type Entry struct {
	SourcePath   string     `json:"source_path"`
	SourceSHA256 string     `json:"source_sha256"`
	SourceSize   int64      `json:"source_size"`
	Converter    string     `json:"converter"`
	OutputSize   int64      `json:"output_size"`
	ConvertedAt  int64      `json:"converted_unix"`
	Assessment   Assessment `json:"assessment"`
}

Entry is the metadata stored beside each cached artifact.

It records the source path and hash so a derived EPUB stays linked to the book it came from, which is what lets sync record the relationship.

type OptimizeCache

type OptimizeCache struct {
	Root string
}

OptimizeCache stores optimized EPUBs under a root directory.

func NewOptimizeCache

func NewOptimizeCache(dir string) *OptimizeCache

NewOptimizeCache returns a cache rooted at dir, which should be config.Paths.OptimizedDir().

func (*OptimizeCache) Lookup

func (c *OptimizeCache) Lookup(sourceSHA string, p Profile) (string, *OptimizeEntry, bool)

Lookup returns the cached artifact for a source and profile, if intact.

func (*OptimizeCache) Optimize

func (c *OptimizeCache) Optimize(src string, p Profile) (string, *OptimizeEntry, bool, error)

Optimize returns an optimized EPUB for src, reusing the cache when possible.

This is the entry point callers should use. The bool reports a cache hit.

func (*OptimizeCache) Prune

func (c *OptimizeCache) Prune(maxAge time.Duration) (int, error)

Prune removes optimized artifacts older than maxAge, reporting how many went.

type OptimizeEntry

type OptimizeEntry struct {
	SourcePath   string `json:"source_path"`
	SourceSHA256 string `json:"source_sha256"`
	SourceSize   int64  `json:"source_size"`
	Profile      string `json:"profile"`
	// OutputSHA256 is the hash of the bytes a sync would actually upload. The
	// manifest records this value, not the source hash.
	OutputSHA256 string `json:"output_sha256"`
	OutputSize   int64  `json:"output_size"`
	Images       int    `json:"images"`
	Rewritten    int    `json:"images_rewritten"`
	OptimizedAt  int64  `json:"optimized_unix"`
}

OptimizeEntry is the metadata stored beside each optimized artifact.

type OptimizeResult

type OptimizeResult struct {
	Source     string   `json:"source"`
	Output     string   `json:"output"`
	Profile    string   `json:"profile"`
	SourceSize int64    `json:"source_size"`
	OutputSize int64    `json:"output_size"`
	Images     int      `json:"images"`
	Rewritten  int      `json:"images_rewritten"`
	Skipped    []string `json:"skipped,omitempty"`
}

OptimizeResult reports what optimizing one book accomplished.

func Optimize

func Optimize(src, dst string, p Profile) (*OptimizeResult, error)

Optimize writes a device-targeted copy of the EPUB at src to dst.

src and dst may be the same path; the underlying repack is atomic either way.

Font stripping (spec.md 9.2) is deliberately not implemented here. Dropping a font file means removing its OPF manifest item and every @font-face rule that references it, and a partial job produces an EPUB that epubcheck rejects. Images are where the bytes are; fonts can come later, done properly.

func (OptimizeResult) Saved

func (r OptimizeResult) Saved() int64

Saved returns the bytes the optimization removed. It can be zero, and never goes negative, because entries only get replaced when they shrink.

type Options

type Options struct {
	// Preset names the converter; empty uses DefaultPreset.
	Preset string
	// Timeout overrides DefaultTimeout.
	Timeout time.Duration
	// Progress, when set, receives human-readable status lines.
	Progress func(string)
}

Options configures a conversion run.

type Preset

type Preset struct {
	Name string
	// Formats the preset accepts, lowercase without the dot.
	Formats []string
	// Notes is shown when the preset is chosen, so the user knows what to
	// expect before waiting on a large book.
	Notes string

	// Args describes the settings the converter runs with. It is identity
	// only — nothing executes it — but it feeds the cache key, so changing a
	// setting produces a new artifact rather than serving output the old
	// settings produced.
	Args []string

	// Version identifies the converter's implementation: the library's module
	// version, folded into the cache key so upgrading re-converts. This
	// matters more for a compiled-in converter than it did for a subprocess,
	// because there is no binary on PATH whose absence would otherwise hint
	// that anything moved.
	Version string
}

Preset is a named converter. Every preset is compiled in; nothing here executes an external program.

type Profile

type Profile struct {
	// Name identifies the profile and is recorded in the sync manifest.
	Name string

	// Model is the string /api/status reports in its "device" field.
	Model string

	// MaxWidth and MaxHeight are the panel's usable pixel dimensions. Images
	// larger than this are downscaled to fit, preserving aspect ratio.
	//
	// Zero means the panel geometry is not known. shelf deliberately does not
	// guess: the firmware API does not report panel size (see the captured
	// /api/status in device/testdata), and a wrong guess either wastes bytes or
	// throws away detail the panel could have shown. With zero dimensions the
	// optimizer still converts to grayscale and recompresses — both are wins
	// independent of geometry — and simply skips downscaling.
	MaxWidth  int
	MaxHeight int

	// Grayscale converts images to 8-bit gray. The panels are monochrome, so
	// color channels are bytes the device will never display.
	Grayscale bool

	// Dither applies Floyd-Steinberg error diffusion after grayscale
	// conversion. It helps gradients on a panel with few grey levels and hurts
	// text and line art, so it is off by default.
	Dither bool

	// JPEGQuality is the re-encode quality for JPEG images, 1-100.
	JPEGQuality int
}

Profile describes one device's optimization target.

func LookupProfile

func LookupProfile(name string) (Profile, error)

LookupProfile resolves a profile by name or by device model.

Both "x4" and "x4-v1" resolve to the current x4 profile, because the CLI documents --profile=x4 while the manifest records the versioned name.

func ProfileForModel

func ProfileForModel(model string) (Profile, error)

ProfileForModel returns the profile matching a /api/status device string.

func (Profile) KnowsPanelSize

func (p Profile) KnowsPanelSize() bool

KnowsPanelSize reports whether the profile can downscale.

Callers surface this so a user is told that geometry is being skipped rather than silently getting a smaller win than they expected.

func (Profile) WithPanelSize

func (p Profile) WithPanelSize(w, h int) Profile

WithPanelSize returns a copy of the profile with panel dimensions applied. Configuration overrides a built-in table entry this way.

type Quality

type Quality string

Quality is the headline verdict.

const (
	// QualityGood means substantial extracted text and nothing alarming.
	QualityGood Quality = "good"

	// QualityQuestionable means it converted, but something looks off enough
	// to be worth a look before syncing.
	QualityQuestionable Quality = "questionable"

	// QualityPoor means the output is very unlikely to be readable — almost
	// always a scanned PDF with no text layer.
	QualityPoor Quality = "poor"

	// QualityUnknown means the output could not be inspected.
	QualityUnknown Quality = "unknown"
)

type Result

type Result struct {
	Source     string
	Output     string
	Converter  string
	Duration   time.Duration
	OutputSize int64
	// Assessment reports whether the output is likely readable.
	Assessment Assessment
	// Stderr holds the converter's diagnostic output, retained for failures.
	// Truncated, since a converter can be verbose on a large book.
	Stderr string
}

Result describes a completed conversion.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL