services

package
v0.5.0-beta.5 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: AGPL-3.0 Imports: 58 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 services implements AudioSmith's domain services (core.*Service) over a store.Store, a jobs.Scheduler and the core.Bus: the take library and generation, voice and project libraries, and debounced drafts.

Every service is goroutine-safe, returns copies, wraps core.Err* sentinels and publishes its event on the bus after the change is durable, never while holding a lock. Bus handlers the services install (TakeService listens for jobs.Updated) hand slow work to goroutines.

Imports: core, store, jobs, engine/proto (the tts.synthesize params a job carries) and i18n (job titles).

Index

Constants

View Source
const (
	// ASRPromptMaxSeconds is the longest audio Qwen3-ASR gets a prompt
	// (vocabulary) with: one of its 30 s chunks.
	ASRPromptMaxSeconds = 30
	// AlignWindowSeconds bounds a window of the forced aligner on long
	// audio; audio up to AlignSingleMaxSeconds is aligned in one call.
	AlignWindowSeconds    = 240
	AlignSingleMaxSeconds = 270
)
View Source
const (
	CallOutbound = "outbound"
	CallInbound  = "inbound"
)

Call directions.

View Source
const (
	CallDialing = "dialing"
	CallRinging = "ringing"
	CallLive    = "live"
	CallEnded   = "ended"
	CallFailed  = "failed" // never connected: Twilio refused, busy, no answer…
)

Call phases.

View Source
const (
	CallEventPlaced    = "placed"
	CallEventAnswered  = "answered"
	CallEventStream    = "stream"     // the media stream connected
	CallEventTakeover  = "takeover"   // Detail "on" / "off"
	CallEventWithheld  = "withheld"   // the guard replaced a sentence
	CallEventWrapUp    = "wrap_up"    // 30 s left
	CallEventError     = "error"      // Detail: what failed
	CallEventEnded     = "ended"      // Detail: telephony.End*
	CallEventRejected  = "rejected"   // the gateway refused a request (Detail: the reason)
	CallEventKey       = "key"        // the caller pressed a key
	CallEventNoStream  = "no_stream"  // answered, but the media stream never connected
	CallEventSummarize = "summarized" // the summary is ready
)

Timeline kinds besides Twilio's statuses.

View Source
const (
	DialogueHeard         = "heard"          // the recognizer did not hear it, twice
	DialogueLength        = "length"         // far shorter or longer than its text, twice
	DialogueSegmentFailed = "segment_failed" // the model could not make the segment
	DialogueUnavailable   = "unavailable"    // no model, no licence or no engine
)

Why a line was not made by the dialogue model (dialogueReason), as a dub's Render.FallbackReason will say it.

View Source
const (
	KindDubFetch      = "dub.fetch"
	KindDubIngest     = "dub.ingest"
	KindDubSeparate   = "dub.separate"
	KindDubTranscribe = "dub.transcribe"
	KindDubReferences = "dub.references"
	KindDubTranslate  = "dub.translate"
	KindDubSynthesize = "dub.synthesize"
	KindDubMix        = "dub.mix"
	KindDubQC         = "dub.qc"
	KindDubExport     = "dub.export"
)

Job kinds of the dub pipeline.

View Source
const (
	DubWarnNoSeparation  = "dub.no_separation"     // the engine cannot separate (or no model): the original is ducked under the dub
	DubWarnNoDiarization = "dub.no_diarization"    // the engine cannot tell speakers apart: one speaker
	DubWarnTooManySpk    = "dub.too_many_speakers" // more speakers than the model separates
	// DubWarnSpeakersModel: the model that tells speakers apart best is
	// not downloaded; Sortformer did (thread #48).
	DubWarnSpeakersModel = "dub.speakers_model"
	DubWarnNoPoster      = "dub.no_poster"     // no media.thumbnail
	DubWarnNoProxy       = "dub.no_proxy"      // the video cannot play in the preview (no media.transcode)
	DubWarnNoEnhance     = "dub.no_enhance"    // references kept as they are
	DubWarnCaptions      = "dub.captions"      // the downloaded captions were used instead of transcription
	DubWarnNoReference   = "dub.no_reference"  // a speaker with too little speech: the default voice
	DubWarnVoice         = "dub.voice"         // a cast voice could not be resolved: the default voice
	DubWarnNoBackground  = "dub.no_background" // keep background, but nothing to keep it from
	DubCodeNoSource      = "dub.no_source"
	DubCodeNoSpeech      = "dub.no_speech"     // transcription found no speech
	DubCodeNoTranslator  = "dub.no_translator" // no translation engine is set up
	DubCodeNoLines       = "dub.no_lines"      // nothing to say in the language
	DubCodeNotMixed      = "dub.not_mixed"     // export of a track not made yet
	DubCodeNeedsEngine   = "dub.needs_engine"  // the export needs an engine method it lacks (data: method)
	DubCodeNeedsFFmpeg   = "dub.needs_ffmpeg"  // MP3 and burnt-in subtitles
	DubCodeFailed        = "dub.failed"
)

Warning and error codes of the dub stages (StageState.Code/Warnings).

View Source
const (
	// DubWarnDialogueUnavailable: the dialogue model is not there (not
	// downloaded, no engine, too little memory): every line was made line
	// by line.
	DubWarnDialogueUnavailable = "dub.dialogue_unavailable"
	// DubWarnDialogueFallback: some lines of the conversations were made
	// line by line (Render.FallbackReason).
	DubWarnDialogueFallback = "dub.dialogue_fallback"
	// DubWarnLinesFlagged: some lines failed their check (Render.Flag):
	// made line by line in place of the dialogue model's and not passing
	// its check either, or cloned from a clip in another language and
	// still wrong when made again (dub_check.go).
	DubWarnLinesFlagged = "dub.lines_flagged"
	// DubDialogueMemory is DubDialogueModel.Blocked on a Mac with too
	// little memory.
	DubDialogueMemory = "memory"
)

Codes of the dub's dialogue model.

View Source
const (
	DubWarnTranslateFailed = "dub.translate_failed" // some lines failed (Line.Err): retry them
	DubWarnLinesFailed     = "dub.lines_failed"     // some lines could not be rendered (Render.Err)
	DubCodeNoModel         = "dub.no_model"         // no TTS model chosen
	// LineLoudness is the level every dubbed line is brought to (LUFS).
	LineLoudness = -20.0
)

More codes of the dub stages.

View Source
const (
	FetchDownloading = "downloading"
	FetchMerging     = "merging"
	FetchFinishing   = "finishing"
)

Stages of a dub.fetch job's progress.

View Source
const (
	FormatM4A  = "m4a"
	FormatMP3  = "mp3"
	FormatFLAC = "flac"
	FormatOpus = "opus"
)

Audio export formats (and FormatWAV, longform_doc.go).

View Source
const (
	IsolateMeta       = "isolation.json"
	IsolateAudio      = "audio.wav"       // the input, decoded
	IsolateVocals     = "vocals.wav"      // the voices
	IsolateBackground = "background.wav"  // the music and effects
	IsolateClean      = "voice-clean.wav" // the voices, denoised
)

The files of an isolation, in its folder.

View Source
const (
	IsolateQueued  = "queued"
	IsolateRunning = "running"
	IsolateDone    = "done"
	IsolateFailed  = "failed"
)

The states of an isolation.

View Source
const (
	ChapterPending   = "pending"
	ChapterRendering = "rendering"
	ChapterDone      = "done"
	ChapterCached    = "cached" // no synthesis was needed
	ChapterFailed    = "failed"
	ChapterStopped   = "stopped"
)

Chapter states.

View Source
const (
	LoudnessOff     = ""
	LoudnessACX     = "acx"     // −19 LUFS, −3 dBTP (Audible)
	LoudnessPodcast = "podcast" // −16 LUFS, −1.5 dBTP
)

Loudness targets of a book (dsp/loudness presets).

View Source
const (
	FormatWAV = "wav"
	FormatM4B = "m4b" // needs the engine's media.encode (EncodeSupported)
)

Output formats of a book.

View Source
const (
	IntensityLight  = 1
	IntensityMedium = 2
	IntensityStrong = 3
)

Direction intensities (StoryLine.Intensity).

View Source
const (
	KindChapter   = "longform.chapter"  // gpu lane: one chapter
	KindAssemble  = "longform.assemble" // cpu lane: the book, after its chapters
	OwnerLongform = "longform:"         // + the render's id
)

Job kinds and owner of longform renders.

View Source
const (
	ProblemNoModel       = "longform.no_model"
	ProblemNothingToSay  = "longform.nothing_to_say"
	ProblemNoVoice       = "longform.no_voice"       // a line without a voice [line]
	ProblemMissingVoice  = "longform.missing_voice"  // a voice that is gone [voice]
	ProblemUnknownVoice  = "longform.unknown_voice"  // [voice:NAME] nobody is cast as: the line's voice reads it [voice]
	ProblemEmptyChapter  = "longform.empty_chapter"  // [title]
	ProblemUnknownTag    = "longform.unknown_tag"    // read aloud [tag]
	ProblemDuplicateWord = "longform.duplicate_word" // the lexicon lists a word twice [word]

	// A manuscript's dialogue blocks (book_dialogue.go); none blocks.
	ProblemDialogueUnclosed   = "longform.dialogue_unclosed"    // a block ends with its chapter [at: "heading" when a heading ended it]
	ProblemDialogueNested     = "longform.dialogue_nested"      // an opening marker inside a block, ignored
	ProblemDialogueStrayClose = "longform.dialogue_stray_close" // a closer outside a block, ignored
	ProblemDialogueEmpty      = "longform.dialogue_empty"       // a block with nothing to say, ignored
	ProblemDialogueUncast     = "longform.dialogue_uncast"      // names in a block without a voice [names]: voices are given at render
	ProblemDialogueOneSpeaker = "longform.dialogue_one_speaker" // one speaker: read line by line
	ProblemDialogueUnknown    = "longform.dialogue_unknown"     // "?" turns nobody was found for: the narrator reads them [count]
	ProblemDialogueLanguage   = "longform.dialogue_language"    // not Chinese or English: read line by line [lang]
	ProblemDialogueTags       = "longform.dialogue_tags"        // tags the dialogue model leaves out [tags]
)

Problem codes (Params in brackets).

View Source
const (
	CodeNothingToSay      = "nothing_to_say"     // the script has no speech
	CodeRenderFailed      = "render_failed"      // joining, mastering or writing failed
	CodeEngineUnavailable = "engine_unavailable" // as engine.CodeEngineUnavailable
)

Job error codes of renders, besides the engine's (proto.Code*), which a failed chunk passes on.

View Source
const (
	NoticeChunkShort  = "render.chunk_short"  // much shorter than its text: words may be missing (value: seconds, params expected)
	NoticeChunkSilent = "render.chunk_silent" // no speech at all
	NoticeChunkLong   = "render.chunk_long"   // much longer than its text: the model may have rambled
	NoticePostSkipped = "render.post_skipped" // the engine's file could not be read: kept as it is
)

Notice codes of TakeRender.Warnings (besides plan's and markup's diagnostic codes, which keep theirs) and of TakeRender.Issues (dsp/qc's codes).

View Source
const (
	StepsFast     = 16
	StepsBalanced = 32 // OmniVoice's default
	StepsQuality  = 48
)

Step counts of the performance tiers, for models with Steps.

View Source
const (
	// SpeakersWindowSeconds is the longest audio a speakers model hears
	// in one pass; longer audio goes in windows of at most this length.
	SpeakersWindowSeconds = 600
	// SpeakersOverlapSeconds is what consecutive windows share: both
	// transcribe it, and its speakers link the two windows' labels.
	SpeakersOverlapSeconds = 60
)
View Source
const (
	ContinuityInstruct  = "instruct"  // takes the scene, personas and directions
	ContinuityIntensity = "intensity" // takes the emotions' intensities only (Chatterbox)
	ContinuityLines     = "lines"     // pacing and merged turns only
)

Continuity levels of a model for stories (ContinuityOf).

View Source
const (
	EmotionSteady    = "steady"
	EmotionHappy     = "happy"
	EmotionExcited   = "excited"
	EmotionTender    = "tender"
	EmotionPleading  = "pleading"
	EmotionHesitant  = "hesitant"
	EmotionWorried   = "worried"
	EmotionHurt      = "hurt"
	EmotionSad       = "sad"
	EmotionAngry     = "angry"
	EmotionScared    = "scared"
	EmotionSurprised = "surprised"
	// EmotionApologetic: sorry, guilty, delivering bad news (added after
	// round 1: without it the director called a father announcing a
	// trip "very scared").
	EmotionApologetic = "apologetic"
)

Emotions (StoryLine.Emotion). EmotionSteady is the character's baseline going on: most lines of a scene.

View Source
const (
	PacingFixed    = ""         // one gap between all lines (LineGapMs)
	PacingDialogue = "dialogue" // tight turns: a conversation
	PacingReading  = "reading"  // a reading pace
	PacingRelaxed  = "relaxed"  // unhurried
)

Pacing presets (Production.Pacing).

View Source
const (
	TurnSame      = "same"
	TurnQuestion  = "question"
	TurnStatement = "statement"
	TurnTrailing  = "trailing"
	TurnNarration = "narration"
	TurnParagraph = "paragraph"
)

Turn kinds between two lines (TurnOf).

View Source
const (
	ExportTXT  = "txt"
	ExportSRT  = "srt"
	ExportVTT  = "vtt"
	ExportJSON = "json"
)

Transcript export formats.

View Source
const (
	WorkflowCodeInvalid  = "workflow.invalid"   // the graph has errors (Run refuses)
	WorkflowCodeBusy     = "workflow.busy"      // a run is going on
	WorkflowCodeNoInput  = "workflow.no_input"  // a step got no value
	WorkflowCodeNoSTT    = "workflow.no_stt"    // no speech-to-text model
	WorkflowCodeNoSpeech = "workflow.no_speech" // transcription found nothing
	WorkflowCodeEmpty    = "workflow.empty"     // a step made empty text or silence
	WorkflowCodeFile     = "workflow.file"      // a clip or a result file can't be read or written
	WorkflowCodeVoice    = "workflow.voice"     // the step's voice can't be used
	WorkflowCodeEncode   = "workflow.encode"    // M4A needs the engine's media.encode
)

Error codes of workflow runs (besides the engine's and the translators').

View Source
const (
	WorkflowWarnSilent   = "workflow.silent"    // normalize: the audio is silent, kept as it is
	WorkflowWarnNoFolder = "workflow.no_folder" // export: no folder, nothing written
)

Warnings of steps.

View Source
const BatchQueue = "queue"

BatchQueue is the batch queue's id (store.DubRecord.Batch).

View Source
const CallOwner = "call:"

CallOwner prefixes the owner of a call's jobs ("call:<id>/<n>").

View Source
const CreditsFile = "credits.txt"

CreditsFile is the name of the credits beside a render's or an export's files.

View Source
const DiskKeepFree int64 = 1 << 30

DiskKeepFree is what work keeps free beyond its estimate: the system and the other work under way need room too.

View Source
const DraftPrefix = "draft:"

DraftPrefix is the store.Documents key prefix of drafts.

View Source
const DubCodeFreed = "dub.freed"

DubCodeFreed: an export needs working files that were freed (the separated stems); a run makes them again.

View Source
const DubExportOwner = "dubexport:"

DubExportOwner prefixes the owners of export jobs ("dubexport:<id>"), apart from the pipeline's so an export does not block a run.

View Source
const DubFreeAfter = 7 * 24 * time.Hour

DubFreeAfter is how long after its last export (or opening, or edit) a dub keeps its working files.

View Source
const DubOwner = "dub:"

DubOwner prefixes the owners of a dub's jobs: "dub:<id>".

View Source
const FamilyMossTTSD = dialogue.FamilyMossTTSD

FamilyMossTTSD is MOSS-TTSD's catalogue family: a one-track dialogue model.

View Source
const FamilyVibeVoice = dialogue.FamilyVibeVoice

FamilyVibeVoice is VibeVoice 1.5B's catalogue family (thread #166).

View Source
const FavoritesScope = "gallery"

FavoritesScope is the favorites scope of the voice gallery's archetypes.

View Source
const IsolateOwner = "isolate:"

IsolateOwner prefixes the owners of isolation jobs: "isolate:<id>".

View Source
const KindEncode = "media.encode"

KindEncode is the engine's media.encode (proposed for the engine thread; see EncodeParams). The app offers M4B only when the engine has it (Config.Encode returns an executor).

View Source
const KindIsolate = "isolate.run"

KindIsolate is the job kind of an isolation.

View Source
const KindRender = "take.render"

KindRender is the job kind of a take's render.

View Source
const KindTranscribe = "transcript.make"

KindTranscribe is the job kind of a transcription.

View Source
const KindWorkflowStep = "workflow.step"

KindWorkflowStep is the job kind of a workflow step's run.

View Source
const LongformVersion = 2

LongformVersion is the version of LongformDoc. Version 2 added the optional dialogue fields (Scene, CastMember.Persona, StoryLine.Direction and Intensity, Production.Pacing and NoMerge): a version 1 document reads as a version 2 one with them empty, which renders exactly as version 1 did, so no migration rewrites anything.

View Source
const MasterDefault = "broadcast"

MasterDefault is the mastering preset of "Even out volume".

View Source
const MaxCoverBytes = 8 << 20

MaxCoverBytes caps a cover image.

View Source
const MethodBurn = "media.burn"

MethodBurn draws subtitles into a video (an app-level method: the app runs it on ffmpeg; params as the app's BurnParams).

View Source
const NoticeDialogueUnavailable = "longform.dialogue_unavailable"

NoticeDialogueUnavailable: a chapter's dialogue blocks were read line by line, the dialogue model not being ready (not downloaded, no licence) [model].

View Source
const NoticeWatermarkFailed = "render.watermark_failed"

NoticeWatermarkFailed: the take could not be watermarked (params: error).

View Source
const SpeakerRef = "speaker:"

SpeakerRef prefixes a VoiceRef naming one of the model's own speakers.

View Source
const TranscriptOwner = "transcript:"

TranscriptOwner prefixes the owners of transcription jobs: "transcript:<id>".

View Source
const TranscriptRate = 16000

TranscriptRate is the sample rate of the audio kept with transcripts (what speech models listen at).

View Source
const WarnNoDenoise = "isolate.no_denoise"

WarnNoDenoise: the denoiser is missing; the voices are not denoised.

View Source
const (
	WarnNoWordTimes = "transcript.no_word_times" // the aligner failed: segments without word timings
)

Warnings of a transcription (TranscribeResult.Warnings).

View Source
const WorkflowOwner = "workflow:"

WorkflowOwner prefixes the owners of a workflow's jobs: "workflow:<id>".

Variables

Emotions lists the vocabulary in the order the UI and the director show it.

View Source
var ErrCallVoice = errors.New("only designed voices and voices with a verified consent recording can make calls")

ErrCallVoice: the voice may not place calls (only designed voices and clones with a verified consent recording may).

View Source
var ErrCallsBusy = errors.New("another call is running")

ErrCallsBusy: as many calls as allowed are running.

View Source
var ErrChanged = fmt.Errorf("the project was changed elsewhere since it was read: %w", core.ErrBusy)

ErrChanged is SaveDocIf's refusal: the project was saved by someone else (the page, an agent) after the caller read it (#101 M7). It wraps core.ErrBusy (HTTP 409).

View Source
var ErrNoEncoder = errors.New("export: nothing can write this format")

ErrNoEncoder is returned for a format other than WAV without an encoder.

View Source
var ErrNoPreview = errors.New("the voice has no audio to build a preview from")

ErrNoPreview: a voice has no WAV to ship as an export's preview (no sample, no WAV reference; its takes are not used): lock a take as its identity (its sample) first.

View Source
var ErrNotInTrash = errors.New("the deleted voice is no longer kept")

ErrNotInTrash: Restore found no deleted voice of that id (purged, or never deleted).

ExportFormats are the formats Export writes, in menu order.

View Source
var ExportLoudness = map[string]loudness.Target{
	"podcast":   loudness.Podcast,
	"speech":    {ID: "speech", Integrated: -18, MinIntegrated: -19, MaxIntegrated: -17, TruePeak: -1},
	"broadcast": loudness.Broadcast,
}

ExportLoudness are the loudness targets of an export, by key: integrated loudness (LUFS) and true-peak ceiling (dBTP).

Pacings lists the presets in the order the UI shows them.

Functions

func ASRPrompt

func ASRPrompt(model, prompt string, seconds float64) string

ASRPrompt is the prompt to send model with audio of seconds: none to Qwen3-ASR for audio longer than ASRPromptMaxSeconds (or of unknown length), prompt otherwise.

func BodyIs

func BodyIs(read core.Project) func(core.Project, LongformDoc) bool

BodyIs is a SaveDocIf check: the stored body is the one read.

func BuildSegments

func BuildSegments(segs []proto.Segment, words []proto.Word, duration float64) []core.TranscriptSegment

BuildSegments makes a transcript's segments from what the model said (segs) and the words an aligner or the model timed (words, in text order; their text may lack punctuation and case). With words, the text is cut into sentences timed by their words, each word keeping its punctuation; without, the model's segments are kept. Segments keep their model segment's speaker label: with words, a change of speaker ends a sentence (a speakers model's turns often end without a full stop). duration (seconds, 0 = unknown) bounds every time.

func CastNames

func CastNames(script string) []string

CastNames are the names a manuscript casts: its [voice:NAME] names, then its dialogue blocks' speakers it does not name so.

func CheckAudio

func CheckAudio(ctx context.Context, path string) ([]core.TakeNotice, error)

CheckAudio runs Check audio over a WAV file.

func CleanTranscription

func CleanTranscription(model string, tr *proto.TranscribeResult) bool

CleanTranscription drops the ending Qwen3-ASR (model) hallucinated on audio longer than ASRPromptMaxSeconds: a last segment that is only "The." or "嗯。", or that tail after the last sentence of the text and of its last segment. Other models' results, and shorter audio, are left alone. It reports whether it changed tr.

func CloneTakesInstruct

func CloneTakesInstruct(caps []string) bool

CloneTakesInstruct reports whether a model's clones take a delivery instruction as well: one that both clones and takes "instruct" (VoxCPM2's "(instruction)" before the text, thread #165). Qwen3-TTS's instruct models don't clone, and its Base models take no instruction.

func Compile

func Compile(d *LongformDoc, resolve VoiceResolver) (LongformSpec, []Problem)

Compile turns a document into a render manifest. Problems with Blocking set mean the spec must not be rendered.

func CompileBook

func CompileBook(d *LongformDoc, resolve VoiceResolver) (LongformSpec, []Problem, []DialogueBlockInfo)

CompileBook is Compile with the manuscript's dialogue blocks.

func ContinuityOf

func ContinuityOf(info Traits) string

ContinuityOf is what a model does with a story's scene, personas and directions.

func ConvertWAV

func ConvertWAV(ctx context.Context, src, dst string, bits int) error

ConvertWAV writes src to dst as a WAV of bits (16 with dither, 24, 32 float): exports of renders.

func CopyFile

func CopyFile(ctx context.Context, src, dst string) error

CopyFile copies src to dst through a temporary file beside it (exports).

func CreditsText

func CreditsText(credits []string) string

CreditsText is the text of a credits.txt: what to name when the audio is published, one credit a line.

func Cues

func Cues(t core.Transcript) []subtitle.Cue

Cues are the transcript's subtitles: its segments split into readable cues by their word timings (estimated from the text when unknown).

func DefaultDubTargets

func DefaultDubTargets() []string

DefaultDubTargets are the languages of a dub nobody chose any for.

func DialogueNames

func DialogueNames(script string) []string

DialogueNames are the speakers of a manuscript's dialogue blocks, in order, one spelling each (markup.NameKey).

func Disclosure

func Disclosure(template, user, voice string) string

Disclosure fills a disclosure template: "{name}" is the user's name, else the voice's.

func DiskFullJob

func DiskFullJob(err error) *jobs.Error

DiskFullJob is err as a disk_full job error when it says the disk is full (a pre-check's core.DiskFullError, a write's ENOSPC, an engine error whose message says so), else nil. The message is kept; the error is not retryable (the next attempt would fail the same way). The app's scheduler classifies executors' failures with it (jobs.Options.ClassifyError). A model download's refusal keeps its own code (hub.CodeDiskSpace), by which the Models page explains it (code review 1103 L-1).

func DuplicateWords

func DuplicateWords(l []LexiconEntry) []string

DuplicateWords lists the words a book's lexicon has more than once (case-insensitive), each once.

func ETA

func ETA(b *RenderBody, now time.Time) (time.Duration, bool)

ETA estimates the seconds a render still needs from the characters done so far and the time they took ("" when too early to say). Pure.

func EmotionExaggeration

func EmotionExaggeration(intensity int) float64

EmotionExaggeration is Chatterbox's emotion exaggeration for an intensity (its default is 0.5).

func EmotionGapFactor

func EmotionGapFactor(emotion string, intensity int) float64

EmotionGapFactor is how much an emotion at an intensity stretches (>1) or shortens (<1) the pause next to its line; 1 for none.

func EmotionInstruct

func EmotionInstruct(emotion string, intensity int, own string, cont, zh bool) string

EmotionInstruct is the instruction of a line directed with an emotion at an intensity (0–3): "略带委屈", "非常委屈,带哭腔", "语气平稳". own, when not "", is the user's own wording, which takes the emotion's place. cont adds "carry on from your last line" when it fits.

func EmotionWord

func EmotionWord(emotion string, zh bool) string

EmotionWord is an emotion's word in Chinese (zh) or English.

func Export

func Export(t core.Transcript, format string) ([]byte, error)

Export writes a transcript as format: plain text (the preferred text: the clean-up when there is one; with two or more speakers, one paragraph per turn after its speaker's name), SubRip or WebVTT subtitles cut to Netflix-style limits for its language (speaker names before SRT cues, as VTT voices), or JSON with every segment and timed word.

func ExportAll

func ExportAll(ts []core.Transcript, date func(time.Time) string) []byte

ExportAll writes transcripts as one text file, newest first: a header line (date, language, title) above each text, "---" between them. date formats the header's time (the UI's localized format).

func ExportNeeds

func ExportNeeds(format string) string

ExportNeeds says what an export format needs that may be missing: "" (nothing), "engine:<method>" or "ffmpeg".

func FetchProgress

func FetchProgress(d dub.DownloadProgress) jobs.Progress

FetchProgress is a URL download's progress as its job's: Bytes and TotalBytes of the whole download, ETA, and the fraction (-1 while not known, or merging).

func HasReference

func HasReference(t core.Take) bool

HasReference reports whether a recipe gives a cloning model a voice to clone: a reference clip or an encoded voice prompt. Without one, a model that only clones refuses it (checkReference) and the others speak in their default voice; the Studio's hints ask the same question.

func Interrupted

func Interrupted(p *dub.Project, active []jobs.Job) bool

Interrupted reports whether p's last run stopped without finishing (no job of it is left, yet it did not get through).

func IsSpeakersModel

func IsSpeakersModel(model string) bool

IsSpeakersModel reports whether model (a repo or id) transcribes with speaker labels: MOSS-Transcribe-Diarize (catalogue capability "speakers").

func Issues

func Issues(rep qc.Report) []core.TakeNotice

Issues converts Check audio's report to take notices.

func LineInstruct

func LineInstruct(lines []LineSpec, li int, scene string) string

LineInstruct is the instruction line li of a chapter's lines is sent when it is said on its own (not merged into a turn), "" for none: its emotion's, else the first director's (previews, evaluation).

func LineTake

func LineTake(p *dub.Project, seg dub.Segment, l string, v dub.VoiceSpec, caps DubModelCaps) core.Take

LineTake is the recipe of a dubbed line: what the synthesize stage renders (and the workspace's audition plays).

func MentionsRecording

func MentionsRecording(disclosure string) bool

MentionsRecording reports whether a disclosure tells the other party the call is recorded (recording needs that).

func NormEmotion

func NormEmotion(s string) string

NormEmotion is the vocabulary's key for an emotion a model or user wrote (a key, its Chinese word or a common synonym), "" for none.

func OneTrackDialogue

func OneTrackDialogue(family string) bool

OneTrackDialogue reports whether a dialogue model family speaks a segment as one track (MOSS-TTSD, VibeVoice: dialogue.OneTrack).

func PlainText

func PlainText(t core.Transcript) string

PlainText is the transcript as text to copy or save: the preferred text, or, when two or more speakers say it and there is no clean-up, one paragraph per turn after its speaker's name ("Ana: …"); labels given the same name are one speaker.

func PortableLine

func PortableLine(lang string) string

PortableLine is what a voice says to become a reference clip when there is no time to pick among takes (about 12 s), in its language: the first of the adult reference texts (voicedesign.ReferenceTexts), lively everyday narration rather than a sentence read about the recording.

func ProcessAudio

func ProcessAudio(b dsp.Buffer, o AudioExport) (dsp.Buffer, float64, float64)

ProcessAudio applies o's processing to b: trim, then sample rate and channels, then loudness. It returns the result, the seconds trimmed from the start and, with a target, the loudness reached (LUFS). b is not modified.

func SafeFileName

func SafeFileName(s, fallback string) string

SafeFileName makes s usable as a file name: path separators and control characters dropped, at most 80 characters; fallback when empty.

func Sidecar

func Sidecar(wavPath string) string

Sidecar is a chapter WAV's sidecar file.

func Speakers

func Speakers(t core.Transcript) []string

Speakers are the transcript's speaker labels in order of appearance.

func StepTiers

func StepTiers(def int) [3]int

StepTiers are the Fast, Balanced and Quality steps of a model whose recommended steps are def (0: StepsBalanced): half, def itself, and one and a half times (OmniVoice: 16, 32, 48; VoxCPM2: 5, 10, 15).

func StoryInstruct

func StoryInstruct(lineText, scene, persona, direction string, intensity int) string

StoryInstruct is a story line's delivery instruction for models that take one: the character's persona, the scene, and the line's direction with its intensity, in Chinese when the line is (else English). "" when all three are empty.

func StoryScript

func StoryScript(lines []StoryLine) string

StoryScript is a story's lines as one manuscript (chapter lines as headings), for stats and search.

func SynthesizeParams

func SynthesizeParams(t core.Take, output string, stream bool) proto.SynthesizeParams

SynthesizeParams is the engine request for a recipe: zero parameters are left out so the model's defaults apply.

func TakesInstruct

func TakesInstruct(caps []string) bool

TakesInstruct reports whether a model with capabilities caps takes a delivery instruction: "instruct" (Qwen3-TTS CustomVoice and VoiceDesign, as the engine reports them), or a free-form voice field on a model that does not clone (an entry that only says "voiceStyle"). OmniVoice's voice field is a closed list of design attributes, not a delivery.

func TranscribeSpeakers

func TranscribeSpeakers(ctx context.Context, call func(k, n int, p *proto.TranscribeParams, out *proto.TranscribeResult) error,
	base proto.TranscribeParams, seconds float64) (proto.TranscribeResult, error)

TranscribeSpeakers transcribes base.Audio (a WAV) of seconds with a speakers model through call: in one pass, or in linked windows (each cut into a WAV of its own next to the audio) when it is longer than SpeakersWindowSeconds. call gets the window's index and the number of windows, for progress. Windows without speech are not sent. The result's segments are in file time, labelled S1, S2… in order of appearance through the whole file; its text joins theirs.

func TurnGap

func TurnGap(g TurnGaps, prev, cur LineSpec) float64

TurnGap is the silence (seconds) before line cur under pacing g; an explicit PauseAfter of prev wins.

func TurnOf

func TurnOf(prev, cur LineSpec) string

TurnOf says what kind of turn goes from line prev to line cur.

func Untitled

func Untitled(n int) string

Untitled is the title of chapter n (1-based) without one, for cue sheets and metadata ("Chapter 3"); the UI translates its own.

func VoiceAllowed

func VoiceAllowed(v core.Voice) bool

VoiceAllowed reports whether v may place calls.

func VoiceNames

func VoiceNames(script string) []string

VoiceNames are the [voice:NAME] names of a manuscript, in order of first appearance ("default" left out).

func WorkflowSummary

func WorkflowSummary(w *workflow.Workflow) string

Summary is a workflow's steps in a line ("Start → Speak → Export"), in English, for search.

func WriteCredits

func WriteCredits(dir string, credits []string) error

WriteCredits writes credits.txt in dir; nothing when there are none.

Types

type AssembleParams

type AssembleParams struct {
	Render string `json:"render"`
	Run    int    `json:"run,omitempty"` // RenderBody.Runs when submitted
}

AssembleParams are a longform.assemble job's params.

type AssembleResult

type AssembleResult struct {
	Book     string        `json:"book"` // float WAV
	Seconds  float64       `json:"seconds"`
	Bytes    int64         `json:"bytes"`
	Chapters []BookChapter `json:"chapters"`
	Cues     string        `json:"cues"`   // the cue sheet (.txt)
	Report   string        `json:"report"` // loudness report (.json)
	// Loudness is the book's own; each chapter has its report in its sidecar.
	Loudness    LoudnessReport `json:"loudness"`
	Stems       []Stem         `json:"stems,omitempty"`
	Encoded     string         `json:"encoded,omitempty"` // the M4B
	EncodeError string         `json:"encodeError,omitempty"`
}

AssembleResult is what the book is made of.

type AudioEncoder

type AudioEncoder func(ctx context.Context, in, dst string, o AudioExport) error

AudioEncoder writes the WAV in as dst in o.Format (not WAV) with o.Bitrate and o.Metadata; the WAV is already at the export's rate and channels.

type AudioExport

type AudioExport struct {
	Format     string // FormatWAV…
	Bits       int    // WAV: 16 (dithered), 24, 32 (float); FLAC: 16 or 24
	Bitrate    int    // lossy formats, bits per second (0: the encoder's choice)
	SampleRate int    // 0 keeps the source's
	Channels   int    // 0 keeps the source's
	Loudness   string // "" off, or a key of ExportLoudness
	Trim       bool   // drop leading and trailing silence
	// Metadata are the file's tags ("title", "artist"); WAV has none.
	Metadata map[string]string
}

AudioExport is how to export audio.

type AudioInfo

type AudioInfo struct {
	Rate, Channels int
	Seconds        float64
	Trimmed        float64 // seconds left after Trim
	Integrated     float64 // LUFS (loudness.Floor when silent)
	TruePeak       float64 // dBTP
}

AudioInfo describes a WAV for the Export dialog: its length, the length once trimmed, and its loudness.

func AnalyzeAudio

func AnalyzeAudio(path string) (AudioInfo, error)

AnalyzeAudio reads a WAV's AudioInfo, streaming: a long take is never held whole (thread #150).

type BatchSettings

type BatchSettings struct {
	Targets []string `json:"targets"`
	// TargetsAuto: Targets are the default (dub.DefaultTarget), switched
	// per video in that language (dub.Project.AutoRetarget).
	TargetsAuto    bool                `json:"targetsAuto,omitempty"`
	SourceLang     string              `json:"sourceLang,omitempty"`
	Voice          string              `json:"voice,omitempty"` // a VoiceRef for every speaker; "" = clone each speaker
	KeepBackground bool                `json:"keepBackground"`
	Model          string              `json:"model,omitempty"`
	Translator     string              `json:"translator,omitempty"`
	Quality        translate.Quality   `json:"quality,omitempty"`
	Timing         dub.Timing          `json:"timing,omitempty"`
	Formality      translate.Formality `json:"formality,omitempty"`
	// Dialogue: dub.DialogueOff dubs every line line by line; "" (and
	// dub.DialogueAuto) speaks conversations with the dialogue model
	// where it can, as a new project does (thread #89).
	Dialogue string `json:"dialogue,omitempty"`
}

BatchSettings are the batch queue's defaults for the videos it adds.

func DefaultBatchSettings

func DefaultBatchSettings() BatchSettings

DefaultBatchSettings are the batch queue's first settings.

type BookChapter

type BookChapter struct {
	Title   string         `json:"title"`
	File    string         `json:"file"`
	Start   float64        `json:"start"`
	Seconds float64        `json:"seconds"`
	Report  LoudnessReport `json:"report"`
}

BookChapter is a chapter of the book.

type BookInfo

type BookInfo struct {
	Author      string `json:"author,omitempty"`
	Narrator    string `json:"narrator,omitempty"`
	Year        string `json:"year,omitempty"`
	Genre       string `json:"genre,omitempty"`
	Description string `json:"description,omitempty"`
	// Cover is a PNG or JPEG of at most 8 MB (absolute path).
	Cover    string `json:"cover,omitempty"`
	Loudness string `json:"loudness,omitempty"` // LoudnessOff, LoudnessACX or LoudnessPodcast
}

BookInfo are a book's details: the metadata of encoded books, the cover and the loudness target.

type BookReport

type BookReport struct {
	Title    string         `json:"title"`
	Target   string         `json:"target,omitempty"`
	Book     LoudnessReport `json:"book"`
	Chapters []BookChapter  `json:"chapters"`
	Made     time.Time      `json:"made"`
}

BookReport is the report.json written next to the book.

type Call

type Call struct {
	ID        string    `json:"id"`
	Direction string    `json:"direction"`
	Number    string    `json:"number"`         // the other party (E.164)
	From      string    `json:"from,omitempty"` // the Twilio number
	SID       string    `json:"sid,omitempty"`  // Twilio's Call SID
	Phase     string    `json:"phase"`
	Status    string    `json:"status,omitempty"` // Twilio's last status
	Created   time.Time `json:"created"`
	Answered  time.Time `json:"answered,omitzero"`
	Ended     time.Time `json:"ended,omitzero"`
	Duration  float64   `json:"duration,omitempty"` // seconds since answered

	Mode       string `json:"mode"` // telephony.ModeAgent / ModeGreeting
	Brief      string `json:"brief,omitempty"`
	VoiceID    string `json:"voiceId,omitempty"`
	VoiceName  string `json:"voiceName,omitempty"`
	Model      string `json:"model,omitempty"` // the TTS model's repo
	Disclosure string `json:"disclosure,omitempty"`
	Greeting   string `json:"greeting,omitempty"`
	MaxMinutes int    `json:"maxMinutes"`
	Record     bool   `json:"record,omitempty"` // recording was on and disclosed

	State    string `json:"state,omitempty"` // the agent's state while live
	Takeover bool   `json:"takeover,omitempty"`

	Outcome string `json:"outcome,omitempty"`
	Note    string `json:"note,omitempty"`    // the agent's note with its outcome
	Summary string `json:"summary,omitempty"` // written after the call
	End     string `json:"end,omitempty"`     // telephony.End*
	Error   string `json:"error,omitempty"`

	Transcript []telephony.Line        `json:"transcript,omitempty"`
	Timeline   []CallEvent             `json:"timeline,omitempty"`
	Turns      []telephony.TurnLatency `json:"turns,omitempty"`
	Recording  string                  `json:"recording,omitempty"` // file name in the calls folder
}

Call is a phone call: its setup, its live state and how it went.

func (Call) Live

func (c Call) Live() bool

Live reports whether the call is still going (or about to).

func (Call) Title

func (c Call) Title() string

Title is the call's line in lists: its brief's first line.

type CallChanged

type CallChanged struct {
	ID      string
	Call    *Call
	Deleted bool
}

CallChanged is published after a call changes (Call is a copy) or is deleted. Topic "call.changed".

func (CallChanged) Topic

func (CallChanged) Topic() string

type CallEvent

type CallEvent struct {
	At     time.Time `json:"at"`
	Kind   string    `json:"kind"` // CallEvent* or a Twilio status
	Detail string    `json:"detail,omitempty"`
}

CallEvent is a step of a call's timeline.

type CallOptions

type CallOptions struct {
	AccountSID string
	PublicURL  string
	Number     string // the Twilio number calls come from
	UserName   string
	// Disclosure is the outbound disclosure's template ("{name}" is the
	// user's or the voice's name); InboundDisclosure the incoming one's.
	Disclosure        string
	InboundDisclosure string
	// Voice speaks incoming calls.
	Voice          string
	Greeting       string
	Inbound        string // telephony.ModeGreeting / ModeAgent
	InboundBrief   string
	InboundMinutes int
	Concurrent     int
	Record         bool
	STTModel       string
	// GatewayOn: the gateway listens (calls can be placed).
	GatewayOn bool
}

CallOptions are the settings calls follow (settings.Calls, mapped by the app), read when needed.

type CallRequest

type CallRequest struct {
	To      string // E.164 (normalised by the caller or here)
	Brief   string
	VoiceID string
	// Disclosure is said first; nil = the default template, "" = none.
	Disclosure *string
	MaxMinutes int // 2–30
}

CallRequest places a call.

type Calls

type Calls struct {
	// contains filtered or unexported fields
}

Calls is the calls service. Goroutine-safe.

func NewCalls

func NewCalls(cfg CallsConfig) *Calls

NewCalls makes the calls service.

func (*Calls) CallVoice

func (s *Calls) CallVoice(ctx context.Context, id string) (core.Voice, error)

CallVoice reads a voice that may place calls.

func (*Calls) Close

func (s *Calls) Close(ctx context.Context)

Close ends the calls in progress and waits for them.

func (*Calls) Delete

func (s *Calls) Delete(ctx context.Context, id string) error

Delete removes a call that has ended, and its recording.

func (*Calls) GatewayLog

func (s *Calls) GatewayLog() []GatewayEntry

GatewayLog is the recent gateway events, newest first.

func (*Calls) Get

func (s *Calls) Get(ctx context.Context, id string) (Call, error)

Get returns a call: the live state while it runs.

func (*Calls) Hangup

func (s *Calls) Hangup(ctx context.Context, id string) error

Hangup ends a call.

func (*Calls) Hooks

func (s *Calls) Hooks() telephony.Hooks

Hooks is the gateway's side of the service.

func (*Calls) List

func (s *Calls) List(ctx context.Context, limit int) ([]store.CallRecord, error)

List returns recent calls (records, no transcripts), newest first.

func (*Calls) PhonePreview

func (s *Calls) PhonePreview(ctx context.Context, voiceID, text string) (string, error)

PhonePreview renders text in a voice and returns it as a phone carries it (8 kHz μ-law, back to 16-bit WAV at 8 kHz) for the setup page.

func (*Calls) Place

func (s *Calls) Place(ctx context.Context, req CallRequest) (Call, error)

Place places an outbound call.

func (*Calls) Reconcile

func (s *Calls) Reconcile(ctx context.Context) error

Reconcile closes calls a previous run left open (the app quit during them).

func (*Calls) RecordingPath

func (s *Calls) RecordingPath(c Call) string

RecordingPath is the absolute path of a call's recording ("" = none).

func (*Calls) Running

func (s *Calls) Running() (int, int)

Running reports how many calls are in progress, and the limit.

func (*Calls) Say

func (s *Calls) Say(id, text string) error

Say speaks the user's line in the call now.

func (*Calls) Takeover

func (s *Calls) Takeover(id string, on bool) error

Takeover pauses (on) or resumes the agent of a live call.

type CallsConfig

type CallsConfig struct {
	Store     store.Calls
	Bus       *core.Bus
	Scheduler jobs.Scheduler
	// Takes renders speech (svc.Render).
	Takes  *Takes
	Voices core.VoiceService
	// Options are the settings.
	Options func() CallOptions
	// Twilio returns the REST client with the account's credentials (the
	// auth token from the Keychain), or an error.
	Twilio func() (*telephony.Client, error)
	// Recipe is the take recipe that speaks text in a voice (the app
	// chooses the model).
	Recipe func(v core.Voice, text string) (core.Take, error)
	// Chat runs the language model (streaming with onDelta); nil or
	// failing: calls cannot run in agent mode.
	Chat func(ctx context.Context, msgs []telephony.Message, onDelta func(string)) (string, error)
	// Signed is told when a webhook passed the signature check.
	Signed func()
	// CacheDir holds temporary audio ("" = the system's temp dir).
	CacheDir string
	Now      func() time.Time
	Logf     func(string, ...any)
	// NoStreamAfter is how long an answered call may wait for its media
	// stream before it is hung up; 0 = 20 s.
	NoStreamAfter time.Duration
	// Endpoint tunes the agents' endpointer (tests).
	Endpoint telephony.EndpointOptions
}

CallsConfig wires the calls service.

type CastMember

type CastMember struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Voice string `json:"voice,omitempty"` // a VoiceRef; "" = the default voice
	// Persona is the character's performance baseline ("a seven-year-old
	// girl, lively, coaxing"), for models that take an instruction.
	Persona string `json:"persona,omitempty"`
	// Baseline is the character's usual feeling in the story (an
	// Emotion): its steady lines are said in it, faintly.
	Baseline string `json:"baseline,omitempty"`
}

CastMember is a character of a story and its voice.

type ChapterParams

type ChapterParams struct {
	Render     string               `json:"render"`
	Run        int                  `json:"run,omitempty"` // RenderBody.Runs when submitted
	Index      int                  `json:"index"`
	Title      string               `json:"title,omitempty"`
	Model      string               `json:"model"`
	Lang       string               `json:"lang,omitempty"`
	Seed       int64                `json:"seed,omitempty"`
	Voices     map[string]core.Take `json:"voices"`
	Lines      []LineSpec           `json:"lines"`
	Production Production           `json:"production"`
	Lexicon    []LexiconEntry       `json:"lexicon,omitempty"`
	Loudness   string               `json:"loudness,omitempty"`
	Scene      string               `json:"scene,omitempty"` // the story's (instructions)
	// Workflow is "story" or "audiobook" (RenderParams.Workflow).
	Workflow string `json:"workflow,omitempty"`
	// Output is the chapter's WAV (absolute); its sidecar is Output+".json".
	Output string `json:"output"`
}

ChapterParams are a longform.chapter job's params: everything the chapter needs, so it can run again after a restart.

type ChapterResult

type ChapterResult struct {
	Output       string  `json:"output"`
	Key          string  `json:"key"`
	SampleRate   int     `json:"sampleRate"`
	Channels     int     `json:"channels"`
	Frames       int64   `json:"frames"`
	AudioSeconds float64 `json:"audioSeconds"`
	Seconds      float64 `json:"seconds"` // wall time
	Chunks       int     `json:"chunks"`
	Cached       int     `json:"cached"` // chunks from the cache
	// Reused: the file of an earlier run of this render was kept.
	Reused bool `json:"reused,omitempty"`
	// Turns are the merged turns (lines of one character made as one)
	// split back into their lines; TurnsUnsplit the ones that could not
	// be, made line by line instead.
	Turns        int `json:"turns,omitempty"`
	TurnsUnsplit int `json:"turnsUnsplit,omitempty"`
	// Tracks are the stretches of a character's lines said in one
	// synthesis and cut apart (story_track.go), TrackLines their lines;
	// TracksFailed the ones that could not be cut, made line by line.
	Tracks       int `json:"tracks,omitempty"`
	TrackLines   int `json:"trackLines,omitempty"`
	TracksFailed int `json:"tracksFailed,omitempty"`
	// Dialogues are the whole-dialogue segments (story_dialogue.go),
	// DialogueLines their lines from the dialogue model, DialogueRedone
	// the lines it made twice, DialogueFailed the lines (or segments)
	// made on the story's model instead.
	Dialogues      int `json:"dialogues,omitempty"`
	DialogueLines  int `json:"dialogueLines,omitempty"`
	DialogueRedone int `json:"dialogueRedone,omitempty"`
	DialogueFailed int `json:"dialogueFailed,omitempty"`
	// Levelled counts the lines brought toward their character's loudness.
	Levelled int               `json:"levelled,omitempty"`
	Report   LoudnessReport    `json:"report"`
	Warnings []core.TakeNotice `json:"warnings,omitempty"`
	Lines    []LinePlace       `json:"lines"`
}

ChapterResult is a chapter job's result and its sidecar.

func ReadChapter

func ReadChapter(wavPath string) (ChapterResult, error)

ReadChapter reads a chapter's sidecar.

type ChapterSpec

type ChapterSpec struct {
	Title string     `json:"title,omitempty"`
	Lines []LineSpec `json:"lines"`
}

ChapterSpec is one chapter: a title ("" = untitled) and its lines.

type Config

type Config struct {
	Store store.Store
	Bus   *core.Bus
	// Scheduler runs generation jobs. Nil until the job queue is wired:
	// Generate then fails with core.ErrUnsupported.
	Scheduler jobs.Scheduler
	// Licences gates models whose licence needs accepting; nil gates nothing.
	Licences core.LicenceService
	// Ready reports whether a model can be used now: nil, or an error
	// wrapping core.ErrNotDownloaded (from the hub). Nil skips the check.
	Ready func(ctx context.Context, model string) error
	// DraftDelay is how long drafts wait for more edits before they are
	// written; 0 means 750 ms.
	DraftDelay time.Duration
	// Now is the clock (tests); nil means time.Now.
	Now func() time.Time
	// Async runs the background work bus handlers hand off (saving the take
	// a job made); nil means a new goroutine. Tests without goroutines
	// pass a function that runs it at once.
	Async func(func())
	// Logf reports failures of background work (saving a generated take, a
	// draft); nil means log.Printf.
	Logf func(format string, args ...any)

	// Synth returns the executor of one tts.synthesize call (the engine's,
	// engine.Executor), asked each time a render starts, so the engine
	// may be connected after the services. nil, or a nil executor, fails
	// renders with engine_unavailable (retryable).
	Synth func() jobs.Executor
	// ModelPath returns the local snapshot directory of a model, or an
	// error wrapping core.ErrNotDownloaded (as engine.ExecutorOptions).
	// Renders fill it into every engine call; nil leaves it out.
	ModelPath func(ctx context.Context, model string) (string, error)
	// Models describes a model (from the catalogue); nil uses defaults.
	Models func(repo string) ModelInfo
	// Replace maps a recipe that names a model AudioSmith removed to its
	// replacement (the catalogue's alias table: model, and a voice,
	// language or parameter the replacement can't take) and reports
	// whether it did. Generate, Preview and every render call it, so old
	// projects, workflows and history recipes keep working. nil maps
	// nothing.
	Replace func(t *core.Take) bool
	// CacheDir holds the render's chunk cache, temporary files and
	// previews; "" means AudioSmith in the system's temporary directory.
	CacheDir string
	// KeepTakes caps the history (settings.Studio.KeepTakes): beyond it
	// the oldest takes neither starred nor in a project are deleted. nil or
	// 0 keeps every take.
	KeepTakes func() int

	// M3 (longform.go). DataDir holds longform renders (<DataDir>/renders);
	// "" means the parent of the store's audio directory. Encode returns
	// the engine's media.encode executor, or nil while the engine has
	// none: books are then WAV only.
	DataDir string
	Encode  func() jobs.Executor

	// Watermark marks every finished render (watermark.go); nil: none.
	Watermark WatermarkFunc

	// Engine returns the engine's executor of a method other than
	// tts.synthesize, for renders that align or check what they made
	// (story tracks: Aligner, Recognizer are the forced aligner's and
	// the speech recognizer's repos); nil: renders do neither.
	Engine              func(method string) jobs.Executor
	Aligner, Recognizer string

	// Credit is the attribution a take of model spoken by voice must
	// carry (a VOICEVOX character's, thread #171; "" = none): renders
	// record it with the take. nil: none.
	Credit func(ctx context.Context, model, voice string) string
}

Config wires the services. Store and Bus are required.

type DialogueBlockInfo

type DialogueBlockInfo struct {
	// Chapter indexes the spec's chapters; Index is its lines' Block.
	Chapter int
	Index   int
	Span    text.Span // in the manuscript: the opening marker to the closer
	// Speakers are the named speakers in order (the cast's spelling);
	// Uncast those without a voice, which are given one when the book
	// renders (they would read in the narrator's).
	Speakers []string
	Uncast   []string
	Turns    int // lines with a speaker
	Lines    int // lines read (turns and narration)
	Unknown  int // "?" turns
	// Language is false for a block in a language the dialogue models do
	// not speak (lang): read line by line.
	Language bool
	Lang     string
	// Tags are the delivery and non-verbal tags of its turns, which the
	// dialogue model leaves out.
	Tags []string
}

DialogueBlockInfo is one dialogue block of a compiled manuscript, for the inspector and the API.

type Drafts

type Drafts struct {
	// contains filtered or unexported fields
}

Drafts implements core.DraftService over store.Documents ("draft:<key>").

Save encodes the value at once (so the caller may keep mutating it) and writes it after the delay has passed without another Save of the same key, on a timer goroutine. Writes are serialized and always write the newest value; one equal to what is stored is skipped. Each write publishes core.DraftSaved.

func (*Drafts) Close

func (s *Drafts) Close(ctx context.Context) error

Close refuses later Saves and writes the pending ones.

func (*Drafts) Delete

func (s *Drafts) Delete(ctx context.Context, key string) error

Delete drops a pending draft and the stored one.

func (*Drafts) Flush

func (s *Drafts) Flush(ctx context.Context) error

Flush writes every pending draft now.

func (*Drafts) Load

func (s *Drafts) Load(ctx context.Context, key string, v any) (bool, error)

Load decodes the newest draft of key, pending or stored, into v.

func (*Drafts) Save

func (s *Drafts) Save(key string, v any)

type DubChanged

type DubChanged struct {
	ID      string
	Project *dub.Project // a copy; nil when Deleted
	Deleted bool
}

DubChanged is published after a dub project is saved or deleted. Topic "dub.changed".

func (DubChanged) Topic

func (DubChanged) Topic() string

type DubDialogueModel

type DubDialogueModel struct {
	Repo, Family, Revision string
	// Languages are the base codes it speaks ("zh", "en").
	Languages []string
	// Blocked says why this Mac cannot run it ("" = it can): too little
	// memory.
	Blocked string
}

DubDialogueModel is a dialogue model a dub can speak its conversations with (DubModels.Dialogue).

type DubModelCaps

type DubModelCaps struct {
	Clone, Duration, Instruct, Speed, Steps, Guidance bool
	// CloneInstruct: its clones take the instruction too (VoxCPM2;
	// CloneTakesInstruct).
	CloneInstruct bool
	// NeedsReference: the model only clones: lines cast
	// with a voice that carries no reference (the default voice, a
	// design) clone their speaker instead.
	NeedsReference bool
	// CloneAudioOnly: clones from the reference audio without its
	// transcript (catalog.CapCloneAudioOnly): how a line in another
	// language than its speaker's clip is cloned.
	CloneAudioOnly bool
	// Languages maps BCP-47 codes to the model's language values
	// ("zh" → "Chinese"); nil = it takes codes, or has no language.
	Languages map[string]string
}

DubModelCaps are what a TTS model can do, as the pipeline needs it.

type DubModels

type DubModels struct {
	STT, Align, Diarize, Separate, Enhance string
	// Speakers transcribes and labels speakers in one pass (thread #48:
	// MOSS-Transcribe-Diarize): the transcript of a source with more than
	// one speaker, in a language it knows (SpeakersLanguages; nil = any).
	// When it is not downloaded, STT and Diarize (Sortformer) do it, and
	// the stage warns DubWarnSpeakersModel.
	Speakers          string
	SpeakersLanguages []string
	// WordTimes: STT times words itself (no aligner needed).
	WordTimes bool
	// STTLanguages are the base languages STT knows (nil: any); OtherSTT
	// (OtherWordTimes) transcribes the rest (thread #46: Qwen3-ASR, then
	// Whisper). "" = STT for every language.
	STTLanguages   []string
	OtherSTT       string
	OtherWordTimes bool
	// Dialogue are the dialogue models the dub can speak conversations
	// with, the default first (thread #89: SoulX-Podcast); none: every
	// line line by line.
	Dialogue []DubDialogueModel
}

DubModels are the models the pipeline uses besides the TTS model (repo ids; "" = that step is skipped).

func (DubModels) DialogueBlocked

func (m DubModels) DialogueBlocked(p *dub.Project, lang string) string

DialogueBlocked says why lang's track of p is not spoken by its dialogue model ("" when it is, as far as the project and this Mac go; the download is checked when it runs): a dub.DialogueWhy* code, DubDialogueMemory, or "model" when no dialogue model is offered.

func (DubModels) DialogueFor

func (m DubModels) DialogueFor(repo string) (DubDialogueModel, bool)

DialogueFor is the dialogue model a project asks for (its repo; "": the first offered), and whether it is offered.

func (DubModels) STTFor

func (m DubModels) STTFor(lang string) (string, bool)

STTFor is the speech-to-text model for a language (BCP-47; "" = detected) and whether it times words itself.

func (DubModels) SpeakersFor

func (m DubModels) SpeakersFor(lang string) string

SpeakersFor is the speakers model for a source language (BCP-47; "" = detected), "" when there is none or it does not know the language.

type Dubs

type Dubs struct {
	// contains filtered or unexported fields
}

Dubs is the dub service. Goroutine-safe.

func NewDubs

func NewDubs(cfg DubsConfig) *Dubs

NewDubs builds the service and registers its executors.

func (*Dubs) Active

func (s *Dubs) Active(ctx context.Context, id string) ([]jobs.Job, error)

Active lists a project's unfinished jobs: waiting, queued or running. Interrupted ones are not: they do not run again without a Retry, and a project should not look busy because of them (#101 H2).

func (*Dubs) BatchSettings

func (s *Dubs) BatchSettings(ctx context.Context) BatchSettings

BatchSettings reads the batch queue's settings.

func (*Dubs) Cancel

func (s *Dubs) Cancel(ctx context.Context, id string) error

Cancel cancels a project's unfinished jobs (interrupted ones too) and its probe, and forgets its run.

func (*Dubs) CancelProbes

func (s *Dubs) CancelProbes()

CancelProbes stops every probe (the app quits). It does not wait.

func (*Dubs) CloseWatch

func (s *Dubs) CloseWatch()

CloseWatch stops the scan loop (the app quits); the folder stays watched for the next start.

func (*Dubs) Create

func (s *Dubs) Create(ctx context.Context, p *dub.Project) (*dub.Project, error)

Create saves a new project (its ID chosen when empty).

func (*Dubs) Delete

func (s *Dubs) Delete(ctx context.Context, id string) error

Delete cancels a project's jobs, waits for them to end, and removes the project with its files. A job still running after the wait (one that does not heed its cancel) makes it ErrBusy: removing the folder under it would leave a stray one behind, or break the job (#101 M3).

func (*Dubs) Dir

func (s *Dubs) Dir(id string) string

Dir is the directory of project id's files.

func (*Dubs) Enqueue

func (s *Dubs) Enqueue(ctx context.Context, paths []string, bs BatchSettings) ([]string, map[string]error)

Enqueue adds videos to the batch queue with settings bs and starts their runs. It returns the projects made; a file that could not be added is in errs (by path).

func (*Dubs) Executors

func (s *Dubs) Executors() map[string]jobs.Executor

Executors are the service's executors by job kind (registered by NewDubs; tests with a fake scheduler run them themselves).

func (*Dubs) Export

func (s *Dubs) Export(ctx context.Context, req ExportRequest, progress func(float64)) (ExportResult, error)

Export writes one export (on the caller's goroutine).

func (*Dubs) ExportJob

func (s *Dubs) ExportJob(ctx context.Context, req ExportRequest) (string, error)

ExportJob queues an export (cpu lane) and returns its job id.

func (*Dubs) FreeIdle

func (s *Dubs) FreeIdle(ctx context.Context, after time.Duration, exported func(id string) time.Time, skip func(id string) bool) (int, int64)

FreeIdle frees the working files of the dubs exported (exported: an export the app recorded, besides Project.Exported) and not touched for after; skip names dubs to leave (the one open: asked again, with the times, just before a dub's files go). It returns how many dubs it freed and the bytes.

func (*Dubs) FreeWork

func (s *Dubs) FreeWork(ctx context.Context, id string) (int64, error)

FreeWork frees dub id's working files now and returns the bytes freed. It refuses (core.ErrBusy) while a job of the dub runs. The audio and the stems go only while the source is there to make them again.

func (*Dubs) Get

func (s *Dubs) Get(ctx context.Context, id string) (*dub.Project, error)

Get reads a project (a copy of the cached one, dub_cache.go).

func (*Dubs) LineRecipe

func (s *Dubs) LineRecipe(ctx context.Context, p *dub.Project, id, l string) (core.Take, string, error)

LineRecipe is the recipe of segment id in lang as the pipeline would render it, with the reason its voice fell back to the default ("").

func (*Dubs) List

func (s *Dubs) List(ctx context.Context, q store.DubQuery) ([]store.DubRecord, error)

List lists projects (without their documents).

func (*Dubs) MixedTrack

func (s *Dubs) MixedTrack(p *dub.Project, l string) string

MixedTrack is lang's mixed track (absolute), "" when there is none.

func (*Dubs) Path

func (s *Dubs) Path(id, name string) string

Path is a project file's absolute path ("" for "").

func (*Dubs) PauseWatch

func (s *Dubs) PauseWatch(ctx context.Context, paused bool)

PauseWatch pauses (or resumes) the watch folder.

func (*Dubs) Plan

func (s *Dubs) Plan(p *dub.Project, req RunRequest) []string

Plan lists the stage keys a request would run (for the UI's summary).

func (*Dubs) Probe

func (s *Dubs) Probe(ctx context.Context, id string) error

Probe reads what project id's source is and saves it: a URL's metadata (Source.Meta, then its cover, Meta.Thumbnail), or a file's length, picture and poster. A link that cannot be read (a site yt-dlp does not know, a private video, one that needs a sign-in) saves why in Meta.Error and returns it. A source already downloaded or read is left alone. A new probe of the project replaces one going on.

func (*Dubs) Probing

func (s *Dubs) Probing(id string) bool

Probing reports whether project id's source is being probed.

func (*Dubs) Queue

func (s *Dubs) Queue(ctx context.Context) ([]store.DubRecord, error)

Queue lists the batch queue's projects, newest change first.

func (*Dubs) Rebuild

func (s *Dubs) Rebuild(ctx context.Context, id string) (map[string]string, error)

Rebuild decodes a freed dub's audio again (the original's playback, a line's own clip); a run makes the rest.

func (*Dubs) RestoreWatch

func (s *Dubs) RestoreWatch(ctx context.Context)

RestoreWatch resumes the watch folder saved by an earlier run.

func (*Dubs) Resume

func (s *Dubs) Resume(ctx context.Context, id string) (map[string]string, error)

Resume continues an interrupted run (Project.Run) where it stopped.

func (*Dubs) Retry

func (s *Dubs) Retry(ctx context.Context, id string) error

Retry runs a batch project again from where it stopped.

func (*Dubs) Run

func (s *Dubs) Run(ctx context.Context, id string, req RunRequest) (map[string]string, error)

Run queues the stages a request needs, as one graph, and returns the job ids by stage key. Stages already done are skipped unless forced; a stage whose prerequisites are not done brings them in.

func (*Dubs) ScanWatch

func (s *Dubs) ScanWatch(ctx context.Context) []string

ScanWatch scans the watched folder once (the loop calls it every 5 s) and enqueues the files that became stable. It returns them.

func (*Dubs) SetBatchSettings

func (s *Dubs) SetBatchSettings(ctx context.Context, bs BatchSettings) error

SetBatchSettings saves the batch queue's settings.

func (*Dubs) SetCookies

func (s *Dubs) SetCookies(id, path string)

SetCookies gives project id's next download a cookies.txt ("" = none).

func (*Dubs) StartWatch

func (s *Dubs) StartWatch(ctx context.Context, dir string) error

StartWatch watches dir: files there now are ignored, new ones join the queue with the batch settings of the moment.

func (*Dubs) StopWatch

func (s *Dubs) StopWatch(ctx context.Context)

StopWatch stops watching.

func (*Dubs) Touch

func (s *Dubs) Touch(id string)

Touch records that dub id was opened (its working files stay DubFreeAfter from now).

func (*Dubs) TrackMixer

func (s *Dubs) TrackMixer(p *dub.Project, l string) (*dub.TrackMixer, error)

TrackMixer is a project's live mix of lang (the A/B player): what the track would be with the lines as rendered now.

func (*Dubs) Update

func (s *Dubs) Update(ctx context.Context, id string, fn func(*dub.Project) error) (*dub.Project, error)

Update applies fn to the saved project, saves it and publishes it. fn may return an error to change nothing; when it changes nothing, nothing is saved or published (and UpdatedAt stays).

func (*Dubs) Watch

func (s *Dubs) Watch() WatchState

Watch is the watch folder's state now.

func (*Dubs) WorkGone

func (s *Dubs) WorkGone(p *dub.Project) bool

WorkGone reports whether some of p's working files are gone (freed): a run makes them again.

type DubsConfig

type DubsConfig struct {
	Store     store.Dubs
	Bus       *core.Bus
	Scheduler jobs.Scheduler
	// Engine returns the executor of an engine method (engine.Executor
	// in the method's role, dub.RoleOf); nil or a nil executor fails the
	// stage with engine_unavailable (retryable).
	Engine func(method string) jobs.Executor
	// Render renders lines through the take pipeline (svc.Render).
	Render    *Takes
	ModelPath func(ctx context.Context, repo string) (string, error)
	// Models are the pipeline's models now (from the catalogue/settings).
	Models func() DubModels
	// Caps describes a TTS model.
	Caps func(repo string) DubModelCaps
	// Voice resolves a VoiceRef for a model (saved voices, designs,
	// gallery voices). Goroutine-safe. nil: every cast voice is the
	// default one.
	Voice func(ctx context.Context, ref, model, lang string) (dub.VoiceSpec, error)
	// Translator returns the translator for a project's settings, or an
	// error with translate.CodeNoLLM / translate.CodeNoKey when none is set
	// up; Extractor the glossary extractor (nil: no Auto glossary).
	Translator func(ctx context.Context, s dub.Settings) (translate.Translator, error)
	Extractor  func() *translate.Extractor
	// TranslateLane is the lane of translation jobs (net; gpu when the
	// route is the engine's own LLM). nil = net.
	TranslateLane func() jobs.Lane
	// YtDlp is the URL importer ("" path = URL import is off).
	YtDlp func() dub.YtDlp
	// Documents keep the batch queue's settings and watch folder.
	Documents store.Documents
	// WatchEvery is the watch folder's scan interval (0 = 5 s).
	WatchEvery time.Duration
	Now        func() time.Time
	Logf       func(string, ...any)
}

DubsConfig wires the dub service. Store, Bus and Scheduler are required.

type EmotionBeat

type EmotionBeat struct {
	Who       string
	Emotion   string
	Intensity int
	Turn      bool
	Fixed     bool
}

EmotionBeat is one line as the smoothing sees it: who says it, its emotion and intensity, whether it is a turn, and whether the user set it (Fixed: kept as it is).

func SmoothEmotions

func SmoothEmotions(beats []EmotionBeat) []EmotionBeat

SmoothEmotions applies the continuity rules to a scene's beats, in order, and returns them: emotions normalised (unknown ones are steady), a steady line at most intensity 1, turns and strong lines kept few, and the same character's consecutive lines at most one intensity apart, without swinging between pleasant and unpleasant feelings, unless the later one is a turn. Fixed beats are kept as they are and the others follow them.

type EncodeChapter

type EncodeChapter struct {
	Title string  `json:"title"`
	Start float64 `json:"start"`
	End   float64 `json:"end"`
}

EncodeChapter is a chapter mark (seconds into the input).

type EncodeMetadata

type EncodeMetadata struct {
	Title       string `json:"title,omitempty"`
	Author      string `json:"author,omitempty"`
	Narrator    string `json:"narrator,omitempty"`
	Year        string `json:"year,omitempty"`
	Genre       string `json:"genre,omitempty"`
	Description string `json:"description,omitempty"`
}

EncodeMetadata are the file's tags (iTunes atoms in M4B: ©nam, ©ART, aART, ©alb, ©wrt for the narrator, ©day, ©gen, desc/©cmt).

type EncodeParams

type EncodeParams struct {
	Input  string       `json:"input"`  // WAV (any bit depth, RF64 allowed)
	Output proto.Output `json:"output"` // path + format: "m4b", "m4a" (AAC); later "mp3"
	Codec  string       `json:"codec,omitempty"`
	// Bitrate in bits per second; 0 = the encoder's choice for speech
	// (64 kb/s mono, 96 kb/s stereo AAC).
	Bitrate    int             `json:"bitrate,omitempty"`
	SampleRate int             `json:"sampleRate,omitempty"` // 0 = the input's
	Chapters   []EncodeChapter `json:"chapters,omitempty"`
	Metadata   EncodeMetadata  `json:"metadata"`
	Cover      string          `json:"cover,omitempty"` // PNG or JPEG
}

EncodeParams are media.encode's params (media worker, a job): one audio file (WAV) encoded into Output, with chapters, metadata and a cover.

type EncodeResult

type EncodeResult struct {
	Output   string  `json:"output"`
	Format   string  `json:"format"`
	Bytes    int64   `json:"bytes"`
	Duration float64 `json:"duration"`
	Bitrate  int     `json:"bitrate,omitempty"`
}

EncodeResult is media.encode's result.

type ExportRequest

type ExportRequest struct {
	Dub    string `json:"dub"`
	Format string `json:"format"` // a dub.Export* format
	// Lang is the language of single-language exports; "" or
	// dub.OrigTrack = the source (subtitles).
	Lang string `json:"lang,omitempty"`
	// Tracks are an MP4's audio tracks (languages, dub.OrigTrack for
	// the original), Default the one players pick.
	Tracks  []string `json:"tracks,omitempty"`
	Default string   `json:"default,omitempty"`
	// Dual subtitles (translated + original); Subtitles adds soft
	// subtitle tracks to an MP4.
	Dual      bool `json:"dual,omitempty"`
	Subtitles bool `json:"subtitles,omitempty"`
	Bits      int  `json:"bits,omitempty"` // WAV
	// Output is the file to write (absolute).
	Output string `json:"output"`
}

ExportRequest asks for one export file.

type ExportResult

type ExportResult struct {
	Output string `json:"output"`
	Bytes  int64  `json:"bytes"`
	Format string `json:"format"`
}

ExportResult is what an export wrote.

type ExportedAudio

type ExportedAudio struct {
	Seconds float64 // the output's length
	// Offset is how much of the source's start was trimmed, seconds:
	// times in the source (chunks, markers) move back by it.
	Offset   float64
	Bytes    int64
	Loudness float64 // integrated, LUFS, when a target was applied
}

ExportedAudio is what an export wrote.

func ExportAudio

func ExportAudio(ctx context.Context, src, dst string, o AudioExport, enc AudioEncoder) (ExportedAudio, error)

ExportAudio writes the WAV src to dst as o says; enc writes the formats other than WAV. dst is written whole or not at all. Without a loudness target it streams (export_stream.go); a target needs the whole take.

A WAV gets o.Metadata's "comment" and "artist" as a LIST/INFO chunk (a VOICEVOX character's credit, thread #171); the other formats get all of o.Metadata from their encoder.

type GalleryFavorites

type GalleryFavorites struct{ Store store.Favorites }

GalleryFavorites persists the gallery's favorites (gallery.FavoriteStore) in the store's favorites table, scope FavoritesScope.

func (GalleryFavorites) LoadFavorites

func (g GalleryFavorites) LoadFavorites(ctx context.Context) ([]string, error)

func (GalleryFavorites) SaveFavorite

func (g GalleryFavorites) SaveFavorite(ctx context.Context, id string, on bool) error

type GatewayEntry

type GatewayEntry struct {
	At      time.Time
	CallSID string
	Event   string // a Twilio status, "stream", or a telephony.Reject* reason
}

GatewayEntry is a line of the setup page's call log.

type ImportedAudio

type ImportedAudio struct {
	Samples  []float32
	Rate     int
	Channels int
}

ImportedAudio is decoded audio: interleaved samples at Rate with Channels.

type Isolation

type Isolation struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
	Title     string    `json:"title"`
	Input     string    `json:"input"` // the file isolated, as picked
	Video     bool      `json:"video,omitempty"`
	Duration  float64   `json:"duration,omitempty"` // seconds
	State     string    `json:"state"`
	Job       string    `json:"job,omitempty"`
	Error     string    `json:"error,omitempty"` // why it failed
	ErrorCode string    `json:"errorCode,omitempty"`
	// The stems written ("" none yet): file names in the folder.
	Vocals     string   `json:"vocals,omitempty"`
	Background string   `json:"background,omitempty"`
	Clean      string   `json:"clean,omitempty"`
	Separator  string   `json:"separator,omitempty"`
	Denoiser   string   `json:"denoiser,omitempty"`
	Warnings   []string `json:"warnings,omitempty"`
}

Isolation is one file's stems.

type IsolationChanged

type IsolationChanged struct {
	Isolation Isolation
	Deleted   bool
}

IsolationChanged follows a saved or deleted isolation.

func (IsolationChanged) Topic

func (IsolationChanged) Topic() string

type Isolations

type Isolations struct {
	// contains filtered or unexported fields
}

Isolations is the voice isolator's library and jobs. Goroutine-safe.

func NewIsolations

func NewIsolations(cfg IsolationsConfig) *Isolations

NewIsolations builds the service and registers its executor.

func (*Isolations) Delete

func (s *Isolations) Delete(ctx context.Context, id string) error

Delete cancels isolation id's job, waits for it to end, and removes its folder. A job still running after the wait (one that does not heed its cancel) makes it ErrBusy: removing the folder under it would leave a stray one behind when the engine writes its stems (code review 1102 M5, as Dubs.Delete since #101 M3).

func (*Isolations) Dir

func (s *Isolations) Dir(id string) string

Dir is isolation id's folder.

func (*Isolations) Executor

func (s *Isolations) Executor() jobs.Executor

Executor runs isolation jobs (registered by NewIsolations).

func (*Isolations) Get

func (s *Isolations) Get(_ context.Context, id string) (Isolation, error)

Get reads isolation id.

func (*Isolations) List

func (s *Isolations) List(ctx context.Context) ([]Isolation, error)

List reads every isolation, newest first.

func (*Isolations) Missing

func (s *Isolations) Missing(ctx context.Context) []string

Missing are the models an isolation needs that are not downloaded: the separator (required), then the denoiser (its stem is skipped without it).

func (*Isolations) Path

func (s *Isolations) Path(id, name string) string

Path is a file of isolation id ("" for "").

func (*Isolations) Start

func (s *Isolations) Start(ctx context.Context, input string) (Isolation, error)

Start makes an isolation of input and queues its job. It refuses when the separation model is not downloaded (an error wrapping core.ErrNotDownloaded, naming the model).

func (*Isolations) Sweep

func (s *Isolations) Sweep(ctx context.Context) int

Sweep removes, once no isolation job runs, the folders without an isolation.json (a Delete that raced a late write, before the wait) and the decoded inputs of isolations that ended (done or failed, isolateSettled ago); it returns how many it removed. Call it at startup.

type IsolationsConfig

type IsolationsConfig struct {
	Dir       string
	Bus       *core.Bus
	Scheduler jobs.Scheduler // nil: Start fails with core.ErrUnsupported
	// Engine returns the executor of one engine method; nil (or a nil
	// executor) fails with engine_unavailable.
	Engine func(method string) jobs.Executor
	// ModelPath is a model's local snapshot, or an error wrapping
	// core.ErrNotDownloaded.
	ModelPath func(ctx context.Context, repo string) (string, error)
	// Models are the separation and denoising models' repos.
	Models func() (separate, enhance string)
	Now    func() time.Time
	Logf   func(format string, args ...any)
}

IsolationsConfig wires the service. Dir and Bus are required.

type LexiconEntry

type LexiconEntry struct {
	Word string `json:"word"`
	Say  string `json:"say"`
}

LexiconEntry is one of a book's pronunciations: Word is said as Say.

type Library

type Library struct {
	// contains filtered or unexported fields
}

Library is the project library beyond core.ProjectService.

func (*Library) Counts

func (l *Library) Counts(ctx context.Context, search string) (map[string]int, error)

Counts counts the library's categories for a search.

func (*Library) DeleteExport

func (l *Library) DeleteExport(ctx context.Context, id string) error

DeleteExport deletes an export record; the file stays, unless it is a sample's copy in the data folder (<data>/samples/<id>/, code review 1102 L1): only the app made it.

func (*Library) Export

func (l *Library) Export(ctx context.Context, id string) (core.Export, error)

Export returns one export record.

func (*Library) Exports

func (l *Library) Exports(ctx context.Context, search string, limit int) ([]core.Export, error)

Exports lists the export records whose title or path has search ("" = all), newest first; limit 0 = no limit (the Assets page, 0.5 F5).

func (*Library) LoadDoc

func (l *Library) LoadDoc(ctx context.Context, id string) (core.Project, LongformDoc, error)

LoadDoc reads a Stories or Audiobook project's document.

func (*Library) RecordExport

func (l *Library) RecordExport(ctx context.Context, e core.Export) (core.Export, error)

RecordExport records that a file was exported; ID, time and size are filled in.

func (*Library) Rename

func (l *Library) Rename(ctx context.Context, id, title string) (core.Project, error)

Rename changes a project's title (and its document's).

func (*Library) SaveDoc

func (l *Library) SaveDoc(ctx context.Context, p core.Project, doc LongformDoc) (core.Project, error)

SaveDoc saves a Stories or Audiobook project: p's ID "" makes a new one (Save as). The body is doc; the summary and the segments (a story's lines, an audiobook's voices) follow, so the library and "where this voice has been used" see them.

func (*Library) SaveDocIf

func (l *Library) SaveDocIf(ctx context.Context, p core.Project, doc LongformDoc, unchanged func(cur core.Project, curDoc LongformDoc) bool) (core.Project, error)

SaveDocIf is SaveDoc refusing with ErrChanged when unchanged, given the project as stored now and its document, says it is not what the caller read (a body compare: BodyIs). nil, or a new project (p.ID ""), saves without asking.

func (*Library) Search

Search lists the library (projects, finished renders, voices, takes, exports), newest first.

func (*Library) UpdateDoc

func (l *Library) UpdateDoc(ctx context.Context, id string, fn func(p *core.Project, d *LongformDoc) error) (core.Project, LongformDoc, error)

UpdateDoc changes a Stories or Audiobook project's document in place: fn gets it as stored now, and no other save comes between the read and the write. fn's error aborts.

type LinePlace

type LinePlace struct {
	ID    string      `json:"id,omitempty"`
	Start float64     `json:"start"`
	End   float64     `json:"end"`
	Spans []SpanPlace `json:"spans"`
}

LinePlace is where a line landed in its chapter (seconds).

type LineSpec

type LineSpec struct {
	ID         string     `json:"id,omitempty"`
	Character  string     `json:"character,omitempty"` // for stems; "" = the narrator
	Spans      []SpanSpec `json:"spans"`
	Speed      float64    `json:"speed,omitempty"` // 0 or 1 = normal
	PauseAfter int        `json:"pauseAfter,omitempty"`
	Paragraph  bool       `json:"paragraph,omitempty"` // the paragraph gap before it
	// Repeat counts the earlier lines with the same text and voice (for
	// VaryRepeats).
	Repeat int `json:"repeat,omitempty"`
	// The line's direction and its intensity, and its character's persona
	// (stories): the instruction of models that take one.
	Direction string `json:"direction,omitempty"`
	Intensity int    `json:"intensity,omitempty"`
	Persona   string `json:"persona,omitempty"`
	// Block is the dialogue block of a manuscript the line is in
	// (book_dialogue.go), from 1 in its chapter; 0: none.
	Block int `json:"block,omitempty"`
	// Emotion (story_emotion.go): the line's feeling, a steady line's
	// being its character's baseline; with it, the instruction is made
	// from Emotion and Intensity (0–3), Direction being the user's own
	// words. Turn: a turn of the scene.
	Emotion string `json:"emotion,omitempty"`
	Turn    bool   `json:"turn,omitempty"`
	// Baseline is the character's baseline emotion (tracks are said in it).
	Baseline string `json:"baseline,omitempty"`
}

LineSpec is one line (a story line, a paragraph of a manuscript).

type Longform

type Longform struct {
	// contains filtered or unexported fields
}

Longform runs and keeps longform renders.

func (*Longform) Active

func (s *Longform) Active() (core.Render, bool)

Active is the full render running now, if any (published body).

func (*Longform) AssembleExecutor

func (s *Longform) AssembleExecutor() jobs.Executor

func (*Longform) ChapterExecutor

func (s *Longform) ChapterExecutor() jobs.Executor

ChapterExecutor and AssembleExecutor are the executors New registers, for tests that run them.

func (*Longform) ChunkDir

func (s *Longform) ChunkDir() string

ChunkDir is the longform chunk cache's folder (Settings → Storage).

func (*Longform) ClearChunks

func (s *Longform) ClearChunks(ctx context.Context) (int64, error)

ClearChunks empties the longform chunk cache and returns the bytes it freed; it refuses (core.ErrBusy) while a render runs: its chapters read and write chunks.

func (*Longform) Close

func (s *Longform) Close()

Close stops following jobs and waits for the updates being applied.

func (*Longform) Delete

func (s *Longform) Delete(ctx context.Context, id string) error

Delete removes a render's record and files; a running render is refused.

func (*Longform) DropProject

func (s *Longform) DropProject(ctx context.Context, project string) (int, error)

DropProject deletes project id's unfinished renders (its finished books stay, as the delete confirmation says) and returns how many went; a running one is left (the app refuses to delete the project first). The chunk cache is trimmed to its limits unless another render runs: its plan may count on chunks not read yet (code review 1103 L-6).

func (*Longform) EncodeSupported

func (s *Longform) EncodeSupported() bool

EncodeSupported reports whether books can be encoded as M4B (the engine has media.encode).

func (*Longform) Get

func (s *Longform) Get(ctx context.Context, id string) (core.Render, RenderBody, error)

Get returns a render with its whole body (manifest included).

func (*Longform) ImportRender

func (s *Longform) ImportRender(ctx context.Context, spec LongformSpec, chapters []ImportedAudio) (core.Render, error)

ImportRender records audio as a finished render of spec (its project, kind, title and chapters; one audio per chapter, all at one rate and channel count) and publishes it.

func (*Longform) List

func (s *Longform) List(ctx context.Context, q store.RenderQuery) ([]core.Render, error)

List lists renders (their bodies as stored).

func (*Longform) Reconcile

func (s *Longform) Reconcile(ctx context.Context) error

Reconcile settles renders recorded as running whose jobs are all gone or finished (the app stopped between two of their updates): they become failed, for Resume. Call it once the scheduler has started.

func (*Longform) Resume

func (s *Longform) Resume(ctx context.Context, id string) (core.Render, error)

Resume renders again what a stopped or failed render lacks: its chapters made from the same program are kept, the rest (failed or not yet made) are rendered, then the book is assembled.

func (*Longform) Start

func (s *Longform) Start(ctx context.Context, spec LongformSpec) (core.Render, error)

Start begins a render of spec. A full render is refused with core.ErrBusy while another runs.

func (*Longform) Stop

func (s *Longform) Stop(ctx context.Context, id string) error

Stop cancels a render's jobs; the chapters made are kept, and Resume goes on from them.

func (*Longform) Sweep

func (s *Longform) Sweep(ctx context.Context) (int, error)

Sweep removes what renders left behind: folders in renders/ no record names (older than strayDirAge), unfinished renders whose project was deleted older than orphanRenderAge (not a draft's: orphanOf), and chunks beyond the cache's limits. It returns how many renders and folders went. Call it once the renders are reconciled (after Reconcile), at startup and daily.

type LongformDoc

type LongformDoc struct {
	Version  int              `json:"version"`
	Kind     core.ProjectKind `json:"kind"` // ProjectStory or ProjectAudiobook
	Title    string           `json:"title"`
	Model    string           `json:"model"`
	Voice    string           `json:"voice,omitempty"`    // the default (narrator) voice: a VoiceRef
	Language string           `json:"language,omitempty"` // BCP-47; "" = auto
	Speed    float64          `json:"speed,omitempty"`    // 0.5–2; 0 = 1
	Format   string           `json:"format,omitempty"`   // FormatWAV ("" too) or FormatM4B
	// Seed is the project's own seed: chapters are rendered with it unless
	// Production.Seed pins another, so a render can be made again and its
	// chunks come from the cache.
	Seed int64 `json:"seed,omitempty"`

	// Stories.
	// Scene is where and how the story's dialogue happens ("evening, the
	// living room; the child wants a kitten, the mother hesitates"): a
	// summary models that take an instruction hear with every line.
	// Never spoken.
	Scene      string       `json:"scene,omitempty"`
	Lines      []StoryLine  `json:"lines,omitempty"`
	Cast       []CastMember `json:"cast,omitempty"`
	ImportText string       `json:"importText,omitempty"` // the review buffer
	SplitBy    string       `json:"splitBy,omitempty"`    // "sentences", "paragraphs" (default), "chapters"
	MaxChars   int          `json:"maxChars,omitempty"`   // per line when splitting by sentences; 0 = 500

	// Audiobook.
	Script    string            `json:"script,omitempty"`
	VoiceCast map[string]string `json:"voiceCast,omitempty"` // [voice:NAME] → VoiceRef

	Lexicon    []LexiconEntry `json:"lexicon,omitempty"` // the book's pronunciations, over the dictionary
	Production Production     `json:"production"`
	Book       BookInfo       `json:"book"`
	Stems      bool           `json:"stems,omitempty"` // write a stem per character
	// Render is the id of the last full render.
	Render string `json:"render,omitempty"`
}

LongformDoc is a Stories or Audiobook project (core.Project.Body) and the page's draft.

func NewLongformDoc

func NewLongformDoc(kind core.ProjectKind, model string) LongformDoc

NewLongformDoc is a new, empty project of kind for model.

type LongformSpec

type LongformSpec struct {
	Project string           `json:"project,omitempty"` // "" for a draft
	Kind    core.ProjectKind `json:"kind"`
	Title   string           `json:"title"`
	Model   string           `json:"model"`
	Lang    string           `json:"lang,omitempty"` // BCP-47, for normalisation and the dictionary
	Seed    int64            `json:"seed,omitempty"`
	// Voices are the voice fields of the recipes by key (SpanSpec.Voice).
	Voices     map[string]core.Take `json:"voices"`
	Chapters   []ChapterSpec        `json:"chapters"`
	Production Production           `json:"production"`
	Book       BookInfo             `json:"book"`
	Format     string               `json:"format,omitempty"`
	Stems      bool                 `json:"stems,omitempty"`
	Lexicon    []LexiconEntry       `json:"lexicon,omitempty"`
	// Scene is the story's scene (LongformDoc.Scene), for instructions.
	Scene string `json:"scene,omitempty"`
	// Audition renders the chapters for listening only: no book, no
	// stems, no loudness target (a chapter or a line preview).
	Audition bool `json:"audition,omitempty"`
}

LongformSpec is what a longform render renders: the voices resolved for the model, and the chapters as lines of voiced spans.

func (*LongformSpec) FirstWords

func (s *LongformSpec) FirstWords(n int) string

FirstWords is the start of the spec's script — its lines' words, tags dropped ("[[word|say]]" keeps the word) — on one line, at most n runes, cut with "…"; the first chapter title when no line says anything; "" when the spec has neither.

type LoudnessReport

type LoudnessReport struct {
	Target     string           `json:"target,omitempty"` // "acx", "podcast"; "" = measured only
	Integrated float64          `json:"integrated"`       // LUFS
	TruePeak   float64          `json:"truePeak"`         // dBTP
	Range      float64          `json:"range"`            // LRA, LU
	RMS        float64          `json:"rms"`              // dBFS
	NoiseFloor float64          `json:"noiseFloor"`       // dBFS RMS of the quietest 0.5 s
	GainDB     float64          `json:"gainDb,omitempty"` // gain applied to reach the target
	LimitDB    float64          `json:"limitDb,omitempty"`
	Seconds    float64          `json:"seconds"`
	Checks     []loudness.Check `json:"checks,omitempty"`
	Compliant  bool             `json:"compliant,omitempty"`
}

LoudnessReport is a chapter's or a book's loudness, measured on the file written, and how it fares against the book's target (the checks of loudness.Verify, measured while streaming so a book of any length needs no more memory than a block).

type ModelInfo

type ModelInfo struct {
	Traits
	// Label is the model's name in the UI (the catalogue's label).
	Label    string
	Revision string
	// Languages maps the values the language parameter takes to BCP-47
	// tags ("Chinese" → "zh"); VoiceLanguages built-in voices to theirs.
	Languages      map[string]string
	VoiceLanguages map[string]string
	// Defaults are the model's recommended parameters (the catalogue's
	// presets, thread #41) by workflow; "" holds the general ones. A
	// recipe that sets none of them gets these (FillDefaults).
	Defaults map[string]ParamDefaults
}

ModelInfo is what the services need to know of a model (from the catalogue, which they do not import).

func (ModelInfo) FillDefaults

func (m ModelInfo) FillDefaults(t *core.Take, workflow string)

FillDefaults gives recipe t the model's recommended parameters for workflow where t sets none (0): the Studio, a story or an API request that leaves the temperature unset gets the tuned one, not the model's built-in default.

func (ModelInfo) Lang

func (m ModelInfo) Lang(language, voice string) string

Lang is the BCP-47 tag of a recipe's language for the text pipeline: its language parameter, else its voice's language, else "" (guess).

type ParamDefaults

type ParamDefaults struct {
	Temperature, TopP, Guidance float64
	Steps                       int
}

ParamDefaults are recommended generation parameters; 0 = none (the model's own).

type Problem

type Problem struct {
	Code     string            `json:"code"`
	Blocking bool              `json:"blocking,omitempty"`
	Chapter  int               `json:"chapter"`       // 0-based; -1 = none
	Line     int               `json:"line"`          // the story line's index, -1 = none
	Span     text.Span         `json:"span,omitzero"` // in the manuscript (Audiobook)
	Params   map[string]string `json:"params,omitzero"`
}

Problem is something the compiler found: Blocking ones stop a render. The UI translates Code with Params.

type Production

type Production struct {
	Steps    int     `json:"steps,omitempty"`    // diffusion steps; 0 = the model's
	Guidance float64 `json:"guidance,omitempty"` // CFG; 0 = the model's
	Seed     int64   `json:"seed,omitempty"`     // 0 = the project's seed
	// VaryRepeats gives identical lines takes of their own instead of
	// reusing one recording.
	VaryRepeats    bool `json:"varyRepeats,omitempty"`
	LineGapMs      int  `json:"lineGapMs"`      // silence between lines (0–2000)
	ParagraphGapMs int  `json:"paragraphGapMs"` // between paragraphs (0–3000)
	// KeepEdges keeps the silence engines pad onto each chunk; the default
	// trims it before joining.
	KeepEdges bool `json:"keepEdges,omitempty"`
	// Pacing picks turn-aware gaps between a story's lines (PacingDialogue,
	// PacingReading, PacingRelaxed: story_pacing.go) in place of LineGapMs,
	// and lets consecutive lines of one character be synthesized as one;
	// "" (PacingFixed) keeps one gap for every line, as stories made
	// before it was added do.
	Pacing string `json:"pacing,omitempty"`
	// NoMerge keeps every line its own synthesis under a pacing preset;
	// NoLevel keeps each line's loudness as the model made it (a pacing
	// preset otherwise brings a character's lines toward one level).
	NoMerge bool `json:"noMerge,omitempty"`
	NoLevel bool `json:"noLevel,omitempty"`
	// NoEmotionGaps keeps the pacing's gaps for lines with an emotion,
	// which otherwise follow it (story_emotion.go).
	NoEmotionGaps bool `json:"noEmotionGaps,omitempty"`
	// NoTracks makes a directed story line by line: by default, within a
	// chapter, the lines of a character that have emotions are said in
	// one synthesis per stretch of one feeling, cut apart with the forced
	// aligner and put back in the dialogue (story_track.go).
	NoTracks bool `json:"noTracks,omitempty"`
	// Dialogue speaks a story's character lines with DialogueModel (a
	// repo of catalogue capability "dialogue"), a scene at a time, each
	// line hearing the lines before it (story_dialogue.go); narration
	// stays on the story's model. DialogueTags puts a line's emotion into
	// the dialogue model's text as a non-verbal tag (an experiment, off).
	Dialogue      bool   `json:"dialogue,omitempty"`
	DialogueModel string `json:"dialogueModel,omitempty"`
	DialogueTags  bool   `json:"dialogueTags,omitempty"`
}

Production are a render's synthesis and joining settings.

func DefaultProduction

func DefaultProduction() Production

DefaultProduction are the production settings of a new project.

func DefaultStoryProduction

func DefaultStoryProduction() Production

DefaultStoryProduction are the production settings of a new story: the dialogue pacing.

type ProjectSummary

type ProjectSummary struct {
	Model    string  `json:"model,omitempty"`
	Chapters int     `json:"chapters,omitempty"`
	Lines    int     `json:"lines,omitempty"`
	Words    int     `json:"words,omitempty"`
	Chars    int     `json:"chars,omitempty"`
	Seconds  float64 `json:"seconds,omitempty"` // estimated runtime
	Cast     int     `json:"cast,omitempty"`
	Render   string  `json:"render,omitempty"` // the last render
}

ProjectSummary is what the library shows of a project without reading its body (store.Projects.PutSummary).

func SummaryOf

func SummaryOf(detail string) ProjectSummary

SummaryOf decodes a library item's summary (store.LibraryItem.Detail of a project).

type Projects

type Projects struct {
	// contains filtered or unexported fields
}

Projects implements core.ProjectService: CRUD over the store.

func (*Projects) Delete

func (s *Projects) Delete(ctx context.Context, id string) error

func (*Projects) Get

func (s *Projects) Get(ctx context.Context, id string) (core.Project, error)

func (*Projects) List

func (s *Projects) List(ctx context.Context, kind core.ProjectKind, search string) ([]core.Project, error)

func (*Projects) Save

func (s *Projects) Save(ctx context.Context, p core.Project) (core.Project, error)

Save creates (empty ID) or updates a project, keeping its creation time.

type Pronunciation

type Pronunciation struct {
	// contains filtered or unexported fields
}

Pronunciation is the pronunciation dictionary (Settings → Pronunciation): entries kept as one JSON document in the store (lexicon.File), cached in memory after the first read. Goroutine-safe.

func (*Pronunciation) Dictionary

func (p *Pronunciation) Dictionary(ctx context.Context, lang string) (*lexicon.Dictionary, error)

Dictionary compiles the entries that apply to language lang.

func (*Pronunciation) Entries

func (p *Pronunciation) Entries(ctx context.Context) ([]lexicon.Entry, error)

Entries returns the dictionary, in its order.

func (*Pronunciation) Export

func (p *Pronunciation) Export(ctx context.Context) ([]byte, error)

Export encodes the dictionary as a JSON file.

func (*Pronunciation) Import

func (p *Pronunciation) Import(ctx context.Context, data []byte, mode lexicon.Mode) (lexicon.ImportReport, error)

Import reads a dictionary file (lexicon.Import's shapes) and merges it into the dictionary or replaces it, then saves.

func (*Pronunciation) Save

func (p *Pronunciation) Save(ctx context.Context, entries []lexicon.Entry) error

Save replaces the dictionary and publishes PronunciationChanged. Entries are stored as given, problems included (lexicon.Validate lists them; disabled or broken entries do not apply).

type PronunciationChanged

type PronunciationChanged struct{ Entries []lexicon.Entry }

PronunciationChanged is published after the dictionary was saved. Topic "pronunciation.changed".

func (PronunciationChanged) Topic

func (PronunciationChanged) Topic() string

type RenderBody

type RenderBody struct {
	// Spec is the manifest. Bodies published with RenderChanged carry its
	// summary only (Summary), not its chapters and voices.
	Spec     LongformSpec    `json:"spec"`
	Summary  RenderSummary   `json:"summary"`
	Dir      string          `json:"dir"` // the render's files
	Chapters []RenderChapter `json:"chapters"`
	// The assembly: its job, whether it runs and how far.
	AssembleJob string          `json:"assembleJob,omitempty"`
	Assembling  bool            `json:"assembling,omitempty"`
	Assembled   float64         `json:"assembled,omitempty"`
	Output      *AssembleResult `json:"output,omitempty"`
	Error       *jobs.Error     `json:"error,omitempty"`
	Stopping    bool            `json:"stopping,omitempty"`
	Runs        int             `json:"runs"` // 1 + how often it was resumed
	Started     time.Time       `json:"started"`
	Finished    time.Time       `json:"finished,omitzero"`
}

RenderBody is a render's JSON (core.Render.Body).

func DecodeRender

func DecodeRender(r core.Render) (RenderBody, error)

DecodeRender reads a render's body.

func (*RenderBody) Done

func (b *RenderBody) Done() int

Done reports whether every chapter is made.

func (*RenderBody) Failed

func (b *RenderBody) Failed() int

Failed counts the failed chapters.

type RenderChapter

type RenderChapter struct {
	Title        string      `json:"title,omitempty"`
	Chars        int         `json:"chars"` // runes to say, for the ETA
	Lines        int         `json:"lines"`
	Job          string      `json:"job,omitempty"`
	State        string      `json:"state"`
	Fraction     float64     `json:"fraction,omitempty"`
	Error        *jobs.Error `json:"error,omitempty"`
	File         string      `json:"file,omitempty"`
	AudioSeconds float64     `json:"audioSeconds,omitempty"`
	Seconds      float64     `json:"seconds,omitempty"` // wall time
	Chunks       int         `json:"chunks,omitempty"`
	Cached       int         `json:"cached,omitempty"` // chunks from the cache
	Started      time.Time   `json:"started,omitzero"`
	Finished     time.Time   `json:"finished,omitzero"`
}

RenderChapter is a chapter of a render.

type RenderParams

type RenderParams struct {
	// Take is the recipe: its ID and File are set; Render holds the
	// output options.
	Take core.Take `json:"take"`
	// Lang is the script's language for normalisation and the
	// dictionary (BCP-47); "" guesses it from the text.
	Lang string `json:"lang,omitempty"`
	// Output is the absolute path of the WAV to write.
	Output string `json:"output"`
	// Stream sends the audio joined so far as the job's chunks
	// (proto.ChunkParams, pcm16le) for the streaming preview.
	Stream bool `json:"stream,omitempty"`
	// NoWatermark leaves the file unmarked: an intermediate render that
	// is watermarked later as part of something else (a dub's track).
	NoWatermark bool `json:"noWatermark,omitempty"`
	// Workflow picks the model's recommended parameters
	// (ModelInfo.Defaults): "" (the Studio, the API), "story",
	// "audiobook", "dub".
	Workflow string `json:"workflow,omitempty"`
}

RenderParams are a take.render job's params.

type RenderProgress

type RenderProgress struct {
	Job    string // the render job
	Owner  string // its owner ("take:<id>")
	Chunk  int    // 1-based chunk starting; 0 when finishing (mastering, writing)
	Chunks int
	Cached int // chunks taken from the cache so far
}

RenderProgress is published when a render starts a chunk, so the UI can say which ("chunk 3 of 12"). Topic "render.progress".

func (RenderProgress) Topic

func (RenderProgress) Topic() string

type RenderResult

type RenderResult struct {
	Output       string          `json:"output"`
	SampleRate   int             `json:"sampleRate"`
	Channels     int             `json:"channels"`
	Frames       int64           `json:"frames"`
	AudioSeconds float64         `json:"audioSeconds"`
	Seconds      float64         `json:"seconds"` // the render's wall time
	Seed         int64           `json:"seed,omitempty"`
	Render       core.TakeRender `json:"render"`
	// Credit is the attribution the audio must carry (Config.Credit).
	Credit string `json:"credit,omitempty"`
}

RenderResult is a take.render job's result.

type RenderSummary

type RenderSummary struct {
	Model    string     `json:"model"`
	Lang     string     `json:"lang,omitempty"`
	Format   string     `json:"format,omitempty"`
	Loudness string     `json:"loudness,omitempty"`
	Voices   []string   `json:"voices,omitempty"`   // VoiceIDs, or speakers ("speaker:<id>")
	MinSpeed float64    `json:"minSpeed,omitempty"` // of the lines
	MaxSpeed float64    `json:"maxSpeed,omitempty"`
	Chapters int        `json:"chapters"`
	Lines    int        `json:"lines"`
	Words    int        `json:"words"`
	Chars    int        `json:"chars"` // unspaced-script characters
	Prod     Production `json:"production"`
	Stems    bool       `json:"stems,omitempty"`
	// Credits are the attributions the audio must carry when published
	// (its VOICEVOX characters', thread #171), also in the render's
	// folder as credits.txt.
	Credits []string `json:"credits,omitempty"`
}

RenderSummary is how a render was made, for the library's details.

type RunOptions

type RunOptions struct {
	// Again makes every result anew (Start a new run), not only the ones
	// whose recipe changed.
	Again    bool
	Priority jobs.Priority
	// Inputs, when set, are one-off inputs of this run in place of the
	// input step's (an agent's run, thread #35): the saved workflow is not
	// changed, and the results of its own inputs are kept.
	Inputs *WorkflowInputs
}

RunOptions tune a run.

type RunRequest

type RunRequest struct {
	// Through is the last stage: dub.StageIngest (the decoded audio
	// alone: Rebuild), dub.StageReferences (the transcript),
	// StageTranslate, StageMix (the dub) or StageQC (Verify).
	Through dub.Stage
	// Langs are the languages (nil = every language the project speaks).
	Langs []string
	// Force runs these stages again although they are done (a new
	// transcript, every line translated again).
	Force []dub.Stage
	// Only re-renders these segments ("Regen"): nil = the stale ones.
	Only     []string
	Priority jobs.Priority
	// Batch: the batch queue's run (background priority, no review).
	Batch bool
}

RunRequest asks for the pipeline up to a stage.

type ScriptStats

type ScriptStats struct {
	Chapters int
	Words    int
	Chars    int
	Seconds  float64
}

ScriptStats are the stats line of a script: chapters, words (and unspaced characters) and the estimated runtime at speed.

func StatsOf

func StatsOf(script string, speed float64) ScriptStats

StatsOf counts a manuscript ("# " chapters) or a story's lines.

type Services

type Services struct {
	core.Services
	// Pronunciation is the pronunciation dictionary.
	Pronunciation *Pronunciation
	// Render is the take service's render pipeline and history tools
	// beyond core.TakeService (previews, Check audio, pruning).
	Render *Takes
	// Longform renders Stories and Audiobook projects; Library saves them
	// and searches everything the Projects page lists (M3).
	Longform *Longform
	Library  *Library
	// contains filtered or unexported fields
}

Services is the set of services over one store, as core.Services for the UI and the Local API.

func New

func New(cfg Config) *Services

New builds the services. Close releases them.

func (*Services) Close

func (s *Services) Close(ctx context.Context) error

Close writes pending drafts, stops listening to the bus and waits for takes being saved. The store stays open: its owner closes it after.

Drafts go first: they are the user's edits. The waits for renders and takes in progress end with ctx (#101 L6); what still runs then is left.

type SpanPlace

type SpanPlace struct {
	Character string  `json:"character,omitempty"`
	Text      string  `json:"text"`
	Start     float64 `json:"start"`
	End       float64 `json:"end"`
}

SpanPlace is where a span landed, with what it says (markup) and who.

type SpanSpec

type SpanSpec struct {
	Voice     string `json:"voice"` // a key of LongformSpec.Voices
	Character string `json:"character,omitempty"`
	Text      string `json:"text"` // script markup without [voice:] tags
}

SpanSpec is a part of a line in one voice.

type StageParams

type StageParams struct {
	Dub   string   `json:"dub"`
	Lang  string   `json:"lang,omitempty"`
	Force bool     `json:"force,omitempty"`
	Only  []string `json:"only,omitempty"`
}

StageParams are a stage job's params.

type Stem

type Stem struct {
	Character string `json:"character"` // "" = the narrator
	File      string `json:"file"`
}

Stem is one character's stem.

type StoryLine

type StoryLine struct {
	ID        string  `json:"id"`
	Text      string  `json:"text"`                // script markup; a chapter line's title
	Character string  `json:"character,omitempty"` // a CastMember's ID; "" = the default voice
	Voice     string  `json:"voice,omitempty"`     // a VoiceRef that overrides the character's
	Speed     float64 `json:"speed,omitempty"`     // 0 = the story's
	// PauseAfter is milliseconds of silence after the line, in place of the
	// gap between lines; 0 = the gap.
	PauseAfter int  `json:"pauseAfter,omitempty"`
	Chapter    bool `json:"chapter,omitempty"` // a chapter heading: Text is its title
	// Direction is how the line is delivered ("pleading", "softly",
	// "无奈地笑"): an instruction for models that take one. Never spoken.
	Direction string `json:"direction,omitempty"`
	// Intensity of the direction: 0 = unset, IntensityLight, Medium or
	// Strong. With an Emotion, 0–3 (0: barely).
	Intensity int `json:"intensity,omitempty"`
	// Emotion is the line's feeling from the vocabulary (Emotions,
	// story_emotion.go), as the second AI director writes it: the line's
	// instruction is made from it and Intensity (Direction, when set, is
	// the user's own wording of it). "" = directed as before (Direction).
	Emotion string `json:"emotion,omitempty"`
	// Turn marks a turn of the scene (转折): the feeling may change at
	// once here; elsewhere it moves a step at a time.
	Turn bool `json:"turn,omitempty"`
	// Note is the director's continuity note ("接着上一句的委屈"): shown,
	// never sent.
	Note string `json:"note,omitempty"`
	// EmotionByUser: the user set the emotion, intensity, turn or
	// direction; the director keeps them when it directs again.
	EmotionByUser bool `json:"emotionByUser,omitempty"`
}

StoryLine is one line of a story.

type Takes

type Takes struct {
	// contains filtered or unexported fields
}

Takes implements core.TakeService.

Generate submits a "take.render" job (render.go) owned by "take:<id>" and keeps the take's recipe until the job ends. It listens to jobs.Updated: when the job succeeds, the take is filled from the result, saved and announced with TakeCreated (on a goroutine, as bus handlers must not block), and the history is pruned to its cap. A job that finishes after a restart (re-queued because it is idempotent) has no recipe in memory: the take is then rebuilt from the job's params. Jobs of the M0 kind, a single "tts.synthesize" owned by a take, are still completed the same way.

func (*Takes) Add

func (s *Takes) Add(ctx context.Context, t core.Take) (core.Take, error)

func (*Takes) AudioDir

func (s *Takes) AudioDir() string

func (*Takes) AudioPath

func (s *Takes) AudioPath(t core.Take) string

func (*Takes) Check

func (s *Takes) Check(ctx context.Context, id string) (core.Take, error)

Check runs Check audio over a take's file, keeps the findings with the take and publishes TakeUpdated.

func (*Takes) Close

func (s *Takes) Close() error

Close stops listening for jobs and waits for takes being saved.

func (*Takes) Delete

func (s *Takes) Delete(ctx context.Context, id string) error

func (*Takes) Executor

func (s *Takes) Executor() jobs.Executor

Executor is the render executor (registered on the scheduler by New), for tests that run renders themselves.

func (*Takes) Export

func (s *Takes) Export(ctx context.Context, id, dst string) error

Export streams the take's audio into dst through a temporary file beside it, renamed into place when complete.

func (*Takes) ExportAs

func (s *Takes) ExportAs(ctx context.Context, id, dst string, bits int) error

ExportAs writes a take's audio to dst as a WAV of bits (16, 24 or 32 float; 0 copies the file as it is). 16 bits get TPDF dither.

func (*Takes) Generate

func (s *Takes) Generate(ctx context.Context, req core.TakeRequest) (string, error)

func (*Takes) Get

func (s *Takes) Get(ctx context.Context, id string) (core.Take, error)

func (*Takes) List

func (s *Takes) List(ctx context.Context, q core.TakeQuery) ([]core.Take, error)

func (*Takes) Preview

func (s *Takes) Preview(ctx context.Context, recipe core.Take) (jobID, output string, err error)

Preview renders a recipe without making a take (the pronunciation dictionary's "Test a sentence"): a take.render job owned by "preview:<id>" writing a WAV in the cache. It returns the job's id and the file it writes; the job's chunks stream the audio.

func (*Takes) Prune

func (s *Takes) Prune(ctx context.Context) (int, error)

Prune deletes the oldest takes beyond the history's cap (KeepTakes), sparing starred takes and takes of projects, and returns how many it deleted.

func (*Takes) Saved

func (s *Takes) Saved(ctx context.Context, id string) error

Saved waits until the take id that Generate queued is saved, or its job ended without a take; at once for takes not being made. Its job ends before the take is saved (onJob saves it on a goroutine): a caller that reads the history right after the job (the Local API's generate_speech, then list_takes or list_assets) waits here first.

func (*Takes) SetStarred

func (s *Takes) SetStarred(ctx context.Context, id string, starred bool) error

type Traits

type Traits struct {
	Family string `json:"family"`
	// NonVerbal: renders non-verbal tags ([laughter]…) and bracketed
	// phonemes itself (OmniVoice).
	NonVerbal bool `json:"nonVerbal,omitempty"`
	// Speed: takes a speed factor ("speed" capability).
	Speed bool `json:"speed,omitempty"`
	// Steps: takes a number of diffusion steps ("Voice refinement",
	// performance tiers).
	Steps bool `json:"steps,omitempty"`
	// Duration: can target a duration ("duration" capability).
	Duration bool `json:"duration,omitempty"`
	// Deterministic models say the same text the same way whatever the
	// seed, so the seed is not part of their chunk keys (Kokoro).
	Deterministic bool `json:"deterministic,omitempty"`
	// MaxChars caps the runes of one engine call for spaced scripts,
	// MaxCharsCJK for scripts mostly in Han, kana or Hangul.
	MaxChars    int `json:"maxChars"`
	MaxCharsCJK int `json:"maxCharsCJK"`
	// NeedsReference: the model only clones (catalog
	// Entry.NeedsReference): a recipe without a reference clip or a voice
	// prompt is refused before it reaches the engine.
	NeedsReference bool `json:"needsReference,omitempty"`
	// NonVerbalTags are the tags the model renders ("laughter"…, without
	// brackets); nil with NonVerbal = every tag markup knows.
	NonVerbalTags []string `json:"nonVerbalTags,omitempty"`
	// Instruct: takes a delivery instruction in its voice field
	// (TakesInstruct): stories send their scene, personas and directions.
	Instruct bool `json:"instruct,omitempty"`
	// CloneInstruct: its clones take the instruction too (VoxCPM2,
	// thread #165: capabilities instruct and clone); other models' clones
	// follow the reference alone.
	CloneInstruct bool `json:"cloneInstruct,omitempty"`
	// Exaggeration: takes an emotion exaggeration (Chatterbox, capability
	// "exaggeration"): stories send their lines' emotion intensities.
	Exaggeration bool `json:"exaggeration,omitempty"`
	// External models run in an engine the user installed (VOICEVOX,
	// AivisSpeech; thread #171), which reads numbers and dates itself:
	// the script is not normalised for them.
	External bool `json:"external,omitempty"`
}

Traits are what the render pipeline needs to know about a model beyond its catalogue capabilities: how much text one engine call takes, and how its markup is lowered. They are keyed by the model's family (catalog.Entry.Family), with the catalogue's capability names.

The catalogue does not carry these yet (see the M1-G handoff: chunk limits, non-verbal tags, steps and determinism belong in catalog.json); until it does, this table is their home.

func TraitsFor

func TraitsFor(family string, caps []string) Traits

TraitsFor returns the traits of a model of family with capabilities caps.

func (Traits) WithCatalog

func (t Traits) WithCatalog(maxChars int, nonVerbal []string) Traits

WithCatalog applies what the catalogue knows of the model (v3): its chunk limit (catalog.TextLength units: CJK characters count three) and the non-verbal tags it renders. Data the catalogue lacks keeps the family's defaults.

type TranscribeRequest

type TranscribeRequest struct {
	// ID of the transcript to make; "" chooses one.
	ID     string                `json:"id"`
	Input  string                `json:"input"` // absolute path: any audio or video
	Source core.TranscriptSource `json:"source"`
	Title  string                `json:"title,omitempty"`
	// RemoveInput deletes Input once its audio is kept (a recording the
	// app made for this transcript).
	RemoveInput bool   `json:"removeInput,omitempty"`
	Mode        string `json:"mode"`              // "fast" | "accurate", recorded with the transcript
	Model       string `json:"model"`             // speech-to-text repo
	Aligner     string `json:"aligner,omitempty"` // forced-aligner repo: time the words; "" = don't
	// Words asks the model for word timings (models with them).
	Words    bool   `json:"words,omitempty"`
	Language string `json:"language,omitempty"` // BCP-47; "" detects it
	Prompt   string `json:"prompt,omitempty"`   // vocabulary hint
	App      string `json:"app,omitempty"`      // dictation: the app it was for
	// Role is the engine worker that transcribes: "" the gpu worker, or
	// proto.RoleListen for dictation, which then runs on jobs.LaneListen
	// and the listen worker's own model, not behind renders.
	Role proto.Role `json:"role,omitempty"`
}

TranscribeRequest asks for a transcript of a file. It is the job's params.

type TranscribeResult

type TranscribeResult struct {
	Transcript core.Transcript `json:"transcript"`
	Warnings   []string        `json:"warnings,omitempty"`
	// AlignError says why word timings are missing (with WarnNoWordTimes).
	AlignError *jobs.Error `json:"alignError,omitempty"`
}

TranscribeResult is a transcription job's result.

type Transcripts

type Transcripts struct {
	// contains filtered or unexported fields
}

Transcripts is the transcript library and its transcription jobs. Goroutine-safe.

func NewTranscripts

func NewTranscripts(cfg TranscriptsConfig) *Transcripts

NewTranscripts builds the service and registers its executor.

func (*Transcripts) AudioPath

func (s *Transcripts) AudioPath(t core.Transcript) string

AudioPath is the file of a transcript's audio ("" when none is kept).

func (*Transcripts) Delete

func (s *Transcripts) Delete(ctx context.Context, id string) error

Delete removes a transcript and its audio.

func (*Transcripts) Executor

func (s *Transcripts) Executor() jobs.Executor

Executor runs transcription jobs (registered by NewTranscripts).

func (*Transcripts) Get

func (s *Transcripts) Get(ctx context.Context, id string) (core.Transcript, error)

func (*Transcripts) Import

func (s *Transcripts) Import(ctx context.Context, t core.Transcript, ext string, audio io.Reader) (core.Transcript, error)

Import saves a transcript made elsewhere (a bundled sample, 0.5 F6) as a new one: a new ID and times; audio (nil none) is kept as its audio, a file with ext (".m4a"). It publishes TranscriptChanged.

func (*Transcripts) List

func (*Transcripts) Ready

func (s *Transcripts) Ready(ctx context.Context, repo string) error

Ready reports whether a model can be used now (nil, or an error wrapping core.ErrNotDownloaded).

func (*Transcripts) Transcribe

Transcribe queues a transcription and returns its job id; the job is owned by TranscriptOwner+req.ID. It refuses models that are not downloaded (core.ErrNotDownloaded) or whose licence is not accepted (*core.LicenceRequiredError) before queueing.

func (*Transcripts) Update

func (s *Transcripts) Update(ctx context.Context, id string, fn func(*core.Transcript)) (core.Transcript, error)

Update applies fn to the saved transcript id (edits, clean-up, speaker names), stamps it and publishes TranscriptChanged.

type TranscriptsConfig

type TranscriptsConfig struct {
	Store     store.Transcripts
	Bus       *core.Bus
	Scheduler jobs.Scheduler // nil: Transcribe fails with core.ErrUnsupported
	// Engine returns the executor of one engine method (the supervisor's,
	// engine.Executor), asked as each job runs; nil, or a nil executor,
	// fails jobs with engine_unavailable (retryable).
	Engine func(method string) jobs.Executor
	// ModelPath is the local snapshot of a model, or an error wrapping
	// core.ErrNotDownloaded; Ready checks the same before queueing.
	ModelPath func(ctx context.Context, repo string) (string, error)
	Licences  core.LicenceService
	Now       func() time.Time
	Logf      func(format string, args ...any)
}

TranscriptsConfig wires the transcript service. Store and Bus are required.

type TurnGaps

type TurnGaps struct {
	Same      int // the same character goes on
	Question  int // a character answers a question
	Statement int // a character answers a statement
	Trailing  int // after a line left hanging (… —): an interruption
	Narration int // between narration and dialogue
	Paragraph int // a paragraph break
}

TurnGaps are the silences (ms) of a pacing preset, by turn.

func GapsOf

func GapsOf(pacing string) (TurnGaps, bool)

GapsOf are the turn gaps of a pacing preset; ok is false for PacingFixed (and unknown presets).

type VoiceResolver

type VoiceResolver func(ref string) (key string, voice core.Take, ok bool)

VoiceResolver says what a voice reference (or a name in a [voice:] tag) means for the document's model: a stable key for it and the voice fields of a recipe (Voice, RefAudio, RefText, VoicePrompt, Seed, Language, VoiceID…). ok is false for a reference it does not know.

type Voices

type Voices struct {
	// contains filtered or unexported fields
}

Voices implements core.VoiceService: profiles in the store, their files in VoiceDir/<id>/, voice packages (.asvoice, VoiceStudio .ovsvoice).

File names inside a voice's directory:

reference.<ext>  the clone reference (as given: wav, flac, mp3, m4a…)
original.<ext>   the reference before it was cleaned (Undo)
sample.<ext>     a rendered sample (designed voices, imports' preview)
locked.wav       the locked take's audio (Lock)
consent.<ext>    the consent recording
portrait.png     the portrait (portrait.<ext> for imports)
prompt-<h>.bin   cached voice prompts by model (tts.encodeVoice)

Files are written under a temporary name and renamed into place before the profile that names them is saved; replaced files are removed after.

func (*Voices) CleanReference

func (s *Voices) CleanReference(ctx context.Context, id, path string, seconds float64, q *core.RefQuality) (core.Voice, error)

CleanReference makes the cleaned clip at path the voice's reference; the current one becomes RefOriginal (its cached prompts go).

func (*Voices) Delete

func (s *Voices) Delete(ctx context.Context, id string) error

Delete deletes a voice for good, its files too. Takes made with it keep their audio.

func (*Voices) Export

func (s *Voices) Export(ctx context.Context, id, dst string, o core.VoiceExport) error

Export writes the voice as a .asvoice file at dst (atomically).

func (*Voices) FilePath

func (s *Voices) FilePath(v core.Voice, name string) string

FilePath is the absolute path of a voice's file.

func (*Voices) Get

func (s *Voices) Get(ctx context.Context, id string) (core.Voice, error)

func (*Voices) HasPreview

func (s *Voices) HasPreview(v core.Voice) bool

HasPreview reports whether Export finds a preview for v by itself: its sample or its reference is a WAV small enough (code review 1103 L3: the app asks before its save dialog). It reads at most a file header each.

func (*Voices) Import

func (s *Voices) Import(ctx context.Context, path string) (core.VoiceImport, error)

Import reads a .asvoice or .ovsvoice file into a new profile: the reference, preview (as the sample), portrait and consent recording are copied into its directory. A consent record in the file is the exporter's claim: the voice is ConsentIncluded until the user records the statement here.

func (*Voices) List

func (s *Voices) List(ctx context.Context, q core.VoiceQuery) ([]core.Voice, error)

func (*Voices) Lock

func (s *Voices) Lock(ctx context.Context, id, takeID string) (core.Voice, error)

Lock makes one of the voice's takes its identity: the take's audio is copied in as the voice's sample (so deleting the take keeps the lock) and its seed becomes the voice's.

func (*Voices) Purge

func (s *Voices) Purge(id string)

Purge removes a deleted voice's files for good: the undo is over.

func (*Voices) PurgeTrash

func (s *Voices) PurgeTrash(ctx context.Context)

PurgeTrash empties the trash at start: what an earlier run deleted is gone for good, and the files of a delete it did not finish (its voice is still in the library) go back in place.

func (*Voices) ReferenceTextChecked

func (s *Voices) ReferenceTextChecked(ctx context.Context, id string, was core.RefHeard, text string) (core.Voice, error)

ReferenceTextChecked records that the recognizer heard the voice's reference say text (thread #93): text becomes RefText (its cached prompts go when it changes, as they encode it) and RefCheck says the text is checked, without a mismatch. was is the reference as heard, its file and text: it fails with ErrInvalid when the reference changed meanwhile.

func (*Voices) Restore

func (s *Voices) Restore(ctx context.Context, id string) (core.Voice, error)

Restore undoes Delete while the voice is in the trash: its profile, its files and its links to takes and segments come back.

func (*Voices) RevertReference

func (s *Voices) RevertReference(ctx context.Context, id string) (core.Voice, error)

RevertReference undoes the automatic cleaning of a voice's reference: the original becomes the reference again (its cached prompts go).

func (*Voices) RevokeConsent

func (s *Voices) RevokeConsent(ctx context.Context, id string) (core.Voice, error)

func (*Voices) Save

func (s *Voices) Save(ctx context.Context, v core.Voice) (core.Voice, error)

Save creates a profile (empty ID) or updates one, keeping its creation time and its files; updating an unknown id fails with ErrNotFound.

func (*Voices) SaveFiles

func (s *Voices) SaveFiles(ctx context.Context, v core.Voice, f core.VoiceFiles) (core.Voice, error)

func (*Voices) SetConsent

func (s *Voices) SetConsent(ctx context.Context, id string, c core.ConsentRecording) (core.Voice, error)

func (*Voices) Trash

func (s *Voices) Trash(ctx context.Context, id string) error

Trash deletes a voice whose files wait in the trash until Purge, so that Restore can undo it (the window's Undo).

func (*Voices) Unlock

func (s *Voices) Unlock(ctx context.Context, id string) (core.Voice, error)

func (*Voices) Usage

func (s *Voices) Usage(ctx context.Context, id string) (core.VoiceUsage, error)

type WatchChanged

type WatchChanged struct{ State WatchState }

WatchChanged is published when the watch folder starts, stops, pauses, scans with a result or adds a video. Topic "dub.watch".

func (WatchChanged) Topic

func (WatchChanged) Topic() string

type WatchState

type WatchState struct {
	Dir    string       `json:"dir,omitempty"`
	Active bool         `json:"active"`
	Paused bool         `json:"paused,omitempty"`
	Added  int          `json:"added"`
	Last   time.Time    `json:"last,omitzero"` // the last scan
	Err    string       `json:"error,omitempty"`
	W      *dub.Watcher `json:"watcher,omitempty"`
}

WatchState is the watch folder, as persisted.

type WatermarkFunc

type WatermarkFunc func(ctx context.Context, path string, bits int) (bool, error)

WatermarkFunc marks the WAV at path (bits: its bit depth, 32 = float) in place. It reports false, without error, when the watermark is off or cannot run now (its model is not downloaded).

type WorkflowChanged

type WorkflowChanged struct {
	ID string
	// Record sums up the workflow (as List returns it).
	Record store.WorkflowRecord
	// Workflow is a copy of the document when it changed (nil when only
	// the run did); Run a copy of the run when it changed.
	Workflow *workflow.Workflow
	Run      *workflow.Run
	Deleted  bool
}

WorkflowChanged is published after a workflow, or its run, is saved or deleted. Topic "workflow.changed".

func (WorkflowChanged) Topic

func (WorkflowChanged) Topic() string

type WorkflowInputs

type WorkflowInputs struct {
	Scripts []workflow.Script
	Clips   []workflow.Clip
}

WorkflowInputs are a run's own inputs: scripts for a Start step, clips for a Source step.

type WorkflowInvalidError

type WorkflowInvalidError struct{ Report *workflow.Report }

WorkflowInvalidError is Run's refusal of a workflow with errors.

func (*WorkflowInvalidError) Error

func (e *WorkflowInvalidError) Error() string

func (*WorkflowInvalidError) Unwrap

func (e *WorkflowInvalidError) Unwrap() error

type WorkflowOutput

type WorkflowOutput struct {
	Item  string // the item's key
	Index int    // its place, 0-based
	Name  string // the item's name
	Node  string
	Value workflow.Value
}

WorkflowOutput is a result the Results list shows: an item's value at a step with nothing after it (an export, or the end of a branch).

func Outputs

func Outputs(w *workflow.Workflow, run *workflow.Run) []WorkflowOutput

Outputs are a run's final results, item by item, in the graph's order.

type WorkflowSTT

type WorkflowSTT struct {
	Model, Aligner string
	Words          bool // the model times words itself
	// Languages, Other and OtherWords: as DubModels' STTLanguages,
	// OtherSTT and OtherWordTimes.
	Languages  []string
	Other      string
	OtherWords bool
}

WorkflowSTT are the speech-to-text models Transcribe and Convert use.

func (WorkflowSTT) For

func (m WorkflowSTT) For(lang string) (string, bool)

For is the model for a language (BCP-47; "" = detected) and whether it times words itself.

type Workflows

type Workflows struct {
	// contains filtered or unexported fields
}

Workflows is the workflow service. Goroutine-safe.

func NewWorkflows

func NewWorkflows(cfg WorkflowsConfig) *Workflows

NewWorkflows builds the service, registers its executor and follows its jobs (to close runs).

func (*Workflows) Active

func (s *Workflows) Active(ctx context.Context, id string) ([]jobs.Job, error)

Active lists a workflow's unfinished jobs: waiting, queued or running. Interrupted ones are not: they do not run again without a Retry, and a run should not stay "running" because of them (#101 H2).

func (*Workflows) Cancel

func (s *Workflows) Cancel(ctx context.Context, id string) error

Cancel stops a workflow's run: its jobs are cancelled, the steps they were on go back to waiting, and the run can resume later.

func (*Workflows) Delete

func (s *Workflows) Delete(ctx context.Context, id string) error

Delete cancels a workflow's run and removes it with its files.

func (*Workflows) Dir

func (s *Workflows) Dir(id string) string

Dir is the directory of workflow id's files.

func (*Workflows) Executor

func (s *Workflows) Executor() jobs.Executor

Executor runs workflow.step jobs (registered by NewWorkflows).

func (*Workflows) ExportAll

func (s *Workflows) ExportAll(ctx context.Context, id, dir, template string) ([]string, error)

ExportAll copies every final result of the last run into dir, named by template (workflow.DefaultTemplate when ""), audio as WAV, and returns the files written.

func (*Workflows) Get

Get reads a workflow and its last run (nil before the first).

func (*Workflows) List

func (s *Workflows) List(ctx context.Context) ([]store.WorkflowRecord, error)

List lists the workflows (without documents), most recent first.

func (*Workflows) Path

func (s *Workflows) Path(id, name string) string

Path is a result file's absolute path ("" for "").

func (*Workflows) Run

func (s *Workflows) Run(ctx context.Context, id string, o RunOptions) (*workflow.Run, error)

Run starts (or resumes) a run: the results whose recipe is unchanged are kept, the others made by one job per step. It refuses an invalid workflow (*WorkflowInvalidError) and a workflow already running (core.ErrBusy). A run with nothing to do finishes at once.

func (*Workflows) Save

Save creates or updates a workflow (the editor's autosave), normalised.

func (*Workflows) Validate

func (s *Workflows) Validate(w *workflow.Workflow) *workflow.Report

Validate checks a workflow with the app's own findings.

type WorkflowsConfig

type WorkflowsConfig struct {
	Store     store.Workflows
	Bus       *core.Bus
	Scheduler jobs.Scheduler
	// Engine returns the executor of an engine method (stt.transcribe,
	// stt.align, media.decode, media.encode); nil, or a nil executor,
	// fails the step with engine_unavailable.
	Engine func(method string) jobs.Executor
	// Render speaks (svc.Render).
	Render    *Takes
	ModelPath func(ctx context.Context, repo string) (string, error)
	STT       func() WorkflowSTT
	// Caps describes a TTS model (as the dub pipeline's).
	Caps func(repo string) DubModelCaps
	// Voice resolves a voice reference for a model (as the dub
	// pipeline's: saved voices, "speaker:", "preset:"…).
	Voice func(ctx context.Context, ref, model, lang string) (dub.VoiceSpec, error)
	// Translator returns a translator by name ("" = the language model).
	Translator func(ctx context.Context, name string) (translate.Translator, error)
	// TranslateLane is the lane of Translate steps (net; gpu for the
	// engine's own LLM). nil = net.
	TranslateLane func() jobs.Lane
	// Check adds the app's findings to validation (models, voices,
	// translators); nil adds none.
	Check workflow.Check
	// Salt is what else results depend on (workflow.Salt); nil = the
	// speech-to-text model of STT.
	Salt  workflow.Salt
	Now   func() time.Time
	Logf  func(string, ...any)
	Async func(func())
}

WorkflowsConfig wires the workflow service. Store, Bus and Scheduler are required.

Jump to

Keyboard shortcuts

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