# Fluvie 0.3.1 documentation Corpus SHA-256: b02762959c3d5f90fdd77e45548c423c0871d7f16ee286235c094ba2ca129588 # The FrameBuilder escape hatch When no preset fits, drop to a builder with the raw frame clock and paint anything. `FrameBuilder` hands you a `FrameContext` every frame, and your builder returns the widget to render for that frame. Here a bar sweeps across its window: ```dart Widget sweepingBar() => FrameBuilder((ctx) { final reach = ctx.progress; // 0..1 across this element's window return Align( alignment: Alignment(-1 + reach * 2, 0), child: const SizedBox( width: 24, height: 240, child: ColoredBox(color: Color(0xFF55EFC4)), ), ); }); ``` `FrameBuilder` is `@experimental`: the escape-hatch surface may still change. Reach for a preset or `.animate()` first. Drop to `FrameBuilder` when you need to read the frame directly. The rest of this page covers the `FrameContext` and the one rule that keeps a builder deterministic. ## The FrameContext The `ctx` your builder receives reads the render state from the same scopes the rest of Fluvie reads. The values: - `ctx.frame` is the absolute video frame this build is for. - `ctx.progress` is `0..1` across this element's resolved window. - `ctx.fps` is the frames per second of the enclosing scope. - `ctx.scope` is the enclosing time scope, with its start frame and length. - `ctx.noise(seed)` is a seeded noise scalar in `0..1` for the seed. - `ctx.audio(track)` is the analysed bass energy of a track, `0..1`. - `ctx.audioBand(track, band)` is the analysed energy of one band. `progress` is the value most builders want. It runs from 0 at the start of the element's window to 1 at the end, so a builder reads as an animation without a curve or a tween. ## Reading noise and audio `ctx.noise` and `ctx.audio` give you the same seeded randomness and the same analysed audio that the effects read. Both are precomputed before the frame loop, so a builder that reads them stays a pure function of the frame: ```dart Widget pulsingChip(Anchor music) => FrameBuilder((ctx) { final wobble = ctx.noise('chip-${ctx.frame ~/ 6}') * 0.1; // seeded, reproducible final beat = ctx.audio(music); // analysed bass energy, 0..1 return Transform.scale( scale: 1 + beat * 0.4 + wobble, child: const SizedBox( width: 120, height: 120, child: ColoredBox(color: Color(0xFF7C5CFF)), ), ); }); ``` `ctx.audio(track)` returns the bass band. For the mid or treble band, call `ctx.audioBand(track, AudioBand.mid)` or `AudioBand.treble`. Pass `null` for the track to read the first audible declared track. The energy comes from the per-frame band table the render shell analyses before frame 0, so it is a pure lookup at frame time. These normalized source energies do not include gain, fades or the encoded mix. In capture without a precomputed reactive scope, `ctx.audio` and `ctx.audioBand` throw and name the band and the precompute pass, because reading live audio in a frame would break determinism. When an audio read first appears on a later frame, declare `requiresAudioAnalysis: true` in the builder's resources. This prepares the composition's declared audio tracks before frame zero. Live preview can return `0` when no analysis backend is available. ## Resources that first appear later Normal reusable `StatelessWidget`, `Builder`, and `LayoutBuilder` components need no resource declarations: Fluvie mounts their real Flutter trees during preparation. A frame-dependent branch can hide a source until after preparation. Declare those alternatives on the component that owns them: ```dart /// Prepare an image whose widget first appears on a later video frame. Widget laterPhoto() => FrameBuilder( (ctx) => ctx.frame < 60 ? const SizedBox.shrink() : Image.asset('assets/cat/later.png'), resources: const CompositionResources(media: [MediaSource.asset('assets/cat/later.png')]), ); ``` The image is ready before frame zero and appears at absolute video frame 60. `CompositionResources` can also live on `Video` or `Scene`; a reusable component can wrap its child in `CompositionResourceScope`. It accepts images, clips, generated media, snapshots, caption sources, and shader assets. A `ClipResource` includes its source, visible window, source trim, playback speed, and embedded audio policy so preparation uses the same playback plan as the widget. The `audio` field declares additional sources for analysis; it does not create audible tracks. Use `Video.audio` or `Scene.audio` for the soundtrack, and set `requiresAudioAnalysis` when a later branch reads `ctx.audio` or a reactive effect. An undeclared source that appears after preparation fails with its frame, source, and the declaration needed to prepare it. Resource declarations prepare bytes and metadata; they do not register new timing targets. Keep widgets with `.animate()` or `.show()` mounted during preparation, even when their visibility changes later. Introducing a new motion target after timing resolution fails. Hoisting its animation list alone does not make a previously absent target part of the timing plan. The error identifies the offending owner and frame and suggests unconditional mounting with `.show()` as the stable alternative. Managed capture raises it before accepting that frame; live preview forwards it to its `onError` owner. ## The one rule A `FrameBuilder` must be a pure function of its `FrameContext`. Read the frame, the progress, the seeded noise, and the analysed audio. Do not read the wall-clock, do not call `Random()`, and do not start async work inside the builder. This is the same rule every effect follows, and it is what keeps a builder as cacheable and golden-stable as a preset. The frame is the only clock. Noise and audio are precomputed, never live. Given the same frame and the same scopes, your builder returns the same widget and paints the same pixels every time. Break the rule and the frame cache and the goldens stop agreeing. `fluvie validate lib/my_video.dart --json` and the optional `fluvie_lints` plugin warn about SDK wall-clock reads and unseeded randomness directly inside `Video`, `Scene` and `FrameBuilder` construction. The diagnostic is `nondeterministic_video`; it suggests frame-based inputs, a fixed timestamp or a seed. A generator stored in mutable state can still depend on seek order even when seeded. Prefer `ctx.noise('label-${ctx.frame}')`, or recreate a generator from a frame-derived seed instead of advancing one across builds. This static check does not follow external helpers or widget initialization. Run `fluvie review lib/my_video.dart --determinism` to compare sampled pixels after reverse seeks and a fresh mount. The managed harness invokes your entry function again, so initialization and factory choices are checked too. These are sampled checks on the current runtime; they do not prove every frame or guarantee identical pixels across Flutter engines, platforms or fonts. Dart's standard `ignore` directives are available for deliberate exceptions. ## Where to next - [Shaders and effects](shaders-and-effects.md): write a custom effect when you want a post-process over the rendered child rather than a new widget. - [Audio and captions](../guides/audio-and-captions.md): the analysed band table `ctx.audio` reads, computed once before frame 0. # Live playback and timeline introspection A composition does not have to become a file to be useful. `VideoPreview` owns media preparation, playback, scrubbing, fitting, and its clock. Use it when you want to show an authored composition inside your own Flutter app: ```dart /// Embeds the authored composition in your own Flutter app. Widget preview() => const VideoPreview.builder(builder: build); ``` The builder rebuilds authored code after hot reload while preserving playback position. Place the preview in a bounded layout such as a `Scaffold` body. Pass a `PreviewAudioController` when the host provides audio; the CLI configures its browser audio automatically. Browser sound starts after a user gesture. For lower-level hosting, `LivePlayer` connects a caller-owned controller to the frame clock. `introspectTimeline` reports timeline positions without mounting a widget. ## Playing a Video live `LivePlaybackController` is a wall-clock face for the frame clock. It maps elapsed time to frame indexes; `LivePlayer` owns the ticker and delivers each frame to the tree through the same per-frame rebuild path capture uses. Create the controller once in `initState`, update it when the timeline changes, and dispose it with its owning `State`: ```dart class PlayingVideo extends StatefulWidget { const PlayingVideo({required this.video, this.previewMedia = false, super.key}); final Video video; final bool previewMedia; @override State createState() => _PlayingVideoState(); } class _PlayingVideoState extends State { late LivePlaybackController playback; @override void initState() { super.initState(); playback = createPlayback(); } LivePlaybackController createPlayback() => LivePlaybackController(fps: widget.video.fps, totalFrames: widget.video.totalFrames)..play(); @override void didUpdateWidget(PlayingVideo oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.video.fps != widget.video.fps || oldWidget.video.totalFrames != widget.video.totalFrames) { playback.dispose(); playback = createPlayback(); } } @override void dispose() { playback.dispose(); super.dispose(); } @override Widget build(BuildContext context) => LivePlayer( controller: playback, child: widget.previewMedia ? PreviewMediaScope(composition: widget.video) : widget.video, ); } ``` There is exactly one frame clock. When the controller says frame 90, authored animations render frame 90. Pause it and the picture freezes; seek it and the picture lands at that authored position. ## Playing clips in a preview `fluvie preview ./lib/my_video.dart` wires this for you. Reach for the rest of this section only when you host a `LivePlayer` yourself, in an app of your own. A player alone gives a `Clip` no frames to paint. A render prepares metadata and the needed clip pictures before each capture, and paint reads that cache synchronously. A plain preview runs no pre-pass, so a clip shows a labelled placeholder instead. Wrap the composition in a `PreviewMediaScope` to run the same pre-pass: ```dart Widget playLiveWithMedia(Video video) => PlayingVideo(video: video, previewMedia: true); ``` The scope prepares the composition's media and mounts its resolver. Clip frames are requested as needed. The painter uses the same timeline and resampling logic as capture. Exact variable-rate timing depends on the selected decoder; the CLI's native bridge supplies source presentation timestamps. Three things to know: - **Preview resolution is bounded.** `maxClipEdge` scales raster decoding (720 by default) while layout, source timing, trims, and resampling keep the original facts. Pass `null` for full source resolution. `VideoPreview` uses an on-demand scrub cache rather than retaining an entire movie's full-size frames. - **Preparation is asynchronous.** The player shows preparation before playback and reports media failures visibly through `onError`. Seeking requests source frames for the new position; it does not decode the whole movie first. - **Your host chooses its decoder.** The CLI configures native tools and its local browser bridge automatically. An independently hosted web preview can pass `clipDecoder:`; a native host can select its media resolver. With no usable decoder, lower-level media scopes report the cause and show fallback content. ## The playback surface ```dart Future driveIt(LivePlaybackController playback) async { playback.play(); // free-run from the current frame playback.pause(); // freeze right here playback.seek(120); // land exactly on frame 120 playback.hold(120); // land there and stay (back-navigation wants this) playback.rate = 1.5; // one-and-a-half speed, rebased without a jump await playback.playRange(120, 180); // play a segment, hold its last frame } ``` Two details worth knowing: - `seek` and `rate` rebase the clock at the current frame, so a playing video never jumps when you scrub or change speed. - `playRange` returns a future that completes when the segment's last frame holds, or when something interrupts it. It never errors and never hangs. Listen to `playback.frames` for per-frame notifications and to the controller itself for state changes. The split keeps chrome from rebuilding sixty times a second. Natural playback holds the final picture while its complete frame interval finishes. A one-picture video still plays for `1 / fps` seconds. The integer `frame` identifies the picture being painted; continuous `position` includes that final interval and drives preview audio. `isComplete` becomes true only when the whole duration has elapsed. Seeking to the final picture leaves that interval available to play. `LivePlayer` mounts `RenderMode.preview`, so wall-clock widgets and platform views are allowed: nothing is being encoded. Determinism binds captures, not previews. ## Reading the timeline without mounting it `introspectTimeline` resolves a video's timing plan statically. Same resolver the mounted `Video` runs, no widgets, no IO, same input same output: ```dart void whereThingsAre(Video video, Anchor logo) { final introspection = introspectTimeline(video); final scene = introspection.scenes[1]; debugPrint('scene 1 runs ${scene.span.start}..${scene.span.end}'); final element = introspection.elementForAnchor(logo)!; debugPrint('the logo is alive ${element.window}'); debugPrint('its entrance plays ${element.enterSpan}'); } ``` The introspection returns `FrameSpan` values (half-open frame ranges) for every scene and every animated element: its alive-window, each animation's absolute span, and `enterSpan`, the combined entrance an element plays to come in as authored. Elements resolve by `Anchor` instance, by widget key, by the widget instances you walked yourself, or by spec element id through `elementById` (a deck built from a spec tags each identified element; a widget-authored deck opts in by wrapping an element in `SpecElementId`). One boundary to respect: introspection walks the tree you declared, the same way media pre-resolution does. An element created inside an opaque custom widget's `build()` is invisible to it. Keep `.animate()` calls in constructor data (scene children, plain layout widgets) and the walk sees everything. ## Dynamic subtrees with LocalMotionScope A `Video` resolves its plan once, so its element set must stay stable across frames. Live consumers sometimes want the opposite: content that appears mid-playback and animates in right then. Wrap the dynamic part in a `LocalMotionScope`: ```dart Widget lateArrival({required bool revealed}) => LocalMotionScope( child: revealed ? const Text('surprise!').animate([Animation.fadeIn()]) : const SizedBox.shrink(), ); ``` Below the scope, `.animate()` elements resolve immediately and locally against the nearest time scope. They can mount and unmount whenever they like. The trade: cross-element triggers (`Trigger.whenEnds`, `whenStarts`) and `Trigger.beat` need the composition plan, so they are unavailable inside. `Trigger.previous` chains on one element still work. ## Live placement overrides for editors A canvas editor drags elements many times a second. Rebuilding the composition per pointer move would remount players and reset element state, so `PlacedOverrides` takes the other route: it mounts per-element `Placement` replacements over a composition that stays exactly as built. ```dart Widget dragPreview(Video video, Map live, LivePlaybackController held) => LivePlayer( controller: held, child: PlacedOverrides(overrides: live, child: video), ); ``` Each `Placed` element that carries an `id` (the spec's element ids flow through automatically) reads its own entry and re-lays out; elements without an entry never rebuild. On release the editor writes the real `transform` and clears the map. The overrides are a preview surface only: saving, digests, and renders read the document, never this scope. ## Where to next - [The FrameBuilder escape hatch](frame-builder.md) reads the same frame clock from inside the tree. - [Timeline orchestration](timeline-orchestration.md) places animations the introspector will happily report back to you. - [Scenes and transitions](../guides/scenes-and-transitions.md) covers the boundaries the scene spans reflect. # Multi-aspect Write a video once, render it to reels, square, landscape, and portrait. An `Adaptive` widget branches its layout per aspect, and `render(video, aspect:)` picks the variant. Lesson 11 lays one subtree out four ways: ```dart child: Adaptive( reels: () => _aspectStack('Built for reels'), portrait45: () => _aspectStack('Built for 4:5'), square: () => _aspectStack('Built for square'), landscape: () => _aspectRow('Built for landscape'), ), ``` Each branch is a builder of plain content. The tall aspects stack their blocks; the landscape aspect places them side by side. The rest of this page covers the four aspects, rendering each one, and what stays the same across them. ## The four aspects `Aspect` names the aspect-ratio families: ```dart Aspect.reels, // vertical 9:16, for Reels, Shorts, TikTok, Stories Aspect.square, // 1:1, for feed posts Aspect.landscape, // horizontal 16:9, for YouTube, presentations, TV Aspect.portrait45, // vertical 4:5, the tall feed-post format ``` `reels` is the default when nothing sets an aspect. Each aspect derives its canvas size from a long edge, so the same long edge gives a `1080 by 1920` reel and a `1920 by 1080` landscape frame. ## Rendering each aspect `render(video, aspect:)` re-derives the canvas size from the aspect and renders the composition for it. Loop over the aspects to fan one definition out: ```dart Future renderForAspects({ required Widget composition, required RenderService service, required ShellMount pumpWidget, required ShellFramePump pumpFrame, }) async { for (final aspect in [Aspect.reels, Aspect.square, Aspect.landscape, Aspect.portrait45]) { await render( composition: composition, aspect: aspect, frameCount: 90, outDir: Directory('out/${aspect.name}'), service: service, pumpWidget: pumpWidget, pumpFrame: pumpFrame, ); } } ``` `render` ignores any size the composition declares for itself and uses the aspect's size instead. It mounts the aspect over the tree, so every `Adaptive` branch and every `AspectScope.of` read picks the variant for the render in progress. The `service`, `pumpWidget`, and `pumpFrame` are the host's render wiring. A host that already has a `Video` should reach for `renderVideo(video:, aspect:)` instead: it takes the same aspect and derives everything else from the video. See [the rendering surface](../reference/rendering-surface.md). From the command line, the same job is one flag: ```sh fluvie render ./lib/my_video.dart --out landscape.mp4 --aspect landscape ``` ## Branching at build time `Adaptive` covers a whole subtree. When one element wants to branch its own layout, read the aspect directly with `AspectScope.of(context)`: ```dart Widget headlineForAspect() => Builder( builder: (context) { final wide = AspectScope.of(context) == Aspect.landscape; return Text( wide ? 'Wide cut' : 'Tall cut', style: const TextStyle(fontSize: 64, color: Color(0xFFE6EDF3)), ); }, ); ``` `AspectScope.of` never throws. Outside a render, or in a plain preview, it returns `Aspect.reels`, so an element always has a sane default. One rule for `Adaptive`: every aspect you render needs a matching branch. A null branch for the aspect under render throws an `ArgumentError` at build time, so a missing layout fails loudly rather than rendering nothing. ## Timing is the same across aspects The headline contract: only the layout branches. The timing does not. The same plan resolves for every aspect, so an animation that starts at 0.5 seconds and runs for 1 second starts and runs the same in the reel and in the landscape cut. The aspects share one clock and differ only in shape. This holds because `render` re-derives the canvas size and re-runs layout per aspect, but resolves the same schedule. A trigger that fires after another element fires at the same frame in every aspect. A stagger keeps its step. What changes between a tall cut and a wide cut is where things sit, never when they happen. Each aspect renders on its own terms. The per-aspect renders each carry their own size in the cache key, so the reel and the landscape cut cache separately and never collide. ## Where to next - [Templates](templates.md): pair multi-aspect with a data-driven template to fan one definition across formats and rows. - [Theming](theming.md): brand every aspect from one palette and type scale. # Performance A render does two jobs in order: capture every frame, then encode them into a file. This page explains what each costs, where the caches help, and the small habits that keep a render fast. Start with the biggest lever, the frame cache: ```sh # an unchanged composition, re-rendered: every frame is a cache hit fluvie render ./lib/my_video.dart ``` Run that twice and the second run reads frames from disk instead of pumping the widget tree. File renders enable this cache automatically. ## Keep the authoring engine warm `fluvie workspace lib/my_video.dart` keeps one Flutter worker alive per source revision. Exact frames, reviews and exports reuse compilation and engine startup. Each request still mounts a fresh composition and releases its media. Source changes retire the worker, and edits during rendering reject stale results. Measure `startupMilliseconds`, `captureMilliseconds` and `elapsedMilliseconds` separately. See [the authoring workspace](../guides/authoring-workspace.md). ## Capture and encode are two phases Capture pumps the widget tree to each frame in turn and reads its pixels. The frame is the only clock, so capture is sequential: frame `n` is built and read before frame `n + 1`. Capture cost scales with the frame count and with how much work each frame's tree does. Encode hands the captured frames to FFmpeg, which compresses them into the container. Encode cost scales with the resolution, the frame count, and the quality. A higher `Quality` (a lower CRF) writes a bigger file and takes longer. For most videos capture dominates. A 6 second reel at 30 fps is 180 frames, and each frame pumps a full tree. The encode is one FFmpeg pass over those frames. ## The frame cache skips repeated work Captured frames are stored on disk, keyed by a render digest and frame index. For a Dart file, the CLI adds a content fingerprint covering project-local Dart sources, including helpers and parts outside `lib/`, resolved dependency Dart code, pubspec and package resolution, assets and fonts, explicit renderer or harness files, export options, and toolchain identity. Editing a source file or replacing an asset invalidates the cached frames even when the video keeps the same duration and dimensions. Build/tool caches and generated adapter directories are excluded from the project scan. A target or renderer physically outside the selected project disables frame caching unless you supply a caller-owned `--cache-key`: its external relative dependency closure is not covered. Include a version or hash for external input in that key and change it when the input changes. Runtime network data, generators and undeclared external files need `--no-cache` when you cannot establish a reliable identity. An unchanged file render reuses frames by default. Changing an export option also changes the fingerprint; this conservative rule can recapture frames even when an option affects only encoding. Use `--no-cache` to force fresh capture: ```sh fluvie render ./lib/my_video.dart fluvie render ./lib/my_video.dart --no-cache ``` The CLI does not automatically track changing network content. Built-in `generate` and `edit` author-and-render operations capture fresh. A custom programmatic renderer must supply its own stable composition identity when it enables frame caching; the CLI source fingerprint belongs to the CLI host. See the [cache identity contract](../guides/exporting-your-video.md#the-frame-cache) for the command-line and `runRenderPipeline` options. ## Content-hash caching loads media once Preparation mounts the composition's real Flutter tree, gathers its media, resolves images, and probes clips before capture. Resource bytes and decoded images are shared through content-hash caches. Clip source frames use a bounded frame cache instead of decoding an entire long clip upfront. Painting reads prepared media synchronously. The preparation step for a capture frame can still await clip decoding; that work happens before pumping and reading the widget's pixels. Synchronous paint lookup does not mean decoding is free. Each asset is keyed by the hash of its bytes, so identical declarations share one load. Reuse a declaration to get the cache hit: ```dart logo, // scene one: one decode logo, // scene two: a cache hit on the same bytes ``` Two `Image.network` calls to the same URL also hash to the same bytes, so they share a decode even when they are separate declarations. ## Native clip decoding stays bounded Persistent decoded clip frames also include the extractor's implementation/build identity in their key, alongside source content, dimensions and decoder choice. The default desktop extractor streams a SHA-256 of the resolved FFmpeg executable and hashes its full version/build output. It memoizes that lookup by canonical path, size and filesystem times, with up to 16 build lookups retained; normal binary replacement invalidates reuse without per-frame hashing. Changes that preserve all of those filesystem metadata values are outside that memoization contract. A custom extractor can implement `FrameExtractionCacheIdentity` and return a stable `cacheIdentity`, or supply an explicit identity to `FfmpegFrameExtractionService` when using an injected process runner. Include every pixel-affecting setting and change it when output can change. Missing, empty or unavailable identities disable persistent clip-frame reuse; bounded in-run decoding remains available. The versioned cache key leaves older entries cold so an earlier decoder build cannot silently supply new pixels. Package export hosts look ahead 15 frames, grouping up to 16 source-frame requests into one decode. A per-source 32 MiB RGBA budget limits batch size and retained scrub frames, normally to at most 16 indices. This is a soft budget: a single larger frame or simultaneously required pictures can exceed it. Direct preview seeks use zero lookahead. Future clip windows wait until visible, and a seek that needs a held final picture reuses that picture. Replaced decode-all frame handles are released after painting. Advanced hosts can tune `CompositionSession.clipLookaheadFrames` on the rendering barrel; ordinary CLI renders use the package default automatically. A local two-second H.264 fixture at 160×90 and 30 fps took 2,741 ms for 60 cold single-frame native requests, compared with 221 ms for four batches of up to 16 frames: about 12.4 times faster, with identical concatenated RGBA hashes. This is one extraction measurement; resolution, codec, source offset, and machine change the cost. The default native clip reader keeps an owned FFmpeg frame session. Sequential requests continue from the decoder's current position; backward seeks restart it. Only requested pixels enter the Dart frame cache. A distant or backward request seeks from an indexed source keyframe and verifies the first decoded presentation timestamp. If the demuxer cannot establish exact alignment, the reader falls back to decoding from the origin. `decoderStarts` and `framesRead` expose the work for diagnostics; long GOPs and uncertain seek alignment can still cost more. Close the session when its source is released. Timeout, cancellation and disposal terminate and reap its owned decoder. The local HTTP bridge used by browser preview retains at most four source sessions with least-recently-used eviction. Decoded frame caching is bounded to 32 MiB; releasing a source or closing the bridge closes its owned decoder. Native timing uses presentation timestamps rather than average FPS when a source has variable frame intervals. `MediaTimeline` normalizes the first displayed picture to time zero and preserves the final picture's interval. The default native resolver supplies that index to clip trim, speed and resampling logic. Custom media resolvers can expose `ClipTimelineResolver`. Browser byte decoders can additionally implement `WebClipTimelineDecoder` from the rendering barrel; `WebImageMediaResolver` uses its `MediaTimeline` when one is available. The local preview bridge supplies the native source index through this interface. A decoder without a source timeline falls back to its reported constant frame rate. ## Keep snapshots pre-resolved A `Snapshot`, `Mermaid`, `WebView`, or `Html` is rasterized once before the frame loop and painted every frame from the cached image. That pre-pass is the expensive part, and it runs outside capture. Declare a snapshot once and reuse the result rather than rebuilding the source every frame. ## Parallelism is per render, not per frame One render captures frames in order, so a single composition does not split across cores at the frame level. Parallelism lives one level up: each render is an independent, deterministic process. - A data-driven batch renders one definition per row. The rows are independent, so run them as separate processes across your cores. - A multi-aspect fan-out renders the same definition to reels, square, landscape, and portrait. Each aspect is an independent render and caches under its own canvas size, so they never collide. Because every render is independent, a batch is safe to shard: re-run only the rows that changed, on as many workers as you have. ## Keep animation lists stable The resolver must see the same animations on every frame. An element inside a per-frame `Builder` rebuilds each frame, so a fresh list literal inside that builder registers a new token after resolution and throws. Hoist the list to a stable field instead: ```dart Builder( builder: (context) => const Text('Stable', style: _line).animate(_stablePop), ); ``` `_stablePop` is a `final List` declared once, so every rebuild binds the same list. Lessons 11 and 12 follow this rule for every element inside a `Builder`. An element built once (directly in a scene's `children`) can keep its inline list. ## Memory for large compositions Default native reactive-audio analysis decodes the audible source interval plus 250 ms of FFT/onset lookahead. Declared `Audio` tracks share the encoder's timing resolution: trims start at source time, scene and sound-effect delays place the analysis on the composition clock, and loops repeat the decoded interval. Source EOF carries its actual duration so a fractional-frame loop does not accumulate rounding drift. Energies and beats are silent outside the audible window. `AudioWindowResolver`, `RangedBeatDetectionService` and `RangedFrequencyAnalyzer` are additive capabilities for custom hosts. The ranged band result includes the actual source duration. Existing resolvers retain their source-only contract; existing analysis services can analyze the needed source prefix for a window-aware repository. Native `FfmpegPcmDecoder.decodeRange` seeks and bounds the decoded interval. Legacy PCM decoders can be sliced after full decoding; their peak allocation remains the delegate's responsibility. Reactivity still reads normalized energies from the selected track, with the first audible declared track as the default. This is not analysis of the encoded master mix, gain automation or clipping. Generated audio without a declared track window retains the source-only fallback. Default reactive-audio preparation shares one PCM decode between beat detection and frequency-band analysis for the same source. `SharedPcmDecoder` coalesces equal active requests and retains at most one completed source and 128 MiB by default, counting the backing buffer. Preparation releases that PCM after the derived beat grids and band tables are built, including on failure. A failed band analysis publishes neither table, so retry can prepare the complete source. Injected analysis services keep their own decoder ownership. Custom hosts can share `SharedPcmDecoder` between their analysis services, tune `maxBytes`/`maxSources`, and call `clear()` when source files change or `dispose()` when the preparation ends. Its budgets bound completed retention, not allocations inside a delegate or samples still held by callers. Disposal rejects pending requests but does not dispose an injected delegate; connect the same cancellation signal to any native decoder it owns. Captured frames stream straight to a file as they are produced, so the captured sequence does not sit in memory. The things that do grow with the composition are the resolved resource bytes and images, bounded clip-frame caches, and the frame cache on disk (one file per cached frame). For a long video with many large stills, reuse declarations so the media cache holds one copy per unique asset. For a quick draft, render a frame window with `--frames N` to capture only the first `N` frames. ## Where to next - [Multi-aspect](multi-aspect.md): why each aspect renders and caches independently. - [Templates](templates.md): one definition per data row, the unit a batch shards on. # Shaders and effects Effects in Fluvie are animations. Grain, a vignette, particles, a fragment shader: they all go in the same `.animate([...])` list as your slides and fades, and Fluvie applies them in a fixed order. Here are two pixel effects laid over a photo wall, in the same list as the slide that brings the tiles in: ```dart Padding( padding: const EdgeInsets.fromLTRB(64, 64, 64, 180), child: Wrap( spacing: 16, runSpacing: 16, alignment: WrapAlignment.center, runAlignment: WrapAlignment.center, children: [ for (final photo in _photos) SizedBox( width: 280, height: 280, child: Image.asset( photo, fit: BoxFit.cover, frame: const PhotoFrame.card(), ), ), ], ).animate([ // Transforms wrap the wall; the two pixel effects post-process // the result, regardless of list order. Animation.slideFadeIn(stagger: const Stagger.each(Time.frames(2))), Animation.grain(0.18), Animation.vignette(0.4), ]), ), ``` There is no separate effects system. One list, one mechanism. ## Two classes, one order Fluvie sorts every animation into one of two classes and always builds them the same way: - **Transforms** wrap the widget first: opacity, position, scale, rotation, blur, color. They run in list order, innermost first. - **Pixel effects** post-process the rendered result: grain, vignette, scanlines, chromatic, bloom, glitch, particles, and shaders. They run last, in list order among themselves. So `[slideFadeIn, grain]` and `[grain, slideFadeIn]` produce the same frame: the wall slides into place, then grain lays over the result. You never order the two classes by hand. This is the unified pipeline. ## The pixel-fx family Each pixel effect takes its strength as a plain number and holds it across the window: - `Animation.grain(amount)` lays seeded monochrome speckle over the frame. - `Animation.vignette(amount)` darkens the edges toward the center. - `Animation.scanlines()` overlays thin dark horizontal lines for a CRT look. - `Animation.chromatic(px)` splits the red and blue channels by a pixel offset. - `Animation.bloom(amount)` bleeds a soft glow out of the bright areas. - `Animation.glitchIn()` tears the frame briefly, then resolves to natural. `amount` clamps to the range 0 to 1; `0` paints nothing. Every painter is a pure function of the frame and its parameters, so the same input always paints the same pixels. None of them read the backdrop or force a `saveLayer`, so they capture cleanly off-screen. ## Particles `Animation.particles` lays a field of particles over the element. You describe the field with a `Particles` spec and a seed: ```dart Widget confettiCaption() => const Text( 'You did it', style: TextStyle(fontSize: 56, color: Color(0xFFFFFFFF)), ).animate([ Animation.fadeIn(), Animation.particles(const Particles.confetti(seed: 'six-moments')), ]); ``` There are three families: `Particles.confetti`, `Particles.snow`, and `Particles.sparkle`. Each pins its own count, palette, size range, and motion, and you override one field at a time. The seed is what makes the field reproducible. Each particle reads its placement from the seeded noise source as `valueForSeed("$seed-$i")`, so a given seed lays the field out the same way every render. That stability is what lets the frame cache and goldens trust the output. Change the seed and you get a different but equally stable field. ## Parallax `Animation.parallax({depth})` drifts the element across the scene by a fraction of its own size. It reads the scene clock, not the animation window, so the offset is `depth` times the scene progress. Stack elements at different depths and the small-depth layers read as far background while the large-depth ones read as near foreground. It is a transform-class effect, so it composes with slides and fades like any other transform. ## Seeded float `Animation.float` bobs an element up and down forever. With no seed it is a pure sine, the same motion it has always had. Pass a seed and the sine carries a low-amplitude noise wobble drawn from the same seeded source as particles: ```dart Animation.float(amplitude: 0.04, seed: 'leaf-7'); ``` The wobble is organic but reproducible, and it is sampled on a closed loop, so it stays continuous across the cycle wrap with no jump. Two elements with different seeds bob differently while each stays identical across runs. ## Fragment shaders (experimental) `Animation.shader` paints a fragment shader over the element. It is the escape hatch for effects no preset covers. Point it at a `.frag` asset registered under `flutter: shaders:`, and Fluvie binds `resolution` and `progress` plus your uniforms into the shader's float slots in a fixed order: ```dart Widget rippleLogo() => const ColoredBox( color: Color(0xFF101820), ).animate([Animation.shader('packages/fluvie/shaders/ripple.frag')]); ``` `Animation.shader` is `@experimental`: the surface may change, and a fragment program is a GPU resource whose software-rasterizer fidelity varies by platform. Fluvie pins its shader goldens to the Linux baseline. The bundled `ripple.frag` ships with the package as a usable built-in and the test fixture. Two rules keep shaders capture-safe. First, the render pre-pass walks the composition, compiles every shader program it finds, and publishes them to the tree before frame 0, the same discipline media follows, so no frame ever waits on a load. A missing or invalid asset surfaces as a `FluvieRenderException` that names the asset, and it surfaces in the pre-pass rather than at paint. Second, every uniform is a `num` bound in iteration order, so the GLSL contract is stable from one render to the next. Each element gets its own shader instance derived from the shared program. That matters because a `FragmentShader` owns mutable uniform slots that paint rewrites every frame: two elements sharing one instance would overwrite each other's uniforms. A shader declared inside your own `StatelessWidget`'s `build` is invisible to the pre-pass, exactly as a `Clip` inside one is invisible to media collection. Declare it in the scene tree, or its first paint tells you the asset was never warmed. ## Writing your own effect When no preset fits, implement `AnimationEffect` for a transform or `PixelAnimationEffect` for a pixel post-process. The marker is the only difference: implementing `PixelAnimationEffect` opts your effect into the pixel class, so Fluvie applies it over the transformed child: ```dart Widget scanlineSweepText() => const Text( 'Sweeping in', style: TextStyle(fontSize: 48, color: Color(0xFFFFFFFF)), ).animate([const Animation.custom(ScanlineSweep())]); /// A custom pixel post-effect: implementing [PixelAnimationEffect] (not just /// [AnimationEffect]) opts into the pixel class, so Fluvie applies it over the /// transformed child, after every transform. final class ScanlineSweep implements PixelAnimationEffect { const ScanlineSweep({this.band = 0.12}); /// The band height, as a fraction of the child's height. final double band; @override Widget build(Widget child, double progress) => CustomPaint( foregroundPainter: _SweepPainter(progress: progress, band: band), child: child, ); } class _SweepPainter extends CustomPainter { const _SweepPainter({required this.progress, required this.band}); final double progress; final double band; @override void paint(Canvas canvas, Size size) { final height = size.height * band; final top = (size.height + height) * progress - height; canvas.drawRect( Rect.fromLTWH(0, top, size.width, height), Paint()..color = const Color(0x33FFFFFF), ); } @override bool shouldRepaint(_SweepPainter oldDelegate) => oldDelegate.progress != progress || oldDelegate.band != band; } ``` Your `build` is a pure function of `progress`, the value Fluvie passes after it applies your curve. Keep it deterministic: read the seed source for any randomness, never `Random()` or the clock, and the frame cache and goldens stay honest. ## Where to next - [Timing and triggers](../guides/timing-and-triggers.md): when an effect plays and how `at:` chains one off another. - [Cheatsheet](../reference/cheatsheet.md): the whole shipped surface on one page. # Templates Describe a video shape once, then render it for many inputs. A `VideoTemplate` turns a `Props` value into a `Video`, so the same definition makes a personalized intro per user or a stat reel per metric. Lesson 11 reuses the built-in `StatHighlight` template and lifts its scene into a reel: ```dart Scene _statCardScene() => const StatHighlight().build(_stat).scenes.single; ``` The props feeding it are plain data: ```dart const _stat = StatHighlightProps(value: 48230, label: 'minutes listened'); ``` Change `_stat` and the same template builds a different card. The rest of this page covers writing your own template, the two built-ins, and rendering a batch. ## Writing a template Subclass `VideoTemplate` and implement `build`. The `build` is a pure function of its props: it reads the value and returns a `Video`, with no IO and no wall-clock: ```dart class GreetingProps { const GreetingProps({required this.name}); final String name; } class GreetingTemplate extends VideoTemplate { const GreetingTemplate(); @override Video build(GreetingProps props) => Video( size: VideoSize.reels, scenes: [ Scene.centered( duration: const Time.seconds(3), background: Background.color(const Color(0xFF0E1116)), child: Text( 'Hi ${props.name}', style: const TextStyle(fontSize: 80, color: Color(0xFF55EFC4)), ).animate([Animation.pop()]), ), ], ); } ``` A template is `const` and holds no state. Every choice flows through the props, which keeps the definition a pure function of its input. Make your `Props` value-equal (immutable, with `==` and `hashCode` by field), so two equal props compare equal and the cache can trust them. ## The built-in templates Two templates ship on the public API. Each is built only on the public element API, so it doubles as a worked example of a `VideoTemplate`. `TitleIntro` is a centered title that pops in, with an optional subtitle that slides in after: ```dart const TitleIntroProps(title: '2025', subtitle: 'Year in review'); ``` `StatHighlight` is a `Counter` headline counting up to a value, with its label beneath: ```dart const StatHighlightProps(value: 48230, label: 'minutes listened'); ``` Both props carry an optional `accent` color and `background` color, so you brand a card without rewriting it. Read the source of either as a starting point for your own template. ## Rendering a template `renderTemplate` builds `template.build(props)` and runs the result through the same offline capture path that `render(video, aspect:)` uses. It is a separate free function from `render`, because Dart has no overloading. To render a batch, map each data row onto its props and call `renderTemplate` once per row: ```dart Future renderGreetings({ required List names, required RenderService service, required ShellMount pumpWidget, required ShellFramePump pumpFrame, }) async { for (final name in names) { await renderTemplate( const GreetingTemplate(), props: GreetingProps(name: name), frameCount: 90, outDir: Directory('out/$name'), service: service, pumpWidget: pumpWidget, pumpFrame: pumpFrame, ); } } ``` `renderTemplate` defaults `aspect` to `Aspect.reels`, so a template renders vertical without a per-call aspect. Pass another aspect to fan one template out across formats. The `service`, `pumpWidget`, and `pumpFrame` are the host's render wiring; the example app and the CLI supply them for you. ## Same props, same render The same template rendered for the same props produces the same render. This holds because `build` is a pure function of its props: the same props build the same tree, the same tree captures the same picture, and value-equal props let the frame cache share work across renders. Different props produce different frames, as you would expect. Pass a different `value` and the count changes; pass an equal `Props` and you get the same render. This is what makes data-driven batch rendering safe. Render a thousand personalized intros from a thousand rows, re-run the batch tomorrow, and every unchanged row produces the same file it did today. ## Where to next - [Multi-aspect](multi-aspect.md): fan one template out to reels, square, landscape, and portrait with the same props. - [Exporting your video](../guides/exporting-your-video.md): pick the container each rendered template writes. # Theming Brand a video from one palette and one type scale. Wrap a subtree in a `FluvieTheme` and its descendants read the brand colors and the type ladder from `context.fluvie`. Lesson 11 sets a brand and a scale once: ```dart const _brand = Palette( bg: Color(0xFF0E1116), accent: Color(0xFF55EFC4), onBg: Color(0xFFE6EDF3), ); final _type = TypeScale.fromBase(40, ratio: 1.3); ``` Text reads those tokens at the call site, picking the display role and the brand accent: ```dart Builder( builder: (context) => Text( 'One definition,\nmany formats', textAlign: TextAlign.center, style: context.fluvie.type.display.copyWith(color: context.fluvie.brand.accent), ).animate([Animation.pop()]), ); ``` The rest of this page covers the palette, the type scale, the three token groups, and the precedence rule. ## FluvieTheme `FluvieTheme` carries three optional tokens and a child. Each token you omit inherits from the nearest theme above, so themes nest and an inner theme overrides only the fields it sets: ```dart FluvieTheme( palette: const Palette( bg: Color(0xFF0E1116), accent: Color(0xFF55EFC4), onBg: Color(0xFFE6EDF3), ), type: TypeScale.fromBase(40, ratio: 1.3), motion: const Defaults(duration: Time.seconds(0.5), ease: Ease.out), child: video, ); ``` Wrap a whole `Video` to brand everything, or wrap one scene to brand a section. Every element that already reads `context.fluvie` (charts, `Code`, `Mermaid`, captions, annotations) picks the brand up with no change at the call site. ## The palette `Palette` is the brand color set. It carries the backdrop, the accent, the foreground that reads on the backdrop, and an optional raised-surface pair: ```dart const Palette( bg: Color(0xFF0E1116), // the backdrop accent: Color(0xFF55EFC4), // the brand color for emphasis onBg: Color(0xFFE6EDF3), // the foreground that reads on bg surface: Color(0xFF1A1F26), // optional: a raised-panel color onSurface: Color(0xFFE6EDF3), // optional: the ink on a surface ); ``` Read it via `context.fluvie.brand`: ```dart context.fluvie.brand.bg, context.fluvie.brand.accent, context.fluvie.brand.onBg, ``` One name to keep straight: `context.fluvie.brand` is this brand palette. `context.fluvie.palette` is a different thing, the ordered chart-series colors a chart cycles through. For brand colors, reach for `.brand`. ## The type scale `TypeScale.fromBase` derives five text roles from one base size and a ratio. Each role steps the body size up or down by the ratio: ```dart TypeScale.fromBase(40, ratio: 1.3); ``` The five roles, largest to smallest: ```dart context.fluvie.type.display, // hero numbers and full-screen statements context.fluvie.type.title, // scene headings and the main on-screen line context.fluvie.type.headline, // a secondary line above body copy context.fluvie.type.body, // running text and labels, at the base size context.fluvie.type.caption, // footnotes, attributions, fine print ``` A role carries only a font size and a weight, never a font family or a color. That keeps it composable: apply a role and add a color at the call site with `copyWith`, the way the themed text above does. ## The three token groups `context.fluvie` exposes three theme groups: - `context.fluvie.brand` is the `Palette` of brand colors. - `context.fluvie.type` is the `TypeScale` of text roles. - `context.fluvie.motion` is the `Defaults` for animation duration and easing. The `motion` group folds into the animation cascade, so a theme can set the default duration and easing for every animation under it without touching each one. ## Precedence When more than one source sets a value, the most specific wins. The order, most specific first: 1. An explicit property on the element. A color or duration you write at the call site always wins. 2. The nearest `FluvieTheme`. Its tokens apply where the element did not set one. 3. The package fallback. A real dark-neutral palette, a 16-pixel type scale, and the built-in motion defaults, so an unthemed subtree still has usable tokens. For motion the cascade has one more rung: an animation-local default beats a `Scene` default, which beats a `Video` default, which beats the theme's `motion`, which beats the package. So you set a broad default once in the theme and override it for one animation when you need to. This is why a theme is opt-in and never surprising. Text stays plain until you read a token, an element keeps any color you pass it, and a video with no theme renders exactly as it did before, against the package fallback. ## Where to next - [Multi-aspect](multi-aspect.md): brand every aspect of a video from one theme. - [Charts and data](../guides/charts-and-data.md): the chart-series `context.fluvie.palette`, the other palette a theme carries. - [Templates](templates.md): brand a data-driven template per render with a `Palette` from your props. # Timeline orchestration Most of the time, `.animate()` on each element is all you need. When you want to place many animations on one shared clock, reach for `Timeline`. It is an opt-in, GSAP-style builder that records steps against a running playhead: ```dart Timeline introTimeline(Anchor title, Anchor subtitle, List bullets, Anchor cta) => Timeline(defaults: const Defaults(duration: Time.seconds(0.5))) ..play(title, Animation.slideFadeIn()) ..play(subtitle, Animation.fadeIn(), at: Trigger.whenEnds(title)) ..wait(0.3.seconds) ..playAll(bullets, Animation.slideFadeIn(), stagger: 0.08.seconds) ..label('reveal') ..play(cta, Animation.pop(), at: 'reveal'.label - 0.2.seconds); ``` `Timeline` is experimental. Its surface may change before 1.0. ## How the playhead moves Each call advances a playhead, the running position the next step starts from: - `play(target, animation)` places one animation and moves the playhead to its end. - `playAll(targets, animation, stagger:)` places one animation on many targets, staggered, and moves the playhead to the last one's end. - `wait(time)` advances the playhead with no step. - `label(name)` records the playhead under a name. `duration` is the end of the latest step, derived for you. ## Placing a step with `at:` `at:` overrides where a step starts. It accepts three things: - a `Trigger`, for example `Trigger.whenEnds(title)` to start when `title` ends; - a `String` label, for example `at: 'reveal'`; - a `LabelRef` with offset arithmetic, for example `'reveal'.label - 0.2.seconds`. Label arithmetic stays symbolic until the timeline resolves its placements at the enclosing `Video`'s fps, so it never reaches the per-frame path. An unknown label already throws at the `play()` call. ## Driving a scene Hand a `Timeline` to `Scene.sequence` and the scene adopts the timeline's derived length. You declare the structure once and the scene runs on it: ```dart Scene sequencedScene(Timeline timeline) => Scene.sequence( timeline: timeline, background: Background.color(const Color(0xFF101820)), children: const [Text('Built on one clock')], ); ``` The timeline has no clock of its own: every `Time` in it resolves at the enclosing `Video`'s fps, so the same timeline places identically at 30 or 60 fps. ## Where to next - [Timing and triggers](../guides/timing-and-triggers.md): the triggers and anchors the timeline resolves against. - [Cheatsheet](../reference/cheatsheet.md): the whole shipped surface on one page. # Browser release checks `tool/verify_browser_matrix.sh` exercises the shipped media bridges and the compiled Flutter application in Chrome, Firefox and Playwright's Linux WebKit. The suite opens the main application, creates an empty editor, and opens the speaker route. Media acceptance covers requested frame selection, bounded RGBA retention, unsupported-container refusal, real H.264 output, embedded-audio metadata, worker cancellation, cleanup and reload. Linux WebKit is useful engine coverage; it does not replace Safari testing on macOS or iOS. Reports identify each actual engine version and native frame format. `FLUVIE_BROWSERS` may select `chrome`, `firefox`, or `webkit-linux`; empty selections and misspelled names fail before launch and replace stale report evidence with an error. ## Pixel comparisons An untagged YUV source does not identify one RGB color matrix. The original SD fixture currently defaults to BT.709 in Chrome/Firefox and SMPTE170M in WebKit. The untagged test uses the decoder's declared matrix/range. A second fixture explicitly tags both the H.264 stream and its MP4 container as BT.709; all engines must report that matrix and limited range for that fixture. Canvas rendering can reconstruct subsampled chroma differently. A requirement that every RGB pixel match one FFmpeg upsampler rejected valid color edges in WebKit. Host FFmpeg and FFmpeg.wasm also produced different edge interpolation with identical scaling options. The reference now decodes YUV independently with FFmpeg and converts it with fixed, version-independent BT.601/BT.709 coefficients and centered bilinear chroma reconstruction. The canvas test requires all of the following for the first, middle and last source frames: - Correct dimensions and fully opaque alpha for the opaque fixture. - RGB RMS error at most 3 across every 8×8 area mean, covering the full image. - RGB RMS error at most 3 at full resolution wherever the reference's 5×5 neighborhood varies by at most 3; at least 30% of the image must meet this condition. The current fixture covers about 64%. The report retains the unnormalized full-resolution RGB RMS as a diagnostic; the test does not claim identical RGB pixels at chroma boundaries. The matrix and quantization coefficients follow [ITU-R BT.601](https://www.itu.int/rec/R-REC-BT.601) and [ITU-R BT.709](https://www.itu.int/rec/R-REC-BT.709). The distinction between native planes and rendered color follows the [WebCodecs rendering and copying contract](https://www.w3.org/TR/webcodecs/#videoframe-interface). ## Independent native-frame check A separately encoded, tagged 512×256 H.264 fixture keeps native row strides aligned. This is necessary for the diagnostic `VideoFrame.copyTo` path on the tested Linux WebKit: copying the original 320px NV12 frame returned zero-filled lower rows, despite the production canvas path displaying those rows correctly. Changing the destination stride did not fix that upstream copy behavior. The suite does not change or bypass the production decoder. For engines exposing I420 or NV12, the test copies and normalizes plane layout only, then requires every native YUV byte to equal an independent FFmpeg decode. There is no error tolerance for those samples. For engines exposing an already converted RGB format, it normalizes channel order/stride and requires a full-resolution RGB RMS of at most 3 against independent FFmpeg output. The report states which comparison ran; it never presents an RGB comparison as exact YUV validation. `tool/test/browser_pixel_oracle_test.mjs` covers matrix/range reference values, missing image regions, wrong colors, errors that cancel in area averages, alpha loss, padded I420/NV12/RGB layouts and a single corrupted native byte. Cleanup and engine-selection tests run alongside it with Node's test runner. # Coverage and the ignore policy Fluvie gates line coverage at 97% on production packages and apps with Dart sources under `lib/`. The goal is 100%. This page explains when you may mark a line `// coverage:ignore`. It also says when you must write a test instead. Run the gate before you commit: ```sh melos run coverage:check ``` It runs every package test with coverage. Then it checks the lcov reports against the 97% floor. Generated files never count. Those are `*.g.dart`, `*.freezed.dart`, and `*.mocks.dart`. `dart tool/workspace_inventory.dart --json` derives the targets from the root workspace and package manifests. Production targets are immediate `packages/` and `apps/` directories. Examples and nested fixture packages are analyzed and tested when they have tests, but do not carry the production coverage threshold. The inventory fails when a production library has no test producer or a discovered package is omitted from the workspace. New packages, including `fluvie_media` and `fluvie_render_client`, enter the gate and coverage upload automatically. `coverage:gate` accepts no separately maintained list of package names. The same inventory selects public API documentation targets through `--dartdoc`. `melos run docs:dartdoc` validates links and rejects warnings for every production package with Dart library sources, including private library packages. Apps and examples retain their analysis/test policy rather than producing API reference sites. A new library enters this gate without another package-name list. The required CI coverage job provisions Fluvie's checksum-verified FFmpeg/ffprobe pair and sets `FLUVIE_TEST_NATIVE_MEDIA=1`. This runs `fluvie_media`'s real native timeline, decoder and contact-sheet regressions in its normal source-derived coverage producer. Local runs may opt in with the same flag and configured `FLUVIE_FFMPEG`/`FLUVIE_FFPROBE` pair; a skipped native suite is not evidence that those integration paths were verified. ## The rule Test behavior. Ignore only lines that have none. If a line does real work, write a test that asserts the work. An ignore is a last resort. Every ignore carries a reason on the same line. The gate honors three markers. Write the reason in letters, digits, and spaces only. No colon after the marker, no punctuation in the reason. `package:coverage` (the collector inside `flutter test --coverage`) drops a marker on any other character, and an unbalanced start and end pair crashes the whole test run. The tool test `tool/test/coverage_ignore_syntax_test.dart` pins every marker to this charset. Use an inline marker for one line: ```dart final x = legacy(); // coverage:ignore-line reason here ``` Use a block marker for a run of lines: ```dart // coverage:ignore-start reason here ... block ... // coverage:ignore-end ``` Use a file marker for a whole file: ```dart // coverage:ignore-file reason here ``` The gate reads the source and drops the marked lines from the total. Then it recomputes the percentage. A reason is mandatory. A bare marker hides a gap, so a reviewer must always see why. ## What you may ignore Ignore a line only when no test could assert its behavior. - **Const-constructor evaluation.** The VM does not instrument a `const Foo(...)` literal. Its constructor line reads as uncovered even when tests pin the object. Test the object's fields, equality, and `toString`. Then ignore the constructor line. - **Diagnostic `toString` and `hashCode`.** Prefer a one-line test. Both are cheap to assert. Both guard debug output. Ignore them only when the type is private and the string never reaches a developer. - **Platform, JS, and process glue.** Code that spawns FFmpeg cannot run in a unit test. Nor can a JS bridge or a real filesystem read. Cover its inputs and outputs with a fake. Then ignore the thin glue that calls the binary. - **Defensive and unreachable arms.** A `default` arm or an `assert` stays for safety. A valid input can never reach it. Ignore it with a reason that names why it is unreachable. ## What you may never ignore Never ignore a line that does real work. Write a test instead. - A branch a real input can take. Drive both sides with two tests. - A thrown error a caller can trigger. Assert the throw with `throwsA`. - A calculation, a transform, or a state change. Assert the result. - A whole file, unless it is a platform bridge that the VM cannot load. A hard-to-test line is a design signal. It is not a license to ignore. Inject a fake through a Riverpod override. Split the unit. Expose a pure helper. Report a stubborn defect to the implementer rather than hiding it. ## Where to next - [Testing guide](testing.md): how the suites and fakes fit together. - [Contributing overview](overview.md): the workflow and the quality gate. # Editor release verification Use the repository's release SDK, Flutter 3.47.2 / Dart 3.13.2, for both the commands below and their child processes. A different Flutter renderer can change golden pixels. Commands run from the repository root unless indicated. ## Regression and package gates ```sh flutter pub get melos run gate bash tool/verify_packages.sh /absolute/path/to/flutter-sdk ``` The standard gate checks formatting, static analysis, custom lints, tests and 97% library/app line coverage. It includes the CI golden variants. The [package gate](package-release.md) additionally checks isolated publication contents. It fails on regressions; its analyzer compatibility exception applies only to the lint package's documented dependency freshness deduction. The real Linux application journey exercises import, editing, save/reopen and actual export, including decoded video and audio assertions: ```sh cd apps/slides flutter test integration_test/editor_e2e_test.dart -d linux ``` The broader `tool/run_full_qa.sh` also runs the opt-in suites, example renders, documentation checks and fresh-checkout acceptance. Retain its report separately from focused hardening runs so an earlier full pass cannot be mistaken for a later source revision's result. ## Browser engines ```sh bash apps/slides/tool/fetch_ffmpeg.sh (cd apps/slides && flutter build web --release) node --test tool/test/browser*_test.mjs bash tool/verify_browser_matrix.sh ``` The matrix uses installed Chrome and pinned Playwright Firefox/WebKit binaries. Test dependencies live under ignored `build/`, not in production dependencies. Use `--with-deps` on a provisioned Linux CI runner to install browser system libraries. `CHROME_EXECUTABLE` can select a specific installed Chrome binary; `FLUVIE_BROWSERS=chrome,firefox,webkit-linux` selects engines and rejects typos. The tests exercise the shipped FFmpeg/WebCodecs bridges, H.264 output, cancellation/reload, temporary-file cleanup, source metadata and decoded media. They also boot the compiled application, open the editor from New deck, and verify the speaker route. JSON evidence and screenshots go to `build/release-hardening/browsers/` or `FLUVIE_BROWSER_OUT`. Linux WebKit is engine coverage, not Safari-on-Apple-device certification. [Playwright documents that distinction and its platform-specific media support](https://playwright.dev/docs/browsers). The [pixel oracle notes](browser-release-checks.md) explain the independent native-frame checks and browser-specific chroma interpolation. Verify the actual retained icon constants against bundled font outlines after the release web build, using a Python environment with the pinned dependency: ```sh python3 -m venv build/font-check build/font-check/bin/pip install -r tool/requirements-font-validation.txt PYTHONDONTWRITEBYTECODE=1 build/font-check/bin/python -m unittest discover -s tool -p test_verify_icon_fonts.py build/font-check/bin/python tool/verify_icon_fonts.py --app apps/slides --flutter-root /absolute/path/to/flutter-sdk ``` The verifier rejects missing families, missing glyphs, empty outlines and nonconstant icon declarations that cannot be checked statically. ## Optimized performance ```sh bash tool/verify_editor_performance.sh profile bash tool/verify_editor_performance.sh release ``` Use a real Linux display and FFmpeg. Stop this task's other builds, tests and emulators before collecting final measurements; record any unrelated machine load that cannot be controlled. `FLUVIE_PERF_OUT` selects an evidence directory. The wrapper deletes stale reports and validates the running program's build mode and assertion state. Release executes an AOT test program without a VM service and exits with the test verdict. The workload is a three-minute 3840×2160, 24 fps document: eight video lanes, 240 clip placements, eight initially visible clips, and one repeated six-second source file. It is not a benchmark of 240 independent decoders. Measurements include document/model work, actual timeline wheel scrolling and zoom, canvas dragging through the full editor host, exact undo restoration, preview generation and Full/Half/Quarter source decoding. Engine build/raster `FrameTiming` is reported separately from interaction wall-clock time, which includes test-driver and frame scheduling waits. The report retains medians, p95, maxima, budget counts and ordered per-frame timings, including scheduling and build-to-raster waits. Drag updates and the final commit are split by engine frame number without pausing the gesture. Readiness requires the first decoded canvas image; initial filmstrip/background work can still overlap the first zoom interaction. This measures that actual first-use scenario and does not claim an isolated, fully warmed interaction or infer release frame rates from debug timings. See Flutter's [performance profiling guidance](https://docs.flutter.dev/cookbook/testing/integration/profiling) and [frame timing collection](https://api.flutter.dev/flutter/package-integration_test_integration_test/IntegrationTestWidgetsFlutterBinding/watchPerformance.html). The benchmark build replaces the Linux bundle's entry point. Restore the normal application afterwards: ```sh (cd apps/slides && flutter build linux --release) ``` ## Native mobile acceptance The [mobile example README](../../examples/mobile_purrfect/README.md) contains the exact Android and iOS commands. `native_clip_reader_test.dart` checks fractional/VFR timestamps, B-frame presentation order, rotation, duplicate and out-of-range requests and replacement at the same path. `native_media_acceptance_test.dart` renders a source and two consecutive trimmed/ramped exports. The host FFmpeg oracle independently checks every video frame, timestamps, embedded audio, a source-time frequency event, gains and fades. Keep the installed test application until its media has been collected. The macOS CI job compiles the iOS plugin and runs both native suites on a real iOS simulator runtime. Merely adding that job, parsing Swift or passing Dart method-channel tests does not establish native compilation or AVFoundation correctness. Record an actual native job result before certifying iOS support. Emulator/simulator acceptance likewise does not establish physical-device throughput, memory limits or all hardware codec implementations. The VFR fixtures prove native source-frame ordering and extraction. Composition still maps source time through a scalar frame rate; these tests do not certify arbitrary variable-frame-rate playback cadence. Use constant-frame-rate media when exact composition timing is required by the current model. # Review Flutter SDK golden changes Keep the pixel comparator exact when upgrading Flutter. First prove a failure is fresh and that its master matches the current reference. Retained `test/**/failures` images can predate a successful reference update. ## Flutter 3.47.2 compatibility review The Studio baseline run on Flutter 3.47.2 and Dart 3.13.2 found nine existing fixtures failing in both Linux and blocked-text CI variants. The relevant rounded-border sources and fixtures were unchanged. Obers UI still resolved to git `990286c9`; Alchemist remained 0.14.0. This was not a redesigned screen or a local Obers theme change. CI now pins the same Flutter 3.47.2 renderer. The provenance test `python tool/test/studio_sdk_baseline_test.py` rejects a mismatched CI SDK, nonportable reference paths, changed accepted hashes or a nonzero comparator tolerance. Older renderer baselines are not claimed to match these references. Two separately captured runs of each variant produced identical test PNG bytes. Every captured master matched its current reference SHA-256. Full Linux captures and isolated differences were inspected at native resolution. The differences were confined to the existing rounded border fringes; text, interiors and layout did not move. A signed-distance audit of the reviewed rounded rectangles found no changed pixel more than 3px from those borders. That geometric audit is not a comparison tolerance, an ignored region or a permission to accept future differences. Native rounded-edge rasterization drift is the evidence-supported inference. An old/new engine rendering bisection was not executed, so no particular upstream renderer commit is attributed. Historical timeline captures from July were excluded: they used superseded masters and did not establish a current timeline regression. | Fixture | Linux changed pixels | CI changed pixels | Maximum channel delta | Reviewed geometry | | --- | ---: | ---: | ---: | --- | | wave2_text_scene | 95 | 95 | 7 | Rounded Box card border | | gradient_editor | 200 | 209 | 35 | Stop strip and color field borders | | spectrum_color_picker | 264 | 404 | 34 | Six palette swatch borders | | inspector_shell | 315 | 312 | 21 | Code card and rounded badges | | playground_idle | 118 | 115 | 21 | Code card and language badge | | start_first_run | 450 | 450 | 87 | Tips and template card corners | | start_returning | 804 | 802 | 87 | Recent glyph and template borders | | start_samples_open | 43 | 43 | 35 | Unoccluded template corners | | start_compact | 46 | 46 | 85 | Tips card top corners | Exact paths, dimensions, previous/accepted PNG hashes and audited geometry are recorded in `tool/baselines/flutter_3_47_2_golden_migration.json`. This report records an independently reviewed migration of exactly 18 existing references. Post-update verification passed twice without enabling reference updates: all eight package runs exited zero with fresh successful terminal JSON events, no JSON errors and unchanged accepted reference hashes. These runs covered the six exact files below and both Linux/CI variants. The complete repository gate subsequently passed twice with fresh external runtimes: formatting, fatal analysis, custom lint, 20 successful Flutter batch reports, four successful Dart package reports, 70 root-tool tests and all 11 required coverage targets above 97% per pass. Each report was independently checked for successful terminal JSON and absence of errors. Interrupted and disk-full retries were not counted. This accepts the pre-redesign Fluvie test baseline, not the local Obers tree or any redesigned application screen. Do not update a directory of unrelated goldens or change the comparator. ## Reproduce the review Run each exact file twice, once per variant, using a private temporary runtime and a fresh JSON reporter. Save each variant's failure captures before the next variant overwrites the shared failure filenames. ```sh TMPDIR='' flutter test '' --tags golden \ --plain-name 'variant: Linux' --file-reporter 'json:' TMPDIR='' flutter test '' --tags golden \ --plain-name 'variant: CI' --file-reporter 'json:' ``` The six files are `packages/fluvie/test/serialization/goldens_wave2_test.dart`, the editor's `goldens_gradient_editor_test.dart` and `goldens_spectrum_picker_test.dart`, the gallery's `goldens_shell_test.dart` and `playground_golden_test.dart`, and `apps/slides/test/goldens_start_test.dart`. Run from the owning package. A fresh completed failure report is the expected pre-migration result; it is not a passing gate. After review, migrate only the individually accepted reference paths. Run the same exact files twice without updates, then run the complete repository gate. The Studio suite runner requires a fresh successful terminal JSON event as well as process exit zero before publishing merged coverage. A terminated Flutter process can return zero despite incomplete tests; that is not success. This baseline review supplies no feature completion or 23-board Studio pixel parity claim. Those require separate screenshots and real feature journeys. ## Where to next Read [the coverage policy](coverage.md) and [the release verification guide](editor-release-verification.md). # Contributing overview This page is the workflow: how a change moves from a failing test to a merged commit. The rule that gates everything is one command. Run it before you commit: ```sh CI=true melos run gate ``` The gate runs format, analyze, lint, and the coverage check. All four must be green. Never leave the tree broken. The rest of this page explains each step and the rules around it. ## Set up the workspace Clone the repo and resolve the workspace, then install the hooks: ```sh git clone https://github.com/SimonErich/fluvie.git && cd fluvie dart pub get # resolves the workspace root melos bootstrap # resolves all packages bash .githooks/install.sh # installs the git hooks (required) ``` You need Flutter 3.44+, Dart 3.12+, and `ffmpeg` on your PATH for the render-integration tests. ## Test first, always Every change starts with a failing test. No production `.dart` file lands before its test exists and has failed for the right reason. Red, then green, then refactor. See the [Testing guide](testing.md) for the suites and fakes. ## The quality gate The gate is four steps, each its own melos script: - `melos run format` checks `dart format` left nothing to change. - `melos run analyze` runs `dart analyze` with `--fatal-infos` and `--fatal-warnings`, so an info is a failure. - `melos run lint --no-select` runs the custom lints (`dart run custom_lint`). - `melos run coverage:check` enforces the 97% line-coverage floor. Goldens run separately with `melos run test:goldens` on the Linux baseline. Run `melos` non-interactively with `CI=true` to avoid the prompt path. The analysis gate also checks that publishable packages carry the current workspace lint policy. Before a release, run the isolated [package release checks](package-release.md). ## The layering law Dependencies point down only, inside `packages/fluvie/lib/src/`: ```text core pure Dart: Time, Keyframe, enums, Defaults, contracts ^ timing TimeScope, frame resolution, the trigger/anchor resolver ^ features rendering, animation, composition, elements, media, audio, theme ^ diagnostics the inspector model and timeline table; nothing depends on it ``` `core` depends on nothing but Flutter math types. `timing` depends only on `core`. A feature may depend on `core` and `timing`, never on `diagnostics`. Nothing imports another package's `src/`. The `layering` and `no_src_import` custom lints enforce all of this, so a violation fails `melos run lint`. A forward dependency goes through an interface in the lowest stable layer, with a fake for tests and the real implementation injected through a Riverpod provider. ## Capture is headless In capture mode the frame is the only clock: no wall-clock and no async work inside a frame, and media is pre-resolved before the loop. For effects, prefer seeded `noise(seed)` and `random(seed)` so a golden stays stable run to run. Fluvie does not guarantee byte-identical output across machines or encoders. Regenerate goldens with `flutter test --update-goldens --tags golden` and review the PNG. ## Code standards - One primary public type per file. No `utils.dart` dumping grounds. - 200 lines per production file, 80 lines per widget `build`. The pre-commit hook enforces the file budget. - Every public member of `packages/fluvie` carries dartdoc. - No `TODO`, `FIXME`, `print`, or unjustified `dynamic`. - Page width 100, trailing commas required. - A new public API needs its dartdoc and its documentation page, in the same change. Docs snippets come from compiled sources, never hand-typed; see the voice rules in [the documentation map](https://github.com/SimonErich/fluvie/blob/main/documentation/README.md). ## Commits Use Conventional Commits, one concern per commit (`feat(timing): …`, `fix(rendering): …`). Bundle nothing unrelated. The commit-msg hook enforces the format. ## Where to next - [Testing guide](testing.md): the suites, the tags, and the fakes. - [Coverage and the ignore policy](coverage.md): the 97% floor and when an ignore is allowed. # Package release checks Published archives must work without the repository's parent directories. Every publishable package therefore includes its local `analysis_options.shared.yaml`. That generated file is an exact copy of the root analysis policy, including the 100-column formatter, strict type checks and Very Good Analysis rules. Package-specific documentation rules, fixture exclusions and custom-lint plugins remain in `analysis_options.yaml`. Edit the root policy, then run `dart tool/sync_package_analysis.dart --write`. The `analyze:policy` gate and root tool tests check that every publishable package has the current copy and declares the same Very Good Analysis version as a direct development dependency. This duplication is deliberate: a published package cannot include `../../analysis_options.yaml`, and adding just a local formatter width does not prevent the formatter from following a broken include. See Dart's [analysis configuration documentation](https://dart.dev/tools/analysis). Run `bash tool/verify_packages.sh /absolute/path/to/flutter-sdk` to check the core library, CLI and lint package with the selected release SDK. The current release uses Flutter 3.47.2 / Dart 3.13.2. The script pins pana 0.23.19, supplies explicit Dart and Flutter SDK paths, and saves JSON reports and logs to `build/pana/`. A different report directory and package names may follow the SDK argument. Pana analyzes an isolated copy of each package; no workspace root is passed. The release-hardening evidence also verifies archives reconstructed from the exact file list chosen by `dart pub publish --dry-run`. Full scores are required for analysis, formatting, documentation, conventions and platform support. The core and CLI require full dependency points too. The lint package has one documented exception, described below. The JSON gate checks each category separately, so that exception cannot hide another failure. CI checks all three packages and retains the reports. Fresh-clone verification fails on a package regression; it no longer swallows pana failures. ## Analyzer compatibility As checked against pub.dev on 27 September 2026, the latest [custom_lint_builder 0.8.1](https://pub.dev/packages/custom_lint_builder/versions/0.8.1) and [custom_lint 0.8.1](https://pub.dev/packages/custom_lint/versions/0.8.1) require `analyzer: ^8.0.0`. The builder also requires `custom_lint_core: 0.8.1` exactly. Although [custom_lint_core 0.8.2](https://pub.dev/packages/custom_lint_core/versions/0.8.2) supports analyzer 9, it cannot be substituted under that builder contract. The upstream manifests are available from the pub.dev [builder metadata](https://pub.dev/api/packages/custom_lint_builder/versions/0.8.1) and [core metadata](https://pub.dev/api/packages/custom_lint_core/versions/0.8.2). Keep `analyzer: ">=8.0.0 <9.0.0"` with `custom_lint_builder: ^0.8.1` until the builder and host release a compatible upgrade. An isolated resolution probe requiring analyzer 9 fails with that exact dependency conflict. Widening the direct analyzer constraint would neither upgrade the transitive analyzer nor prove API compatibility; overriding it would violate the lint protocol. This constraint costs the lint package ten dependency-freshness points, so its accepted current score is 150/160. Only that exact package and pair of constraints receive the exception. An upgrade must remove or revise the exception after resolving normally, running lint-rule and fix tests, checking the validator's rule execution, and running the full workspace custom-lint gate. Do not trade working editor diagnostics for a nominal dependency score. Dry-run publishing is separate from release authorization. It does not upload anything, and an uncommitted working tree produces an expected warning. Choose the release version and review the changelog before an actual publication. # ADR: build steps, speaker notes, and the digest Status: accepted, 2026-07-19. This page fixes the `.fluvie` shape for build steps and speaker notes. It also pins which keys count into the render digest. The presenter and the editor both build on these shapes. The format version and its migration hook absorb any later change. ## The decision in one look ```json { "duration": "8s", "children": [ { "id": "el-title", "type": "Text", "text": "Incident review" }, { "id": "el-b1", "type": "Text", "text": "3am page" }, { "id": "el-b2", "type": "Text", "text": "one line fix" } ], "steps": [ { "elements": ["el-b1"] }, { "elements": ["el-b2"], "notes": { "text": "Land the punchline." } } ], "notes": { "text": "Open with the outage story.", "highlights": ["3am page", "one line fix"] } } ``` ## Steps are scene-level ordered groups of element ids A scene may carry a `steps` list. Each entry is an object with two keys: - `elements` (required): the ids of the scene children this step reveals. Every id must name a child of the same scene. An id appears in at most one step. Children not named in any step are step 0 and show on entry. - `notes` (optional): the per-step notes override. The shape is below. The list order is the step order. There is no `order` key. The widget model needs `Stop.order` because document position is its only other signal. A JSON list already is an explicit order, and a second ordering mechanism would only add ways to disagree. Steps reference ids instead of nesting the children. The editor addresses elements by id for transforms, selection, and layers. Steps are presentation metadata over those same children, not a structural container. Nesting would force every canvas tool to look through a wrapper. Ids keep the children list flat, and the id groups are exactly what the presenter needs to build its `Stop` wrappers. ## Notes are a scene default plus per-step overrides A notes object has two optional keys, matching `SpeakerNotes`: - `text`: the full prose for the speaker. - `highlights`: the glanceable bullet list. The scene-level `notes` object is the slide default. A step's `notes` follows the presenter's merge rule: its `text` replaces the scene text while that step is active, and its `highlights` append to the scene's. ## The engine ignores both fluvie stores `steps` and `notes`, validates them, and round-trips them. It never reads them while rendering. A rendered video plays straight through. Only `package:fluvie_presenter` interprets them: `deckFromSpec` wraps each step's built children in a `Stop` and injects `SpeakerNotes`. Only the editor authors them. fluvie never imports the presenter. ## The digest counts everything except `editor` `VideoSpec.digest()` hashes the canonical JSON with exactly one key removed: the top-level `editor` block. Everything else counts, including `steps` and `notes`. The line is drawn by audience, not by pixels. Steps and notes change what an audience can be shown: a presented deck pauses differently, and a speaker says different things. Two specs that differ there are different documents, so they must not share a digest. The `editor` block is authoring convenience only (viewport, panel state, names). It can never change any output, so it must never invalidate a frame cache. Two consequences are worth naming: - A frame cache keyed by the digest re-renders when steps or notes change, even though the pixels did not. That is the accepted cost. One conservative digest beats a second digest flavor, and step edits are rare next to canvas edits, which change pixels anyway. - Anything added to the spec later counts into the digest by default. Exclusion is the exception, and it needs this page amended first. ## Validation splits by what each layer can know `spec_validation` checks shape and references per scene: `steps` is a list of objects, every id in `elements` names a child of that scene, no id repeats across steps, and `notes` carries only `text` (a string) and `highlights` (a list of strings). The presenter's `validateStepPlan` adds the compile-level checks the pure validator cannot know: cross-element or beat triggers on an element inside a step, and a timeline that does not resolve on its own. The editor calls it live at edit time. ## Where to next - [Authoring with specs](../guides/authoring-with-specs.md) - [Timing and triggers](../guides/timing-and-triggers.md) # Testing guide Every change starts with a failing test. This page explains the suites, how to run them, and the fakes and goldens that keep them honest. Run the fast suite before you commit: ```sh melos run test ``` That runs the pure-Dart and Flutter unit tests across the workspace. It excludes goldens and the tagged integration suites, so it is quick. The rest of this page covers the slower suites and how each kind of test is written. ## Test first Write the test, watch it fail for the right reason, then make it pass. No production `.dart` file lands before its test exists. Red, green, refactor. ## The kinds of test - **Unit tests** cover everything pure: `core`, `timing`, services, and math. They are the bulk. No real network and no real filesystem. - **Golden tests** assert pixels through Alchemist. They carry the `golden` tag. - **Integration tests** need a real resource and carry a tag for it: `ffmpeg`, `snapshot`, `wasm`, or `render`. A plain `melos run test` excludes goldens and the tagged suites. CI gates the tags per platform. ## Unit tests with mocktail and Riverpod Mock a collaborator with mocktail and inject it through a Riverpod override. A service is an abstract contract plus an implementation, wired by a provider, so a test overrides the provider with a fake: ```dart final container = ProviderContainer( overrides: [frameCaptureServiceProvider.overrideWithValue(fakeCapture)], ); ``` Stub the fake's methods with `when(() => fake.method(any())).thenAnswer(...)`. Register a fallback value for any non-primitive argument matched with `any()`: `registerFallbackValue(Directory('/tmp'))`. No test touches the live network or a real binary; media flows through an injected fake client or local fixtures. ## Golden tests with Alchemist Goldens render at a fixed fps, a fixed seed, and DPR 1.0, so a frame is reproducible. Seeded effects (`noise(seed)` / `random(seed)`) keep a golden stable from run to run, so a diff means the output actually changed. Tag the file `@Tags(['golden'])` and assert with `goldenTest`. There are two flavors: - **CI goldens** use the Ahem font and run on every platform. - **Platform goldens** use real bundled fonts and run on the Linux baseline only, because font rasterization differs across platforms. Run them and generate baselines: ```sh melos run test:goldens # run the goldens flutter test --update-goldens --tags golden # regenerate baselines ``` Always review the PNG before you commit it. A golden diff is a deliberate decision, not a rubber stamp. ## Integration suites Each integration suite names what it needs in its tag, so CI can gate it where the resource exists: - `ffmpeg` needs the encoder on PATH (the 12-lesson render smoke, encode tests). - `snapshot` needs a live headless renderer (the deferred Mermaid/WebView/Html transport). - `render` and `wasm` need a full capture path or a web runtime. These are not part of the fast gate. Run a tagged suite directly with `flutter test --tags ffmpeg`. ## The web demo smoke test The demo (`examples/gallery/`) has a headless-Chrome smoke test: it builds the web app, serves it, and checks that the Flutter app boots, lays out, and logs no runtime error. It guards the in-browser demo and runs in CI (the `web_smoke` job). ```sh melos run web:smoke # build, serve, and smoke-test the demo web app ``` It needs node, python3, and a Chrome binary (set `CHROME`). Pass `SKIP_BUILD=1` to reuse an existing build. ## Coverage The gate enforces 97% line coverage on every package under `packages/`. Run it before you commit: ```sh melos run coverage:check ``` Test behavior; ignore only lines that have none, with a reason on the same line. The full policy is in [Coverage and the ignore policy](coverage.md). ## Doc snippets are tested too Documentation Dart fences come from compiled sources under `examples/gallery/lib/`. Each snippet file has a small test that builds it, so a doc never ships dead code. Check the fences are in sync and free of naked Dart blocks: ```sh melos run docs:snippets:check # fences match their source melos run docs:lint # every dart fence has a code-excerpt directive ``` ## Where to next - [Coverage and the ignore policy](coverage.md): the 97% floor and when an ignore is allowed. - [Contributing overview](overview.md): the workflow and the quality gate. # Untrusted render security The Playground and the `fluvie_server` render endpoints compile and run **untrusted user code and specs**. This page records the threat model, the result of a four-round red-team, and what remains to do. Read it before you change anything under `fluvie_server/lib/src/api/render/` or the capture harness. ## Verdict **The untrusted-render boundary is not sound, and it cannot be made sound by patching individual seams.** A submitted `Video build()` snippet is JIT-run with full VM privileges inside `flutter test`. Its only containment is an import allowlist (`code_import_policy.dart`) plus a per-loader `FLUVIE_BLOCK_FILE_SOURCES` flag. That model is the wrong layer: the allowed `package:flutter` surface reaches the filesystem and network on its own, without any `dart:io` import. **Do not expose the Playground to untrusted input until the render runs under OS-level sandboxing.** The in-process checks below are defense in depth, not a boundary. ## Threat model - Trusted: a `KeyRenderRequest` (a bundled, developer-authored lesson). - Untrusted: `Code`, `Spec`, `Prompt`, and `Edit` requests, and the `/v1/validate` + MCP `validate_code` paths. - The attacker controls the Dart snippet or the spec JSON. The snippet must be a zero-arg synchronous top-level `Video build()`; it may import only allowlisted libraries. That is not a real restriction (see below). ## Confirmed exploits (executed against the live code) The red-team wrote proofs and ran them. These are facts, not theory. **Reachable with only allowlisted `package:flutter` + `package:fluvie/fluvie.dart` imports:** - `rootBundle.loadString('/etc/passwd')` (flutter/services) returns the file. Under `flutter test` the `flutter/assets` channel resolves the key as a raw path, with absolute paths and `../` traversal. Arbitrary host-file read. - `NetworkImage(url)` inside `compute()` (flutter/foundation + flutter/painting) performs an outbound request. `compute` runs in a fresh isolate where flutter_test's mock `HttpOverrides` does not apply, so the request leaves the host. SSRF and exfiltration. - A `fluvie` `Image.file(path)` wrapped in a plain `flutter.Builder` (invisible to the media collect walk) under a nested `RenderModeContext(mode: preview)` reaches the paint-time preview fallback, a raw `dart:io` file read that the loader-level `FLUVIE_BLOCK_FILE_SOURCES` never sees. **Availability / integrity:** - 64-bit integer overflow defeats the canvas bounds: `width = height = 2^32` makes `width * height` wrap to 0 and pass. Fixed (per-axis check). - `renderPosterPng` is a second capture entrypoint that never calls the canvas guard and drives `boundary.toImage()` straight from the untrusted `baseSpec`. - The parser-DoS pre-scan (`_nestsPastLimit`) counts only bracket depth, so a bracket-free deep AST (a long cascade `o..a..a...`, an elseless collection-`if`) under the size cap still burns seconds of synchronous CPU in `parseString`. - `/v1/validate` and MCP `validate_code` run the analyzer on untrusted input with no complexity guard at all, on the main server isolate (~38 s measured for a ~60 KB payload). Code and spec renders are not rate-limited. Earlier rounds also found: a bypassable regex allowlist (now AST-based), and the allowlist trusting all of `package:fluvie/` including the private `src/` tree, which exposed `IoProcessRunner.run` (RCE) and `readFileBytes` (file read). Both fixed. ## Root cause Containment is inherited from `flutter_test`'s incidental mocking or from string-level import filtering, never owned by Fluvie at the IO and allocation layer. String filtering cannot enumerate every capability of the allowed framework surface, and `flutter_test`'s mocks do not survive `Isolate.run`. ## Required remediation (in priority order) 1. **Run every untrusted render and every untrusted analysis in an OS sandbox**: a locked-down process or container with no filesystem access beyond a scratch dir, no network, dropped privileges (seccomp / gVisor / a container with `--network none` and a read-only rootfs). This is the actual boundary; the import allowlist becomes one layer inside it. 2. **Parse untrusted code off the request isolate with a hard wall-clock budget** (import scan and `/v1/validate`), so any pathological input is bounded regardless of structure. Rate-limit code and spec renders like prompt/edit. 3. If any in-process mitigation must stand before (1): install process-wide `HttpOverrides` and an asset-channel handler that hard-fail under the untrusted define, latch capture mode from the root so a nested `RenderModeContext` cannot downgrade it, and narrow the flutter allowlist. Treat each as partial. ## What is hardened in-process today Defense in depth only, all under `FLUVIE_BLOCK_FILE_SOURCES` / the render path: - Import allowlist is AST-based and grants only the public `fluvie.dart` barrel, flutter non-`src/` libraries, `dart:math`, and `dart:ui` (`code_import_policy.dart`). - `FileSource` is blocked at every media loader on the untrusted path. - Canvas and frame-count bounds are overflow-safe and per-axis, enforced at the capture chokepoint (`render_harness.dart` `assertRenderWithinBounds`). - The in-process MCP render path (`LocalRenderGateway`) enqueues straight to the render queue, so it leans on that capture chokepoint for its size bound instead of the HTTP handler's early reject, and like code and spec renders it is not rate-limited. - The edit poster (`renderPosterPng`) grounds an untrusted base spec for the model; on the blocked path it rejects `FileSource` and network sources before they reach the preview fallback, so a base spec cannot read a host file into the grounding image. - A linear nesting pre-scan rejects bracket bombs before the parse (partial: see the cascade/collection-`if` bypass above). ## Where to next - [Testing policy](testing.md) - [Coverage](coverage.md) # ADR: the video-mode document shape Status: accepted, 2026-07-23. This page fixes the `.fluvie` shape for audio tracks, element time windows, and imported media. Video mode edits the same document as slides mode; these three shapes are what it adds. The format version and its migration hook absorb any later change. ## The decision in one look ```json { "fps": 30, "audio": [ { "kind": "music", "source": { "kind": "file", "value": "/home/ada/music/bed.mp3" }, "volume": 0.8, "fadeIn": "1s", "fadeOut": "2s", "loop": true } ], "scenes": [ { "duration": "12s", "audio": [ { "kind": "sfx", "source": { "kind": "asset", "value": "audio/whoosh.mp3" }, "at": "sceneStart" } ], "children": [ { "id": "el-broll", "type": "Clip", "source": { "kind": "bundle", "value": "media/b-roll.mp4" }, "show": { "from": "2s", "to": "6.5s" } } ] } ] } ``` ## Audio is a track list, mirrored from the constructors A video may carry a top-level `audio` list, and each scene an `audio` list of its own. Each entry is one track: - `kind` (required): `music` or `sfx`, selecting `Audio.music` or `Audio.sfx`. - `source` (required): the same `{kind, value}` object images and clips use. - `volume`: linear gain, `1` plays the file as authored. - Music only: `fadeIn` and `fadeOut` (times), `loop` (a bool), `trim` (a `{from, to}` object of times, the same shape as a clip's trim), and `track` (an anchor id naming the beat grid that `beat` triggers resolve against). - Sfx only: `at`, a trigger in the same vocabulary animations use. Missing means the owner's start. The field list is the constructors' field list, nothing more. `track` is in even though a timeline lane never edits it, because the constructor carries it and a beat trigger cannot serialize without it. Validation rejects a music-only key on an sfx track and `at` on a music track: the constructors force exactly those fields, and a silently dropped key would lie. Placement in time comes from the owner, exactly as in the runtime. A video-level track spans the video; a scene-level track starts with its scene. There is no music `at` because `Audio.music` has none: to start a bed later, put it on a later scene or trim it. Unlike steps and notes, the engine consumes audio. The spec build hands the video-level list to `Video.audio` and each scene's list to `Scene.audio`, and the existing collector reads them from there in declaration order, video first, then scenes. The per-track filter nodes and the `amix` graph do not change. The digest counts audio, per the default rule: everything except `editor` counts. ## `show` is a first-class element key The runtime's `show({from, to})` is not an animation. It desugars to `animate([], window: from.to(to))`: a `TimeRange` on the `.animate(...)` call that overrides the element's alive window. The serialized animate entry has three forms (preset, keyframes, raw from/to), and none carries a window, because the window is an argument of the call and the `animate` list has no slot for call-level arguments. A `fadeIn` plus `fadeOut` pair is not the same thing either: the element stays mounted for the whole scene and its triggers still resolve against the whole-scene window. Reuse would not produce the same resolved spans, so `show` becomes a reserved element key: - `from`: when the element becomes alive; missing means the scene start. - `to`: when it stops; missing means the scene end. An empty `show` object is invalid. `show()` with no bounds changes nothing in the runtime, so save canonicalization removes the key instead, following the no-residue rule the notes editor set. The builder applies `show` as the `window` argument of the one `.animate(...)` call it already makes for the element. One `MotionTarget`, so the element's animations resolve inside the window: a clip that enters at `2s` plays its `fadeIn` at `2s`. The `.show()` sugar is the no-animations special case of exactly this call. The law for tools: the timeline's lane edits write exactly this form. Dragging a clip along its lane rewrites `from` and `to`. Dragging an edge rewrites one of them. Resetting the lane removes the key. ## Media survives save and reload by kind ### Desktop keeps paths The importer already writes `{ "kind": "file", "value": "/abs/path" }`, and that stays the saved form. A save option rewrites file values that sit under the document's directory to document-relative values, for decks that travel with their media. The loader resolves a relative `file` value against the document's directory before the spec reaches the engine, so the engine keeps its plain path semantics. ### Web bytes ride a bundle Bytes cannot live in the JSON: the media codec rejects memory sources by design, and that stays. On the web an import becomes an in-memory source with an object URL for live preview. Both are session state, not document state. Save decides by content. A document that references no session media saves as plain JSON, exactly as today. A document that does saves as a bundle: a zip holding `deck.fluvie.json` plus a `media/` folder with the imported files. Inside a bundle, a media or audio source uses a fourth kind: ```json { "kind": "bundle", "value": "media/b-roll.mp4" } ``` The value is bundle-relative, so the digest is stable across machines. A temp unpack path in the JSON would re-key every frame cache per session. The schema and validator learn the `bundle` kind because it is part of the document format, but building a spec that still contains one throws, naming the missing bundle context: the loader resolves each bundle source before build, into memory sources on the web and into files under a sandboxed temp directory on desktop, so the engine never sees the kind. Saving plain JSON while session media exists warns, suppressibly, that the media will not travel. Nothing is silently dropped or rewritten; the warning is the whole intervention, per the additive-optional law. Data URIs are rejected. Base64 grows every asset by a third inside a document the editor holds, diffs, and autosaves as text. The digest hashes the canonical JSON, so embedded megabytes would be rehashed on every dirty check. And no honest line separates a small asset from a large one, so the cliff would surface in production instead of review. ### One extension, sniffed Both forms are `.fluvie`. A loader sniffs the leading bytes: `PK` (the zip magic) means bundle, anything else parses as JSON. One extension keeps every existing association, recent-files list, and docs page true. A second extension would fork the format's identity to answer a question the first two bytes already answer. ## The security boundary holds - `FileSource` stays blocked at every media loader on untrusted render paths. Nothing here loosens that: a bundle never uses a `file` source for its own media, and imported web bytes travel as memory sources, never paths. - Bundle unpacking is sandboxed. Entries are read only from `media/` plus the one deck JSON, entry names must be relative with no `..` segments (the zip-slip check), and per-entry plus total sizes are bounded before inflation. - The web media store bounds the total bytes it holds and refuses an import past the budget with a visible error. - The network allowlist is untouched; a bundle adds no fetch. - Memory sources still have no plain-JSON form, so an untrusted spec cannot smuggle bytes. A `bundle` source outside a real bundle fails at build. ## Consequences and validation - `AudioSource` has no memory variant today; the web path needs `AudioSource.memory` so imported audio reaches the mix without a path. That lands with the video-mode epics, alongside the audio serialization. - Validation splits as before. The pure validator checks shape: track kinds, the source object, music/sfx key ownership, times and triggers that parse, a `track` id that resolves through the anchor table, and a `show` with at least one bound. - The digest names sources; it does not hash media bytes. Replacing a file's contents under an unchanged name does not move the digest, which matches the advisory nature of the media cache. - Opening a bundle and then saving plain JSON warns the same way session media does: the document would reference media the JSON cannot carry. ## Where to next - [ADR: steps, notes, digest](steps-notes-digest.md) - [Authoring with specs](../guides/authoring-with-specs.md) - [Untrusted render security](untrusted-render-security.md) # Cookbook You know what you want. This page points you straight at it. Each recipe is one task with the shortest path to a working result. For the full story behind a recipe, follow its guide link. If you would rather learn in order, start with [your first video](getting-started/your-first-video.md) and the runnable lessons in the example app. ## Text and motion - **Fade or slide a title in.** See [Animating elements](guides/animating-elements.md) for the one motion list and the preset menu. - **Type text out like a terminal.** Use `Typewriter`; see [Text and typography](guides/text-and-typography.md). - **Count a number up.** Use `Counter`; see [Charts and data](guides/charts-and-data.md). - **Stagger a list of items.** Use `Stagger`; see [Animating elements](guides/animating-elements.md). ## Scenes and timing - **Play scenes one after another.** See [Scenes and transitions](guides/scenes-and-transitions.md). - **Wipe or fade between scenes.** Use `Transition`; see [Scenes and transitions](guides/scenes-and-transitions.md). - **Start an animation when another finishes.** Use a `Trigger` and an `Anchor`; see [Timing and triggers](guides/timing-and-triggers.md). - **Carry one element across a scene cut.** Use `SharedElement`; see [Scenes and transitions](guides/scenes-and-transitions.md). ## Media - **Show a photo or a logo.** Use `Image`; see [Images and video clips](guides/images-and-video-clips.md). - **Embed an existing video clip.** Use `Clip`; see [Images and video clips](guides/images-and-video-clips.md). - **Pan and zoom across the frame.** Use `Camera`; see [Scenes and transitions](guides/scenes-and-transitions.md). ## Data and developer scenes - **Reveal a bar, line, or pie chart.** See [Charts and data](guides/charts-and-data.md). - **Show typed, highlighted code.** Use `Code` and `CodeReveal`; see [Code and terminal videos](guides/code-and-terminal-videos.md). - **Animate a code diff.** See [Code and terminal videos](guides/code-and-terminal-videos.md). - **Render a Mermaid diagram or a web page.** See [Diagrams and web views](guides/diagrams-and-webviews.md). ## Audio and captions - **Add a music bed or a sound effect.** Use `Audio`; see [Audio and captions](guides/audio-and-captions.md). - **React to the beat.** Use beat detection; see [Audio and captions](guides/audio-and-captions.md). - **Burn in subtitles from an SRT or VTT file.** Use `Captions`; see [Audio and captions](guides/audio-and-captions.md). ## Look and feel - **Brand a video from one palette.** Use `FluvieTheme`; see [Theming](advanced/theming.md). - **Add grain, particles, or a shader.** See [Shaders and effects](advanced/shaders-and-effects.md). - **Reuse one design across data rows.** Use a template; see [Templates](advanced/templates.md). ## Export - **Render to MP4, GIF, an image sequence, or transparent WebM.** See [Exporting your video](guides/exporting-your-video.md). - **Export the same video as reels, square, and landscape.** Use `Adaptive`; see [Multi-aspect](advanced/multi-aspect.md). - **Write a poster frame.** Pass `--poster`; see [Exporting your video](guides/exporting-your-video.md). - **Render in CI or on a server.** See [Rendering on a server](guides/rendering-on-a-server.md). ## Let AI do it - **Author a whole video from a prompt.** See [AI and MCP](guides/ai-and-mcp.md). - **Refine a video by describing the change.** See [AI and MCP](guides/ai-and-mcp.md). ## Where to next - [Animating elements](guides/animating-elements.md): the motion model in full. - [Cheatsheet](reference/cheatsheet.md): the whole public surface on one page. - [FAQ](reference/faq.md): the questions newcomers ask first. # Audio editing The Audio workspace groups lanes, meter estimates, per-track volume automation, and ducking. All edits use the document's command history, so undo restores the complete previous envelope. Lane mute and gain affect export. **Solo monitor** is session state and never enters a saved document or an exported mix. ## Automation Audio uses the same `values`, `positions` and `easings` grammar as effects. Positions are measured from the audible start of a track, or from a clip's own window. The gain multiplier is clamped to 0–1 and multiplies the authored track volume and lane gain. A single constant is represented by a number. ```json { "kind": "music", "source": {"kind": "asset", "value": "audio/bed.wav"}, "automation": { "volume": { "values": [1.0, 0.25, 0.25, 1.0], "positions": ["0f", "30f", "90f", "120f"] } } } ``` The same `automation` property on a Clip controls its embedded audio. In Dart: ```dart final music = Audio.music( 'audio/bed.wav', automation: AudioAutomation( values: const [1, 0.25, 1], positions: [0.frames, 1.seconds, 4.seconds], easings: const [Ease.smooth, Ease.linear], ), ); ``` Add a volume stop at the playhead, then edit its gain, frame and outgoing easing in the Audio inspector. Times stay ordered. Removing the last stop clears the envelope; changing a value preserves the other stops and their easing. FFmpeg receives one typed, deterministic `volume` expression with `eval=frame`. No authored text is inserted into the graph. Linear segments remain linear; nonlinear easings resolve to composition-frame samples and the same samples are handed to custom and mobile encoders. Empty automation preserves the previous static filter string exactly. Mix order always remains document order, regardless of lane order. ## Lanes and meters Gain is edited in dB and saved as linear amplitude (`0 dB = 1`, approximately `-6.02 dB = 0.5`). Mute removes assigned tracks from the render mix. Scene audio starts and ends with its scene, including overlapping transitions. Automation, trim, loops, rate and fades are reflected in the meter calculation. Meters use cached decoded waveform envelopes, so they work without a live audio device. Individual peak and RMS values derive from source buckets. Combined peak is a conservative ceiling and combined RMS assumes uncorrelated sources: waveform summaries do not retain sample phase. The workspace labels them as estimates and indicates values above full scale as `CLIP`. ## Ducking Select a trigger lane and target lane. Set attenuation, attack, hold and release, then choose **Apply ducking**. Trigger presence writes ordinary automation onto each target track as one undo step. Overlapping trigger windows do not allow the target to rise between them. Ducking replaces the target's prior volume automation; undo restores it exactly. Export uses the written envelope, without any special runtime ducking process. ## Verification Maintained tests cover absent-envelope graph identity, single/multiple stops, ordering validation, clamping, shared easing resolution, round-trip digest, scene timing, lane mute/gain/order, monitoring-only solo, meter estimates, ducking overlap/shape/undo, and an actual FFmpeg PCM encode whose measured amplitude falls to the authored duck level and recovers afterward. Android and iOS use the same resolved sample list; native device validation requires their respective SDKs and devices. ## Placement and program audition Both music and sound effects accept `at`, relative to their scene or the video. A placed music track retains its source trim, looping and fades. A trimmed bed placed at 3 seconds with a 2–5 second source trim plays from 3 to 6 seconds; its fade-out ends at 6 seconds, subject to its owner's end. Embedded clip audio appears alongside declared tracks in the Audio workspace. Its lane gain, automation and ducking use the actual built clip window, including transition crossfades. Probed source metadata resolves trimmed clips at their source frame rate. An unprobed trimmed clip is marked unavailable for audition until metadata is loaded, rather than played from an invented source range. Program audition mixes bounded chunks of cached PCM. Solo is applied only to those chunks and meter estimates. Timeline waveforms cover absolute composition time, with silence before placement and after each audible window; they reflect trim, playback rate, speed ramps and automation. Waveform columns are bounded samples of cached summaries, rather than an exact recording of the final mix. Speed ramps carry an integrated output-to-source clock to every encoder. FFmpeg uses persistent `atempo` stages with source-time commands, followed by volume, fades and delay. Its pitch-preserving processing has normal audio-block timing precision. The pure audition mixer and Android use sample resampling, so pitch changes with playback speed; iOS scales source segments through AVFoundation. Native-device audio quality and platform codec availability need verification on the target device. Program and Source Listen audition use a mono downmix; export channels remain independent. Decoded PCM is cached in a 128 MiB LRU, source waveforms use 2048 buckets, and audition chunks are limited to 30 seconds. Desktop audition requires ffmpeg and ffplay. Browser audition uses Web Audio with imported bytes or CORS-enabled sources. Load/playback errors remain visible with a retry action. ## Cutting and removing music An explicitly placed, non-looping music track with exact source trim supports razor, lift, extract and ripple edits. Razor keeps both source ranges adjacent; extract closes the removed time while preserving each remaining source range. Scene-owned tracks retain their scene-relative clock. Curved automation and fades are cropped into ordinary volume points, preserving gain at every composition frame instead of restarting the fade on each new piece. Embedded clip audio receives the same envelope slicing when its picture is razored. Tracks with trigger placement, named beat timelines, looping, or unknown trim report the required change before an exact structural edit. Locked lanes refuse the whole edit. Each structural action, including edits to multiple audio and picture items, is one undoable command. # The canvas The canvas is where you point at things. Everything it does writes real geometry into the document: fractional transforms that render identically in the editor, the presenter, and the video file. ## Tools One key each, Figma's letters: | Key | Tool | | --- | --- | | `V` | Select, move, and transform | | `H` | Hand: drag to pan the viewport | | `T` | Text: click to place, type inline | | `R` | Rectangle | | `O` | Ellipse | | `L` | Line | | `A` | Arrow | | `M` | Media: insert an image or video file | A drawing tool returns to select after each placement. Escape returns to select from anywhere. Double-click a text element to edit it in place. ## Selection and the gizmo Click selects. Drag on empty ground sweeps a marquee; hold Shift to add to the selection. A selected element shows the transform gizmo: drag the body to move, a handle to resize, the top handle to rotate. Shift locks the aspect ratio, Alt resizes from the center, and Escape cancels the drag without losing the selection. A multi-selection moves as one unit; handles stay single-selection. Arrow keys nudge by one canvas pixel, Shift+arrows by ten. A run of nudges undoes as one step. ## Snapping, rulers, and guides While you drag, the canvas snaps to guides, the slide edges and center, other elements' edges and centers, and equal-spacing gaps. Snap lines pulse as they catch. Hold Ctrl to bypass snapping for one drag. Toggle the rulers from the toolbar. Drag off a ruler to place a guide, drag a guide to move it, and drop it back on the ruler to remove it. Guides save with the slide and never affect rendering. ## Groups and blocks Select two or more elements and press `Ctrl+G` to group them. A group moves, hides, and animates as one unit. Double-click enters the group to edit its children; Escape leaves. `Ctrl+Shift+G` dissolves it, and the children keep their exact places, because grouping only rewrites frames of reference, never pixels. The Layers list moves elements across group boundaries too: expand a group and drag a row into its run to move the element inside, or drag a child to a top-level slot to promote it. Nothing moves on screen either way. With a group entered, paste and duplicate land inside it — except a pasted group itself, which lands at the slide's top level beside the entered group. Groups never nest by an editor gesture: move, drag, and paste hold the same one rule. A **block** is a group with a layout brain. The element menu's Block submenu turns a selection into a row, column, grid, list, two-column split, or title-with-body block. The block arranges its children and re-balances when you add, remove, resize, or reorder them; the inspector's Block section edits spacing, alignment, and the other knobs per kind. Blocks nest. Drag a child out of its block's box to release it back to free placement. The arranged positions are ordinary transforms in the document, so a deck full of blocks renders everywhere, block-aware or not. ## Arrange Z-order rides the brackets: `]` brings forward, `[` sends backward, with Ctrl for all the way. Lock (`Ctrl+Shift+L`) keeps an element out of the way of clicks; Hide (`Ctrl+Shift+H`) writes the spec's `visible: false`, so a hidden element is honestly absent from the render. Align and distribute live in the element menu under Align. ## Menus and the palette Right-click anything for its menu: element commands over an element; undo, redo, paste, and select-all over empty canvas; slide commands on a slide-strip tile. `Ctrl+K` opens the command palette with every command searchable, recents on top. Menus, palette, and keyboard all fire the same registry entry, so the shortcut a menu prints is exactly the key that works. ## Where to next - [The timeline](editor-timeline.md): when things happen, under the canvas. - [Shortcuts](editor-shortcuts.md): every binding on one page. - [Free placement](../guides/free-placement.md): the `Placed` element the canvas writes, from the code side. # Colour Open the **Colour** workspace and select a clip or an element. Colour effects use the same effect stack in the preview, saved document, generated Dart and export. The original media stays untouched. ## Start with a Look Choose **Social pop**, **Clear speaker**, **Studio clean** or **Warm cinema**. Set **Look intensity** first; 0.6 gives a useful starting point. Applying a Look replaces the selected elements' colour treatment in one undo step, preserving other effects. The applied intensity remains editable on the grade or LUT. **Copy grade** copies only grade, curves and LUT effects using the effects clipboard format. **Paste grade** replaces the colour treatment of every selected element. **Paste to lane** applies it to clips on the selected element's declared lane. Clipboard payloads travel between documents and app windows. ## Correct colour **Add correction** supplies exposure, contrast, saturation, temperature and tint. White balance applies first, then exposure, contrast and saturation. The wheel adjusts temperature and tint together; both also have keyboard-editable numeric fields. A wheel drag commits once on release. Intensity mixes the resulting colour matrix with the identity matrix; zero is an exact no-op. Every numeric field accepts arithmetic and has a diamond to turn it into a keyframed value. Effect rows in the timeline expose its stops. Keyframed white balance values are edited through their numeric/timeline controls rather than the two-channel wheel. ## Shape a curve **Add curves** opens master, red, green and blue channels. Select a channel and a point, drag it on the graph, or edit **Input** and **Output** numerically. **Add point** divides the widest interval without changing the curve's sampled value; **Remove point** keeps at least two points. **Reset curve** restores the diagonal. The graph and renderer share the monotone cubic evaluator, with no overshoot between monotone points. Every point stays inside the unit square and input positions stay strictly increasing. ## Import a LUT **Import .cube LUT** validates and embeds the file text in the document. It therefore survives save/reopen, clipboard operations and generated Dart without an external file dependency. Library authors can still use the relative `asset` form. An invalid import shows its error and leaves the document unchanged. The supported contract is a 3D `.cube` table with 2–64 samples per axis and at most 4 MiB of UTF-8 text. Input and output are encoded, non-linear sRGB in the unit cube. Only `DOMAIN_MIN 0 0 0` and `DOMAIN_MAX 1 1 1` are accepted. Fluvie applies no extra transfer function. Values are sampled with trilinear filtering; LUT intensity zero returns the original child exactly. Shader programs and lookup images warm before the graded composition mounts. The canvas displays preparation, failure and retry states instead of silently pretending a failed LUT applied. Export uses the same preparation path. ## Read scopes The histogram shows RGB distributions. The waveform shows luminance by horizontal position. The vectorscope shows Cb/Cr chroma density, with neutral colours at its centre. Transparent pixels are excluded. Scopes read the existing settled preview stage before editor handles, at up to 320 pixels across. Requests are throttled to ten per second and cached by document render digest and frame; fast scrubbing coalesces to the latest settled frame. Scopes are read-only and never change a document digest or appear in export. They describe preview pixels, so a reduced-resolution preview can differ slightly from full-resolution delivery. GPU golden baselines are pinned to Linux; software rasterizers and encoders need not produce identical bytes across machines. ## Dart authoring ```dart return child.effects([ Effect.grade(exposure: 0.2, contrast: 1.08, intensity: 0.6), Effect.curves(master: ToneCurve.fromPoints(const [(0, 0), (0.5, 0.55), (1, 1)])), ]); ``` See [Effects](editor-effects.md) for stack order, enabling and keyframe controls. # Continuity across slides A slide is a chapter marker, not a wall. Three things cross one: an overlay runs the whole video as a single element, a shared chain morphs a hero through every cut it touches, and a boundary is a hairline you can drag. ## Overlays: one element for the whole video An overlay lives outside every slide. It is mounted once, never re-parented at a boundary, and its window is measured against the whole video rather than a slide — so it holds through every cut and every blend without blinking. Use one for anything that belongs to the video rather than to a moment: a logo, a lower third that runs a whole section, a watermark, a progress bar. - The timeline draws an overlay as **one bar spanning its window**, crossing boundaries with no seam. There is no slide to clamp it to. - Adding one never lengthens the video and never moves a boundary. - Overlays paint above every slide, in declaration order, and below captions. - An overlay cannot be a shared hero: it already runs the whole video, so there is no boundary for it to morph across. An overlay is drawn on one slide's canvas — its **home** — so you can place it, size it and style it the way you place anything else. The home is editorial: it decides where you edit the overlay, never when it plays, and it never moves the render digest. Deleting its home slide re-homes it rather than deleting it, because it belongs to the video and not to that slide. **Make global** turns a slide element into an overlay and **Make slide-local** turns one back, each in one undo step. Neither moves the bar a pixel: a slide-relative window and an absolute one are two ways of naming the same frames. Coming back into a slide, a window that reaches past that slide is clamped to it — there is no honest way for a slide-local element to outlive its slide. ## Shared chains: a hero that morphs through the cuts Two elements naming the same `shared` id in neighbouring slides are one logical thing: during the blend, the editor draws it travelling from the first rect to the second. That is a **morph** — two elements made to look like one. A chain is any contiguous run of slides, not just a pair. A hero declared in slides 1, 2 and 3 morphs through both cuts, each boundary blending its own two ends. What a chain may not be: - **One slide.** A hero with nothing to morph to. - **A run with a gap.** The hero would vanish for a slide and come back, which is two morphs pretending to be one. Both are refused with the anchor named, rather than rendering something nobody meant. **Morph or overlay?** A morph is the right answer when the thing genuinely changes across the cut: a title that starts large and centred and ends small in a corner. An overlay is the right answer when it does not change at all. If you find yourself giving both ends identical geometry, you wanted an overlay. The timeline shows a chain as one bar. Its first and last edges span the member scenes; dragging an edge applies the same local-frame timing change to every member and clamps at each scene's bounds. A chain keeps its scene memberships. Razor divides the logical bar into left and right chains, including a cut exactly on a scene boundary. Lift removes the selected chain or marked range; Extract and Ripple delete close its gaps within each member scene. Each operation is one undo step and retains every member’s authored geometry. Inspector content edits propagate the changed properties through the chain in one undo step. Unchanged properties keep their authored values. Geometry, anchors and identity remain local, so moving the title in one scene retains the other scenes' poses. ## The hairline and the bar edge Two lines on the timeline, two different gestures: | Line | What it is | Dragging it | | --- | --- | --- | | A **hairline** on the ruler | A slide boundary | Retimes the slide before it | | A **bar edge** on a lane | A clip's in or out point | Trims that clip | They look different because they mean different things. A slide's length is the master clock: retiming one moves every slide after it and changes the video's length. Trimming a clip changes only that clip. The same retime is a number in the inspector, under **Length**: frames and seconds, one gesture apart from the drag, writing exactly the same command. Two things a retime is honest about: - A slide too short to hold its own transitions is refused, in the engine's own words, rather than written into a document that would fail to render. - Windows that no longer fit are clamped into the shorter slide, and the note names them. A window that starts past the new end loses its timing rather than being written inverted: the element keeps its place on the canvas. ## Where to next - [Video mode](editor-video-mode.md): lanes, the razor, and the trim family. - [The timeline](editor-timeline.md): the slides-mode lens on time. - [Scenes and transitions](../guides/scenes-and-transitions.md): the blends a chain morphs across. # Delivery Quick export offers Draft, Share and Master presets. Draft selects up to 720 px and a fast low-quality H.264 encode; Share selects up to 1080 px at high quality; Master keeps the authored canvas at maximum quality. Presets never upscale a smaller document. Deliver opens the encoder controls by default. ## Encoder controls MP4 supports H.264 and H.265, an explicit CRF from 0 to 51 or a positive target bitrate, a closed set of encoder speed presets, and yuv420p, yuv420p10le or yuv444p output. CRF and bitrate are mutually exclusive. The default remains H.264, quality high, medium preset and yuv420p; absent knobs preserve the existing argument list and serialization. ```dart const settings = Export.mp4( codec: ExportCodec.h265, crf: 21, preset: EncoderPreset.fast, pixelFormat: ExportPixelFormat.yuv420p10le, ); ``` The dialog's choices affect one render snapshot. The saved document changes only when explicitly edited. Frame-rate changes are document edits because all timing is measured in composition frames. Desktop and browser FFmpeg receive typed, validated argument arrays. Browser codec availability depends on the installed FFmpeg build; an unavailable codec fails visibly. Mobile hardware export accepts codec and target bitrate and rejects software-only CRF, preset and pixel-format requests before capture. ## Cancellation and cleanup Each export can carry a `RenderCancellation` token. Desktop capture checks it between frames; encoding terminates the FFmpeg child process and waits for it to exit before deleting the partial sandbox. Failed renders also remove their sandbox. Successful desktop delivery copies the completed artifact to the chosen location and then removes the temporary render files. Browser cancellation terminates the FFmpeg worker, resets its loaded state and clears the in-memory capture sandbox. A later job reloads the worker. Successful and failed encodes delete staged virtual input/output files. The browser bridge must expose `terminate` and `deleteFile` for cancellable jobs; unsupported bridges fail explicitly. Disposing the desktop capture surface unmounts the widget subtree before releasing the render pipeline. Maintained tests exercise typed argument combinations, legacy defaults, round-trip digests, actual H.264/H.265 encodes, real process cancellation, partial-sandbox removal, browser worker reload/cleanup, and desktop capture subtree disposal. The maintained browser acceptance runs the app's real local FFmpeg worker and WebCodecs bridge, including encode, cancellation, reload, staged-file cleanup, first/middle/last source-frame pixels, embedded-audio metadata, and bounded RGBA retention. Run `dart apps/slides/tool/verify_web_encoder.dart` after vendoring browser assets. Source video preview currently demuxes MP4/MOV ISO BMFF files; other containers report that conversion is needed. Browser codec availability also depends on WebCodecs support for the file's video codec. ## Preview quality and background exports Full, Half and Quarter bound the preview's decoded clip raster. A 4K RGBA frame uses about 31.6 MiB at Full, 7.9 MiB at Half and 2.0 MiB at Quarter. Scrubbing keeps a bounded recent-frame cache. Layout and source timing stay the same. Draft can bypass effects and grades; the stage explicitly labels that choice. These preferences never modify the project or an export snapshot. Add exports to the Deliver queue or choose **Batch 1080p + 720p**. Each job owns the project snapshot taken when queued, so later edits do not change an ongoing render. Jobs run in order, display progress and can be cancelled individually. A failed job leaves following jobs runnable. The queue survives workspace switches and belongs to the current editor session, rather than disk storage. The repeatable optimized performance checks are `bash tool/verify_editor_performance.sh profile` and `bash tool/verify_editor_performance.sh release`. They drive a three-minute 4K project with eight lanes and 240 placements sharing one six-second source on Linux, measuring loading, digest work, timeline gestures, canvas drag, source decoding and preview capture. Engine frame timings are recorded separately from test-driver latency. Reproduction steps and measurement limits are in the [release verification guide](../contributing/editor-release-verification.md). The complete native journey saves and reopens identical project data, continues editing during rendering, then verifies both real MP4 artifacts with ffprobe. # The Effects tab Stack visual effects on any element and tune them without leaving the editor. The tab edits the same `effects` list the spec carries, so what you build here renders identically from the document, from generated Dart, and in the export. ## Add an effect Select an element and open the **Effects** tab in the inspector column. Add an effect three ways, and all three land the same command: - Pick it from the searchable **Add effect** select. - Click a chip in the grouped browser under it. Hover a chip to read what the effect does. - Drag a chip onto the element on the canvas, or onto a bar in the video timeline. The effect lands on the element under the pointer. Thirteen effects ship: grade, curves, lut, grain, vignette, scanlines, chromatic, bloom, blur, glitch, particles, shader and parallax. Each arrives on its own defaults, so a freshly added effect renders exactly what a bare `{"kind": ...}` declaration would. A bare grade is the identity: it changes nothing until you move a slider. ## Edit the stack Each effect is a tile in stack order. Drag tiles to reorder; order matters, because the stack composes by class then list order. The switch turns an effect off without losing its settings, exactly as `visible: false` works for an element: off stays in the document. The trash removes it. Add, reorder, toggle and remove are one undo step each. Numeric parameters are scrub fields: drag the label to scrub, type math to commit, arrow keys to step. Each field clamps to the effect's honest range, and each committed value is its own undo step, like every scrub field in the inspector. Boolean and choice parameters use a switch and a select. Blur exposes sigma in logical pixels; zero is an exact no-op. Glitch intensity scales its band displacement and channel split while preserving the original animation's timing and default appearance. The curves editor exposes actual channel control points. Particle settings and shader uniforms have validated JSON editors with explicit Apply actions; invalid drafts remain visible for correction and do not change the document. See [Colour](editor-colour.md) for Looks, portable LUT import, white balance and scopes. ## The diamond Every numeric row ends in a diamond. Click it to keyframe the parameter: the literal becomes a flat two-stop ramp over the element's own window, so the picture does not change and the stops appear as diamonds on the element's effect row in the video timeline. From there, edit the ramp on the timeline: add stops at the playhead, drag them, delete them. Click the diamond again to collapse the ramp back to a single value: the one it reads at the playhead, so what you see is what you keep. ## Copy a look **Copy Effects** puts the selected element's whole stack on the clipboard; **Paste Effects** appends it to every selected element as one undo step. The clipboard carries plain JSON text, so a look travels between documents and between editor windows. Both verbs live in the element's right-click menu and the command palette. ## Where to next - [Video mode](editor-video-mode.md): the effect rows and their diamonds on the timeline. - [Authoring with specs](../guides/authoring-with-specs.md): the `effects` list and keyframed parameters in the document itself. - [The timeline](editor-timeline.md): the slides-mode lens on time, per slide and per element. # Exporting a video from the editor `Export > Export video (MP4)` opens the options dialog, then renders the open deck through your platform's pipeline: a local FFmpeg on the desktop, or ffmpeg.wasm in the browser when the page ships the bridge. The dialog opens on the deck's own settings, so confirming it unchanged means "export exactly what I authored". ## Resolution Pick a canvas size. The list starts at the deck's own long edge and offers smaller rungs below it. Only the size scales; the deck keeps its aspect. A 16:9 deck exported at 720 renders 720 x 405, and a 9:16 deck exported at 720 renders 405 x 720. The label under the picker shows the canvas you will get. Larger sizes than the deck are deliberately not offered. Re-rendering above the authored canvas draws vector content sharper, but it cannot invent detail in a video clip or an imported image, so the option would promise more than the render delivers. Author at the size you want to deliver. ## Quality Quality maps to the encoder's rate factor. `high` is the default and is what every render used before this dialog existed, so an unchanged export is byte-for-byte the render you had. Lower quality means a smaller file, not a smaller canvas — the resolution picker is the one that changes pixels. ## Frame rate Frame rate is different from the other two, and the dialog says so when you change it: **it edits the deck.** A deck's timeline is measured in its own frames. Every scene duration, every `show` window and every animation span resolves against the deck's rate. So there is no honest way to capture a 30 fps deck at 60: the render would pump frames the composition's timeline does not have, and the video would either run past the end holding its last frame or stop short. Changing the rate therefore rewrites the document before the render starts. It is an ordinary edit: it lands on the undo stack and marks the deck unsaved, like any other change. ## What happens next The progress dialog reports the phases the pipeline reports — capturing frames, then encoding — and ends with the written path. A cancelled save dialog closes it quietly. A failed render leaves the reason in the dialog rather than discarding it. On a web page without the ffmpeg.wasm bridge the menu entry stays visible and disabled, naming what is missing, instead of quietly disappearing. ## Where to next - [The canvas](editor-canvas.md) — authoring the deck you are exporting. - [Video mode](editor-video-mode.md) — arranging clips on the timeline. - [Exporting your video](../guides/exporting-your-video.md) — the same pipeline from Dart, with the export modes the dialog does not yet offer. # Editor FAQ Short answers to the questions the editor raises. ## Why is my element not animating? An element only moves if it carries an animation. Select it and check the inspector's Animate section: an empty list means a still element. Add a preset there, or check the timeline for its bar. Two more traps: a hidden element (`visible: false`) builds nothing, so it has no timeline bars at all; and in Present mode entrances play once when the slide appears, so scrub back in the editor's timeline to watch them again. ## What does the saved indicator actually compare? The document's digest, a fingerprint of the whole JSON. `Saved` means the current digest equals the digest of what is on disk, so undoing your way back to the saved state reads `Saved` again without saving. `Autosaved just now` means the crash-recovery copy covers your current state; the file on disk is still behind until you save. ## Where does autosave live? On desktop, under your user config directory: `~/.config/fluvie_slides/autosave/`. On the web, in the browser's localStorage. One record per deck, holding exactly what Save would write — and on desktop, a deck referencing imported session media autosaves as a bundle sidecar, bytes included, so a crash loses nothing. Opening a deck that has a newer autosave prompts you to recover; the file on disk stays untouched until you choose to save. On the web the record alone survives: reopen your bundle first and recovery has its media; the prompt names any media it cannot rebuild instead of opening a broken deck. ## How do I bring the intro tips back? The start screen shows the "New here?" card until you dismiss it or save your first deck. Delete the file that remembers the dismissal and it returns: `~/.config/fluvie_slides/start_prefs.json` on desktop, or the `fluvie_slides_start_prefs` key in the browser's localStorage on the web. The same file holds your recents neighbour, `recent_decks.json`, which you can delete to clear the recent list. ## What is different on the web? Everything edits and presents the same. Saving uses the File System Access API where the browser has it, and falls back to downloads. Export slide images downloads numbered PNGs instead of asking for a folder, and Export PDF downloads the one file (the PDF bytes build the same everywhere). Export video renders fully in the browser through ffmpeg.wasm and lands as a download; the page must ship the `FluvieFfmpeg` bridge in `index.html` (vendor the wasm files with `apps/slides/tool/fetch_ffmpeg.sh`). Without the bridge the entry stays visible but disabled and names what is missing. ffmpeg.wasm is much slower than native FFmpeg, so long renders belong on the desktop. ## Why did pasting change my element's ids? Every paste and duplicate mints fresh ids, so two elements can never share one. References inside the copied set follow the re-mint; your other elements keep theirs. ## Do blocks or groups change how my deck renders elsewhere? No. A block is editor bookkeeping over a real `Group` whose children carry ordinary transforms. Open the deck in any Fluvie renderer, or clear the block, and the layout is pixel-identical. ## Why does auto-animate skip one of my elements? It pairs elements that are the same content on both slides, or that share an explicit id. An element with no partner is skipped on purpose: the engine never invents motion, so unmatched elements ride the slide's authored transition. Use the Morph row on the element to link a pair by hand. ## The exported Dart source lost my build steps and notes? It cannot express them: plain fluvie code plays straight through. The printed file says so in a leading comment. Present from the `.fluvie` file (or `deckFromSpec`) and steps and notes are preserved; the Dart export is for rendering and for reading your deck as code. ## Is there a keyboard shortcut for undo? Yes: Ctrl/Cmd+Z undoes and Ctrl/Cmd+Shift+Z (or Ctrl+Y) redoes, anywhere in the editor; the top bar's two arrow buttons do the same. Every command is one undo step, including a whole drag or a whole theme apply. ## Where did my second monitor's speaker notes come from? From the notes strip under the timeline. Slide-scope notes show on every step; a step scope replaces the text and appends its highlights, exactly as the strip's preview line shows. ## Where to next - [Editor getting started](editor-getting-started.md): the tour. - [The start screen](editor-start-screen.md): recents, templates, samples. - [Editor shortcuts](editor-shortcuts.md): the full key map. - [Authoring with specs](../guides/authoring-with-specs.md): the same document, written by hand or by a model. # The editor: getting started The Fluvie editor is a visual presentation editor. Your document is a `.fluvie` file, the same JSON spec the rest of Fluvie reads, so a deck you draw on the canvas renders as a video, presents live, and loads from code. Open the slides app and you are looking at the start screen: - **New deck** starts from one empty slide. - **Open a deck** opens a `.fluvie` file you already have. - **New from template** opens a gallery of complete starter decks. - **Present a .fluvie file** plays a deck without opening the editor. - **Samples and tutorials** holds the seven bundled example decks and **Edit the demo deck**, which opens the bundled example on the canvas. See [The start screen](editor-start-screen.md) for the rest of it. The app runs in the browser at [slides.fluvie.dev](https://slides.fluvie.dev) or as a desktop build from `apps/slides` in the repository. Everything below works in both; the differences are listed at the end. ## Put something on a slide Pick a tool from the left toolbar, or press its key: - `T` drops a text element. Type straight into it. - `R` draws a rectangle, `O` an ellipse, `L` a line, `A` an arrow. - `M` inserts an image or video from a file. - `V` returns to the select tool. So does Escape, and so does finishing a placement. Every element lands with a real position and size in the document. Drag to move it, drag a handle to resize, use the top handle to rotate. The inspector on the right edits the numbers directly. ## Style it Select an element and the inspector shows its content, transform, and style. Color fields open a picker that leads with your theme palette; tap a token to bind the color to the theme, so a theme switch restyles the deck. The Theme tab on the left edits the palette, type scale, spacing, and motion. See [Themes, masters, and templates](editor-themes.md). ## Save Save writes the document as pretty-printed `.fluvie` JSON. The first Save asks where; after that it rewrites the same file silently. The quiet label next to the deck name tells you where you stand: `Saved`, `Unsaved`, `Autosaved just now`, or `Saving…`. Autosave covers you between saves; if the app dies, the next open offers to recover. The document is plain spec JSON: ```json { "fluvieSpec": 1, "size": { "width": 1920, "height": 1080 }, "fps": 30, "scenes": [ { "duration": "6s", "children": [ { "id": "el-1", "type": "Text", "text": "Hello", "transform": { "x": 0.5, "y": 0.3, "w": 0.8, "h": 0.2 } } ] } ] } ``` Anything Fluvie can read can open this file. Nothing the editor writes is editor-only magic; its own bookkeeping lives under one `editor` key that renderers ignore. ## Present Present plays the deck live over the editor, stepping like a presenter: entrances play, then the slide waits for you. Close it and you are back on the canvas with every edit intact. Build steps and speaker notes authored in the timeline and notes strip carry into the speaker window. ## Export The Export menu in the top bar offers five ways out: - **Export .fluvie** saves the document to a fresh file (Save as). - **Export Dart source** writes a runnable `Video build()` Dart file, printed by the fluvie_cli printer. Theme tokens print as resolved literals and masters print applied, so the code renders exactly what you see. - **Export slide images (PNG)** renders every slide's settled state to a numbered PNG. Desktop asks for a folder; the web downloads the files. - **Export PDF** renders the same settled states into one PDF, a page per slide at the deck's canvas size. Desktop asks where to save the file; the web downloads it. - **Export video (MP4)** renders the deck through fluvie's real pipeline. The desktop renders through your local FFmpeg into a file you pick. The web renders fully in the browser through ffmpeg.wasm and lands as a download; the page must ship the `FluvieFfmpeg` bridge in `index.html`. Without the bridge the entry stays visible but disabled and names what is missing. See [Video mode](editor-video-mode.md) for the details. ## Web and desktop | Capability | Desktop | Web | | --- | --- | --- | | Edit, present, save, autosave | yes | yes | | Export .fluvie and Dart source | yes | yes (File System Access or download) | | Export slide images | yes, into a folder | yes, as downloads | | Export PDF | yes, into a picked file | yes, as a download | | Export video (MP4) | yes, local FFmpeg | yes, ffmpeg.wasm (the page ships the FluvieFfmpeg bridge) | ## Where to next - [The canvas](editor-canvas.md): tools, selection, snapping, groups, and the command palette. - [The timeline](editor-timeline.md): animation bars, keyframes, build steps, and the playhead. - [Continuity across slides](editor-continuity.md): overlays, shared chains, and the difference between a hairline and a bar edge. - [Themes, masters, and templates](editor-themes.md): restyle a whole deck from one palette. - [Shortcuts](editor-shortcuts.md): the full key map. - [The start screen](editor-start-screen.md): recents, templates, and where the samples live. - [FAQ](editor-faq.md): short answers to the questions the editor raises. # Media bin and source monitor In video mode, **Import media** adds a reusable source to Assets. It does not place a clip until you choose Place or drag a source range onto the timeline. The bin supports folders, search and sorting. Imported metadata shows duration, resolution, source frame rate and audio channel count when the platform can probe them. Unavailable metadata is stated rather than guessed. Select an asset to open its source monitor. Scrub independently of the project playhead and use **I** and **O** while the source monitor has focus to mark its range. Marks belong to the asset, so repeated placements reuse them. The placed clip stores its own trim and timeline window; later changes to bin marks do not retime existing clips. Fractional source rates are converted through source time rather than treated as the project's frame rate. Choose Place to use the active lane and playhead, or drag the marked range to a compatible lane. Locked or incompatible lanes refuse the placement visibly. Audio ranges also preserve their placement offset and source trim. The source monitor's **Listen from playhead** action auditions audio; the channel label identifies the mono preview mix. **Stop listening** ends the audition. Desktop imports keep file references. Browser imports keep bounded session bytes and save them in the project bundle, including assets that remain only in the bin. Save and reopen preserve folders, metadata and marks without changing the render digest. A plain file-reference project still needs its referenced files at their saved paths. Browser video preview supports MP4/MOV containers and codecs available through WebCodecs. Other containers report the required conversion. Desktop decoding uses FFmpeg. Source and timeline decode failures offer visible errors; a filmstrip can be retried after the media becomes available again. See [Media and bundles](editor-media.md) for portability and [Workspaces](editor-workspaces.md) for layout and disclosure. # Media and bundles Drop a photo or a clip into the editor and it becomes part of your deck. This page covers the three ways media comes in, where the bytes live on each platform, and how a deck travels with its media. ## Importing media Media enters the editor three ways: - The media tool (M) opens the system picker for images, videos, and audio files. - Dropping a file onto the canvas inserts it on the current slide. - The Assets dialog (in the toolbar) lists everything the deck already holds, one tap to reuse it. An image inserts as an `Image` element, a video as a `Clip`, both centered on the slide. An audio file joins the deck's media store only; the video mode's audio tracks pick it up from there. ## The media store Every import is recorded in the document's `editor.media` block: the file's name, its kind, its source, and its size. The store feeds the Assets dialog, so a file you imported once is one tap away on every slide. Remove an entry with the trash control next to it. Store entries are editor metadata: they never change how the deck renders, and the render digest ignores them. ## Where the bytes live On desktop an import stays a file path. The document references `{"kind": "file", "value": "/path/to/photo.png"}` and the render pipeline reads it from disk, exactly as before. Saving makes those paths portable. Any image or video file inside the document's own folder is written relative to it, as `{"kind": "file", "value": "media/photo.png"}`, so the folder travels as one unit: move it, reopen the deck, and the values resolve against the file's new location. Paths outside the folder stay absolute, and audio paths always stay absolute (the spec requires it). The values stay relative inside the saved JSON, so the render digest is stable from one machine to the next. The web has no file paths. An imported file's bytes stay in the session: the document references them with a bundle source, `{"kind": "bundle", "value": "media/photo.png"}`, and the live preview resolves that reference against the session's bytes. The session bounds its total size; an import past the budget is refused with a visible message instead of a silent drop. ## Saving a deck with session media Session bytes cannot live inside a JSON file. When you save a deck that references them, the editor asks: - **Save bundle** writes one `.fluvie` file that is a zip: the deck JSON plus a `media/` folder with every referenced file. The deck travels with its media. - **Save JSON only** writes the plain document. The media references stay in the text, but the bytes do not travel. - Check **Don't ask again for this deck** and your choice is remembered in the document; Save stops asking. Both forms use the one `.fluvie` extension. Opening sniffs the first bytes: a zip is unpacked (only `media/` entries, size-capped, traversal names refused) and its media is restored into the session; anything else parses as plain JSON. Reopening a bundle and saving it again produces the same document, byte-identical media included. Save a copy always writes plain JSON, so it warns first when the deck references session media. ## Crash recovery and session media Autosave covers session media too. On desktop, an autosave of a deck that references session bytes is written as a bundle sidecar (the same zip form a `.fluvie` bundle uses), so recovery after a crash restores the document, the bytes, and the previews in one step, even for a deck you never saved. The web's localStorage cannot hold media bytes, so a web autosave keeps the document JSON alone. Recovery is still complete in the common case: reopen your bundle file and its media repopulates the session, and the autosaved edits recover over it. Only media imported after your last bundle save has no surviving bytes; a recovery that would break such references stops and names them instead of opening a broken deck, and keeps the autosave for an open that has the media. ## Presenting with a speaker window The web speaker popup is its own browser window, so your session's bytes are not in it. Presenting hands the popup a session-scoped copy of the deck whose bundle references are rewritten to object URLs minted in the main window; the popup fetches the same bytes through them for as long as the main window stays open. Nothing of this is saved: your document keeps its bundle references, and the rewritten copy dies with the session. If you open the speaker route later, without a presenting main window, its media URLs are gone with the window that minted them. ## Where to next - [Editor getting started](editor-getting-started.md): the tools and panels around the canvas. - [The canvas](editor-canvas.md): placing and arranging what you import. - [The timeline](editor-timeline.md): animating the media once it is placed. # Editing the video timeline The timeline uses one absolute frame ruler for the whole video. **Quick** shows an unnumbered Picture lane and Audio lane; **Edit** shows the declared numbered video and audio lanes, effects and transitions. Switching workspaces changes presentation without rewriting the document or its lane assignments. Drag a bar to move it in time and onto a compatible lane. Drag its edges to trim. Snapping uses nearby bar edges, the playhead, scene boundaries, markers, in/out marks and frame zero. Hold Ctrl (Cmd on macOS) to bypass snapping. Click selects a bar, Shift-click extends a range, Ctrl/Cmd-click toggles membership, and dragging empty space selects a rectangle across lanes. The **Clip** and **Sequence** menus, command palette and keyboard all use the same command registry. Set in/out with I/O, razor the selection at the playhead with B, and use Ripple delete, Lift or Extract for the selected material. The [shortcut reference](editor-shortcuts.md) lists the current bindings. A ripple closes gaps within each scene and preserves scene duration. A shared chain is edited across all its memberships in one undo step. Razor divides it into independent left and right chains; a marked range can cut across several members. Geometry stays local to each member. Locked lanes refuse edits. Clips that overlap a deleted gap remain in place and the editor reports this. Roll changes the cut between adjacent clips. Slip changes source in/out while holding the bar's window. Slide moves a bar and adjusts its neighbours. These operations refuse trigger-driven timing or source ranges they cannot determine; the reason appears above the timeline. Slip also works across a shared chain: each member retains its own source range, rate, timing and geometry, and a source start clamps the whole gesture. Roll and Slide require a single scene's neighbour pair; a logical chain spanning several scene clocks is refused with guidance to use its timing handles. They do not guess a neighbour in another scene. Audio with an explicit placement can be moved, while trigger-based placement is preserved. Music with a known source trim supports Razor, Lift, Extract and ripple edits. Those cuts retain volume automation and fades across the split. Looped, anchored or trigger-placed audio explains why it cannot be cut without changing its authored timing. Declared lane labels offer lock, mute and preview-only solo. Drag a label to reorder lanes; video lane reorder also rewrites element order so the canvas, layers list and hit testing agree. Empty declared lanes remain available as drop targets. Cached waveforms and filmstrips appear as media becomes available; visible spans drive thumbnail requests and off-screen rows are virtualized. A ruler hairline is a scene boundary. Dragging it retimes the preceding scene; its Length field edits the same value. A bar edge is a clip cut. See [continuity](editor-continuity.md) and [transitions and speed](editor-transitions.md) for the distinction and the available rate-stretch and blend tools. # Editor shortcuts Everything the editor listens for. On macOS, Cmd replaces Ctrl in every chord. The Edit and Arrange tables are the command registry's own bindings; menus and the command palette print the same chords, and a test pins this page to the registry, so the table cannot drift. ## Tools | Key | Does | | --- | --- | | `V` | Select tool | | `H` | Hand tool (pan) | | `T` | Text tool | | `R` | Rectangle | | `O` | Ellipse | | `L` | Line | | `A` | Arrow | | `M` | Insert media | | Esc | Cancel the drag, else back to select, else exit the group, else clear the selection | ## Edit | Chord | Does | | --- | --- | | `Ctrl+Z` | Undo | | `Ctrl+Shift+Z` (or `Ctrl+Y`) | Redo | | `Ctrl+X` | Cut | | `Ctrl+C` | Copy | | `Ctrl+V` | Paste | | `Ctrl+D` | Duplicate | | `Ctrl+A` | Select all | | `Del` (or Backspace) | Delete | Paste re-mints element ids, so a copy never collides with its source, and nudges the copy when it lands on the same slide. ## Arrange | Chord | Does | | --- | --- | | `]` | Bring forward | | `[` | Send backward | | `Ctrl+]` | Bring to front | | `Ctrl+[` | Send to back | | `Ctrl+G` | Group | | `Ctrl+Shift+G` | Ungroup | | `Ctrl+Shift+L` | Lock | | `Ctrl+Shift+H` | Hide | ## On the canvas | Input | Does | | --- | --- | | Arrows | Nudge the selection one canvas pixel | | Shift+Arrows | Nudge ten pixels | | Ctrl (held while dragging) | Bypass snapping, on the canvas and the timeline | | Shift (while resizing) | Keep the aspect ratio | | Alt (while resizing) | Resize from the center | | Shift (while marqueeing or clicking) | Add to the selection | | Double-click | Enter a group, or edit a text inline | | Right-click | The context menu for whatever is under the pointer | ## Timeline and transport | Input | Does | | --- | --- | | Space (panel open) | Play or pause | | Space (panel closed) | Step to the next build landing; past the last, the next slide | | Shift-drag the ruler | Arm a playback loop over the range | | Esc | Clear the loop | | Del | Remove the selected keyframe or build marker | | Double-tap the ruler | Split a build step | ## Timeline The verbs that act on time rather than on the canvas. None of them is an edit, so none of them lands on the undo stack — moving the playhead is navigation, and burying your real steps under it would make undo useless. | Input | Does | | --- | --- | | `I` | Mark in, at the playhead | | `O` | Mark out, at the playhead | | `Shift+I` | Go to in | | `Shift+O` | Go to out | | `Page Up` | Previous edit | | `Page Down` | Next edit | | `B` | Razor at playhead | | `Shift+B` | Razor all lanes | | `X` | Lift selection or marked range | | `Shift+X` | Extract marked range | | `Shift+S` | Timeline snapping | | `Shift+N` | Add lane | | `Shift+Del` | Ripple delete | Next and previous edit land on the frames where the picture actually changes: each scene's start and end, and the frame it settles on after its incoming transition. They read the same timebase the compositor mounts against, so they cannot land somewhere nothing happens. The page keys carry these rather than the arrows, because the arrows nudge the selected element on the canvas and the registry dispatches by key across every surface. The razor and the ripple delete are the two edits here, and the only verbs on this page that land on the undo stack. It cuts every selected clip the playhead sits inside, as one step, and leaves the ones it misses alone. The halves play exactly what the clip played: the tail picks up the source where the head left off rather than restarting it. The other six need a playhead to act on. A stage holding a settled still (slides mode, and master editing) has none, so they read as disabled there rather than marking frame zero, which is a real position and not an absence. ## Everything else | Input | Does | | --- | --- | | `Ctrl+K` | The command palette | Undo and redo also sit on the top bar as the two arrow buttons. In Present mode the presenter's own keys apply: arrows and Space step, `F` is fullscreen, `B` blacks the screen, `S` opens the speaker window. ## Where to next - [The canvas](editor-canvas.md): the tools behind the letters. - [The timeline](editor-timeline.md): what Space steps through. - [FAQ](editor-faq.md): the questions the key map raises. # The start screen The slides app opens on the start screen. It has one job: get you into a deck. Two buttons do most of the work, your recent decks sit next to them, and everything else is one click away. ## The two primary actions - **New deck** opens the editor on one empty slide. The deck is called `untitled.fluvie` until you save it. - **Open a deck** opens a `.fluvie` file from your machine in the editor. Both live in the left column under **START**, on top of everything else, so they never scroll away. ## The secondary actions Under **MORE**: - **New from template** opens the template gallery: a pitch, a report, a portfolio, and a master starter, each with its own theme and masters. - **Present a .fluvie file** plays a deck without opening the editor. Use it when you only need to show a deck someone sent you. - **Samples and tutorials** opens the sample browser. See below. You can also drop a `.fluvie` file anywhere on the window to present it. ## Recent decks Every deck you open, save, or rename lands in the recents list, newest first, capped at eight. A tap reopens it in the editor. Each row shows when you last opened it and where it lives. In the browser there are no file paths, so a web entry shows as history instead of a button. Reopen it with **Open a deck**. The list is stored in `~/.config/fluvie_slides/recent_decks.json` on desktop and under the `fluvie_recent_decks` localStorage key on the web. Delete either one to clear the list. ## Templates The template strip shows one card per built-in template with a small sketch of the theme it ships. A card starts a new deck from that template right away. **Browse all** opens the same gallery the **New from template** tile opens, grouped by purpose. See [Themes, masters, and templates](editor-themes.md) for what a template carries. ## Samples and tutorials The seven bundled example decks live behind **Samples and tutorials**. Each one presents, and each one teaches the feature it uses: | Deck | What it shows | | --- | --- | | Plain slides | One scene is one slide | | Builds with Stop | Reveal content step by step | | Speaker notes | Scene defaults and per-step overrides | | Media-heavy slides | Charts, code, and live elements | | Embedded video | Real players with sound, on the web | | What is fluvie | Fourteen slides, notes on every one | | The full talk | Everything together, end to end | The same dialog holds **Edit the demo deck**, which opens the bundled demo spec on the canvas instead of presenting it. ## The first-run tips On your first run the screen shows a **New here?** card with four things worth knowing: scenes are slides, the presenter keys, the render path, and where the samples are. It disappears when you dismiss it or once you have a recent deck. To bring it back, delete `~/.config/fluvie_slides/start_prefs.json` on desktop, or the `fluvie_slides_start_prefs` key in the browser's localStorage. ## Where to next - [Editor getting started](editor-getting-started.md): the tour of the editor itself. - [Themes, masters, and templates](editor-themes.md): what a template brings with it. - [FAQ](editor-faq.md): short answers to the questions the editor raises. # Themes, masters, and templates One palette should restyle a whole deck. The editor gets there with three layers: theme tokens for values, masters for slide layouts, and templates for complete starting decks. All three are spec data, so a themed deck renders themed everywhere, not just on this canvas. ## Theme tokens The Theme tab (third tab on the left, next to Slides and Layers) edits the document's `theme` block: a color palette, a type scale, spacing, and motion defaults. Every color field in the inspector leads with the palette; tap a token and the field binds to it as `{"token": "accent"}` instead of a literal. A bound field shows the token as a chip; unbind it and the resolved literal is written back. Change the token's value and every bound color in the deck follows, slide thumbnails included. Renaming a token rewrites every reference in one undo step, and removing a token that is still referenced is refused, because a dangling reference would fail the next render loudly. Three builtin themes ship as starting points: midnight, paper, and neon. They share one token vocabulary, so "Start from" restyles the same bound deck rather than resetting it. ## The gradient editor Gradient backgrounds edit in a dedicated widget: a stops bar you drag, tap to add a stop (it samples the gradient there), drag a stop well below the bar to remove it, a numeric angle for linear gradients, and a radial mode. Dragging a stop writes its offset into the spec's `stops` list; while every stop sits at its even-spacing position the list stays out of the document. Stops you did not touch keep their exact JSON, so token-bound gradient colors survive edits to their neighbors. ## Masters A master is a named slide layout: fixed chrome plus named placeholder slots. A slide adopts a master by name and fills its slots; editing the master changes every adopting slide, because adoption happens at build time, never by copying. The slide strip grows a masters row once masters exist: apply one to the current slide, or open it in master-edit mode, where the same canvas and inspector edit the master itself. Placeholders show as labeled outline boxes. On an adopting slide, an unfilled slot is a click target: a text slot types straight in, a media slot asks for a file. A filled slot is a first-class element, and deleting it unfills the slot. Applying a different master, or detaching one, never loses content: fills whose slots survive stay fills, and orphaned content is promoted to plain slide elements where it stood. ## Templates **New from template** on the start screen opens a gallery of complete decks (a pitch, a report, a portfolio, a master starter), each carrying its own theme and masters over the builtin token vocabulary. A slide tile's menu can also insert a single template slide into the open deck; the tokens and masters the deck is missing merge in additively, and the deck's own entries always win on collision. ## Auto-animate With nothing selected, the inspector shows the slide's Auto-animate section. Switch on "Match previous slide" and the editor pairs this slide's elements with the previous slide's, explicit shared ids first, then same-content matches, and writes shared-element ids on both sides so the pair morphs across the slide boundary. Preview morph plays the real transition in a dialog; the file render and the presenter play the same morph, one machinery. The engine never invents motion: unmatched elements ride the slide's authored transition. The Morph row on a selected element links or unlinks a pair by hand, and manual links survive switching the toggle off. ## Where to next - [Theming](../advanced/theming.md): the same token idea on the code side. - [Editor getting started](editor-getting-started.md): where the tabs and the start screen live. - [The canvas](editor-canvas.md): editing the elements the theme colors. # The timeline The timeline panel sits under the canvas and shows when the current slide's motion happens. One track per element, in layer order; one bar per animation, colored by phase: enter, during, exit. The panel opens by default; its header collapses it. ## Bars: retime and trim Drag a bar to retime its animation: the drag writes the animation's delay, so it works the same for every trigger form. Drag an edge to trim the duration; the left edge moves the start too. One drag is one undo step. A slide with no animations shows a one-line offer to add a first `fadeIn`. ## Keyframes: the diamonds A `keyframes` animation draws a diamond per stop. Click a track at the playhead to insert a stop there, interpolated between its neighbors. Drag a diamond to move its stop; stops never cross. Delete removes the selected stop, and a two-stop bar loses the whole animation, because one stop is not a keyframe animation. Trimming a bar rescales authored stop positions proportionally. Select a diamond and the inspector grows a Keyframe section with the stop's full field set: position, scale, rotation, opacity, color, origin, and the easing of the outgoing segment. ## The Animate panel The inspector's Animate section lists the selected element's animations from the same model the timeline draws, so the two can never disagree. Each row edits duration, ease, trigger, and offset, and removes. Add opens a searchable picker of every preset, grouped by phase. Triggers cover the keyword forms (auto, previous, scene start, scene end) and the anchor forms ("when X ends", "when X starts"); anything authored beyond that shows as a read-only custom trigger rather than being flattened. ## Trigger links A bar with a cross-element trigger draws an elbow connector from its trigger's bar, labeled with the offset (`+12f`). Drag the small handle at a bar's top onto another bar to create a link: the editor mints the anchor and writes the trigger in one undo step. Re-drop to retarget, or delete the link to return the animation to automatic timing. A drop that would create a timing cycle is refused before it can break the deck. ## Build markers: click steps Markers on the ruler split the slide into presenter click steps, in exact parity with the presenter's own step compiler: marker k sits where step k settles. Double-tap the ruler to split a step, drag a marker to re-balance two steps, drag it off the ruler (or press Delete) to merge. When a step plan is invalid, the panel header names the problem and the offending bars outline in the error color. ## Scrub and transport The ruler's playhead is the one clock: the canvas, the ruler, and the readout always agree on the frame. Scrub to seek; the stage holds the exact frame. The header plays and pauses, and Shift-drag on the ruler arms a loop over a range (Escape clears it). Space is contextual. With the panel open it toggles playback. With the panel closed it steps the slide the way a presenter click would, landing on each build step's settled state, and walks into the next slide past the last step. ## The notes strip Under the timeline sits the speaker-notes strip: prose plus highlight bullets per slide, with per-step scopes when the slide has build markers. What you type here is exactly what the speaker window shows. Step text replaces the slide text; step highlights append. ## Where to next - [Configure a TrackTimeline](../reference/track-timeline.md): migrate the grouped widget inputs when you embed a timeline. - [The canvas](editor-canvas.md): the space those bars animate in. - [Timing and triggers](../guides/timing-and-triggers.md): the timing model the timeline edits. - [Animating elements](../guides/animating-elements.md): the presets behind the Animate panel. # Titles and motion Open **Titles** beside Assets, choose a full-screen headline, lower third, credits or callout, then edit its selected text on the canvas or in the inspector. A title inserts ordinary elements on the active lane at the playhead, bounded by the scene end. It adds missing theme tokens and master definitions; existing document tokens win. The complete insertion is one undo step. The four shipped compositions are JSON assets in `fluvie_editor/assets/titles`, so saved documents remain editable without a preset dependency. `SplitText` splits by word, extended grapheme cluster, or explicit line. Combining accents and emoji sequences stay intact. Apply ordinary animation presets with `stagger`; each part uses the same stagger distributor and clock as a Row or Group. Effects and shared-element wrappers preserve this distribution. Select an element and open **Animation** to edit an animation's easing, a keyframe segment, or a numeric effect segment. Drag a control point or enter its coordinates. A drag commits once on release, so undo restores the previous curve in one step. Choose a named ease to reset the curve. Custom curves serialize as `{"cubic": [x1, y1, x2, y2]}`; an exact named shape canonicalizes back to its name. X coordinates remain within `[0,1]`; Y coordinates may overshoot. The same cubic appears as a native Flutter `Cubic(...)` in exported Dart. ```dart Widget titleMotion() => SplitText( 'Your next great story', style: const TextStyle(fontSize: 54, fontWeight: FontWeight.bold), ).animate([ Animation.slideFadeIn( duration: const Time.frames(30), ease: const Cubic(0.2, 0.9, 0.6, 1), stagger: const Stagger.each(Time.frames(4)), ), ]); ``` # Clip transitions and speed A hairline is a scene boundary; a bar edge is a clip cut. Dragging a hairline retimes a scene and everything downstream. A transition at a clip cut blends two neighbouring clips inside the same scene and lane. ## Dissolve, wipe, zoom and slide Open **Transitions** above the video timeline and drag a tile onto the cut between two clips. The cut snaps to the neighbouring pair and starts with a half-second blend. The transition has its own bar. Drag either edge to change its duration; a whole drag is one undo step. Select the transition and choose **Remove transition** to restore the authored clip windows. Both clips must be direct siblings on the same lane. Their authored windows must touch, or already overlap by no more than the blend. A duration that does not fit is refused with its reason. Shared heroes have their own scene-boundary morph and cannot also be members of a clip transition. Structural edits preserve the transition whenever the resulting pair still fits. A razor transfers an outgoing transition to the tail and keeps an incoming one on the head. A cut inside a blend that leaves too little material is refused with the engine’s reason. The default overlapping blend starts the incoming clip early by the blend length and preserves its duration, so its end also moves earlier. The scene's length stays fixed: for example, a clip authored at frames 24–48 with a six-frame overlap plays at 18–42, leaving the scene background at 42–48. Extend the last clip or shorten the scene if that gap is unwanted. Its picture and source audio use that same window. Audio fades use complementary sine/cosine envelopes for constant power and multiply any authored volume automation. Changing the transition duration changes both envelopes. A spec with `overlap: false` holds the outgoing picture on its last frame while the incoming clip starts at the cut; its outgoing source audio fades before the cut and the incoming audio fades after it, because a held frame has no new source audio to play. Custom transitions use the public `registerTransitionStrategy` registry and `Transition.custom`. A strategy returns its widgets in paint order, bottom first, and receives eased progress in `(0, 1]`. A cut has no blend window and cannot be registered as a blend strategy. ## Speed and slow motion Select a clip and edit **Speed ×** in the inspector. Enable **Rate stretch** above the timeline to make the bar's right edge change its speed. Both preserve the selected source in/out points and adjust the displayed duration. Whole-frame rounding adjusts the stored rate so the same source range is consumed. Extend the scene first if the requested duration cannot fit. Shared clip chains apply the requested speed to every member in one undo step, preserving each member's source in/out, start and geometry. Rate stretch scales their durations together and puts the last member's end at the dragged edge. If a member cannot fit its scene or group, or its lane is locked, the whole edit is refused with its reason. Choose **Add speed ramp** to vary speed over the clip. Edit each stop's rate, add or remove a middle stop, change its position percentage, and edit the easing between stops. The source clock is the integral of that curve: picture, frame extraction, preview and source audio all follow the same clock. Stretching a ramp scales all its rates together. Rates must stay positive, including between stops; a curve that crosses zero is refused. Slipping a ramp translates its source range using that same integrated clock. The window and easing remain unchanged. A drag captures every shared member's original source range, so reversing the pointer returns to the original footage without accumulating offsets. **Reverse** applies to a constant speed and explicitly drops the clip's source audio. Use an independent audio track for a rewind sound. Reverse ramps are not accepted. Razor preserves the complete eased speed curve and source-frame phase on both halves, including cuts between original ramp stops. Stops outside a half’s visible window remain in its curve so playback does not restart the easing. ## Related editing tools - [NLE timeline](editor-nle-timeline.md): lanes, cuts, trim tools and shortcuts. - [Continuity](editor-continuity.md): overlays, shared chains and scene duration. # Video mode Flip the editor into a video editor: the whole composition on one absolute clock, clips and audio as lanes, and a real MP4 out the other end. Same document, same undo history, same canvas. Video mode is a different lens over time, not a different file. ## Switching modes The top bar carries two mode buttons: Slides and Video. The switch is one undoable step, and the document remembers its mode across saves. Nothing drops on a switch: steps, notes, and per-slide animation have no video-mode surface, but they stay exactly as authored and come back with Slides mode. A deck that never enters video mode never writes the mode key. ## Importing media Import works the same in both modes: the file picker (press M), drop onto the canvas in slides mode, or the assets panel for reuse. A video import lands as a clip on the canvas and an entry in the deck's media store. An audio import is store-only: audio has no canvas shape, so it waits in the store until you add it as a track. On the desktop an import keeps its file path; on the web the bytes live in the session, and Save offers a `.fluvie` bundle so the deck travels with its media. ## The timeline lanes Video mode's panel shows the whole video: scene blocks on a ruler, one lane per clip (and per element with an authored time window), and one lane per audio track. - Drag a clip lane to move it in time. The drag writes the element's `show` window; the video's edges are the only hard walls. - Drag the bar's start into another scene and the element moves there. It lands exactly where you dropped it, keeps its transform, props, and animations, and comes out on top of the target slide's stack. If the old slide's build steps named it, the move strips it from them and the panel header says so. A group moves whole; a grouped element never moves alone. - Drag a lane edge to trim. Trimming a full-scene clip mints its first window. - A music bed refuses to move, because the spec has no key for a delayed bed; it starts with its owner. Trim it instead. The panel header says exactly that when you try. - A sound effect moves by rewriting its start time. If a trigger places it, the drag is refused rather than silently destroying the trigger. Every lane edit is one undo step, and a refused or clamped drag explains itself in the panel header. ## Lanes A deck can declare lanes, and the timeline draws one row for each of them in declaration order. Clips and audio tracks that name a lane sit on its row; anything that names none keeps a row of its own, exactly as it did before lanes existed. A declared lane with nothing on it is still a row, because that is where you drag the next clip. Drag a clip onto another lane's row and it moves there. Its window, its trim and its place in the stack are untouched: a lane says where a clip is *shown*, never what order it paints in, so re-laning never changes the picture. The move and the re-lane are one drag and one undo step. A muted lane is silent, in the preview and in the export. That is the one lane setting the renderer reads. ## Reading the lanes The ruler carries timecode and seconds together: an author laying out a forty-second video thinks in seconds, and one matching a cut to a reference reads the timecode. A lane can set its own height, and an audio lane uses the room for its waveform, drawn from the decoded envelope across the whole lane. A clip lane can carry a filmstrip; the frames are asked for only as they scroll into view, because decoding a whole project to draw a strip nobody looked at is the one cost a timeline cannot afford. Only the rows the panel can actually show are built and painted, so a project with a hundred lanes scrolls like one with five. ## Effect rows and their diamonds An element with an `effects` stack grows one row per effect, indented under its bar. The effect's bar spans the element's window, because an effect has no span of its own: it runs for its element's life. When the element sits on a declared lane, the effect row carries the element's name too, so you always know whose grain you are looking at. A keyframed parameter draws a diamond per stop, the same diamonds slides mode draws for `keyframes` animations: - Park the playhead inside the bar and click the effect's row to add a stop there. The new stop takes the value the ramp already reads at that frame, so the picture at that frame does not change. On an eased segment the two halves re-ease from the new stop, which reshapes the curve around it, the same way an animation keyframe insert does. - Drag a diamond to move its stop. It stays strictly between its neighbors, and the whole drag is one undo step. - Click a diamond and press Delete to remove its stop. At the two-stop minimum the parameter collapses back to a literal, the surviving stop's value, because a one-stop ramp is a plain number wearing a list. A still parameter never grows stops from the timeline. Converting a literal into a keyframed value is the Effects tab's job. ## Selecting clips Click a bar to select it. Shift or Ctrl adds one to the selection, and a drag across empty lane space draws a rubber band that takes every bar it touches, across as many lanes as it crosses. A band that catches nothing clears the selection, which is what sweeping empty space plainly means. Selecting a bar also selects its element on the canvas, so the inspector follows. The two selections stay separate underneath: a bar is a span of time on a lane and an element is a thing on the canvas, and a verb aimed at one must never find the other. ## The razor Park the playhead inside a selected clip and press `B` (or use the scissors in the panel header) to cut it in two. Every selected clip the playhead sits inside is cut, in one undo step, and the ones it misses are left alone. The halves play exactly what the clip played. The head keeps the clip's identity, its place in the stack and everything it carried; the tail is a new element with the same props and a trim that picks up where the head left off, so the cut does not restart the footage. A reversed clip cuts from the far end, because that is the end it plays from. Two cuts it refuses, and says so rather than guessing: - A clip inside a group. Ungroup it first, or the halves would land outside the group. - A clip whose trim is written in source frames. Source frames only mean something at the source's own frame rate, which the editor cannot read; rewrite the trim in seconds and the cut is exact. ## Ripple, roll, slip and slide Each of these is defined by what it holds still, and each is one gesture with one modifier held. | Gesture | Does | Holds still | | --- | --- | --- | | Drag a bar | Moves the clip | Everything else | | Alt + drag a bar | Slips: changes what plays | When it plays | | Shift + drag a bar | Slides: changes when it plays | What it plays, and its neighbours' outer edges | | Drag an edge | Trims | Everything else | | Alt + drag an edge | Ripple trims: what follows moves with it | The clips before it | | Shift + drag an edge | Rolls the cut | Both clips' outer edges | `Shift+Del` ripple deletes the selected clips: they go, and what followed them on the same slide comes back to fill the gap. A ripple never changes a slide's length, because a window is measured inside its slide. Where nothing follows the gap, it stays and the header says why. A clip that overlaps a deleted span is left where it is rather than pulled somewhere the author never put it, and the header names how many. Every one of these is one undo step, and every refusal or clamp explains itself in the panel header: a roll with no cut to move, a slide with no neighbour to absorb it, a slip already at the start of its source. ## Snapping Drags catch on the frames that matter: the playhead, every scene boundary, and every other bar's start and end. A white guide line flashes where the catch happened, so a bar that lands on a cut looks like it meant to. - A moved bar catches on either of its own edges. Drag a clip so its tail meets the next scene and the bar lands with the tail exactly on the cut. - A trimmed edge catches on its own, and the edge you are not dragging never moves. - Hold Ctrl while dragging to bypass the catch for that one drag. - Turn snapping off entirely in the canvas aids; the timeline reads the same switch, so the two can never disagree. The catch is eight pixels wide whatever the zoom, so it feels the same distance away when a whole minute is on screen and when ten frames are. ## Audio tracks and the inspector The header's Add audio picker lists the store's audio entries and appends one as a video-level music track. Tap an audio lane to open the audio inspector on the right: volume, fade in, fade out, loop, trim, and, for a sound effect, its start. Tracks reorder and remove there too. Multiple tracks layer and mix through the same `amix` graph a hand-written Fluvie composition uses. ## Scrubbing One clock drives everything. The playhead crosses scene boundaries, the canvas shows the exact frame, and Space always toggles playback. The slide stepper seeks scene starts on the same clock, and interactive editing targets the scene under the playhead, exactly like slides mode on that slide. ## Export to MP4 Export lives in the top bar's Export menu, in both modes. - **Desktop**: the deck renders through fluvie's capture loop and your local FFmpeg, into a file you pick. The progress dialog follows the capture and encode phases. - **Web**: the deck renders fully in the browser through ffmpeg.wasm, with audio enabled, and lands as a download. The page must ship the `FluvieFfmpeg` bridge in `index.html` (vendor the wasm files with `apps/slides/tool/fetch_ffmpeg.sh`). Without the bridge the menu entry stays visible but disabled and names what is missing; there is never a dead button. ffmpeg.wasm is much slower than native FFmpeg, so long renders belong on the desktop. Both paths feed the same spec-built `Video`, so the mix you authored in the lanes is the mix in the file: every track's volume, fades, trim, and start become the same FFmpeg filter graph on either platform. The same menu also exports still forms of the deck: numbered PNGs, or one PDF with a page per slide at the deck's canvas size, both rendered from each slide's settled final state. ## Where to next - [The Effects tab](editor-effects.md): stack, tune and keyframe the effects whose rows and diamonds you see here. - [Media and bundles](editor-media.md): where imported bytes live and how a deck travels with them. - [The timeline](editor-timeline.md): the slides-mode lens on time, per slide and per element. - [Audio and captions](../guides/audio-and-captions.md): the `Audio` model the lanes and inspector edit. # Workspaces Quick, Edit, Colour, Audio and Deliver show different controls over the same project. Switching workspaces preserves the timeline, selection, undo history and saved render data. Your workspace and panel sizes are personal preferences stored beside the editor layout. Drag the vertical divider above the timeline to change its height. The timeline spans the window. Drag the column dividers to resize the library, stage and inspector; sizes restore when the editor opens again. Quick groups the timeline into Picture and Audio, shows three tools and six essential inspector controls, and offers Draft, Share and Master exports. Its first-project hint advances when you import, place, trim and successfully export. Still-image projects can proceed to export without a source trim. Dismiss the hint at any time; it is hidden outside Quick. Edit exposes numbered lanes and the full editing tools. Colour and Audio open their corresponding inspector tabs. You can still change tabs yourself. Deliver shows the render queue and advanced encoder controls. The File, Edit, View, Clip, Sequence, Window and Help menus use the same commands and keyboard bindings as the command palette. Numeric controls accept arithmetic, arrow stepping and label scrubbing. A field's unit controls whether it shows frames, seconds, timecode, percentages or degrees. Timecode uses the project's frame rate; unsupported drop-frame notation is rejected instead of silently reinterpreted. See [Media bin](editor-media-bin.md), [NLE timeline](editor-nle-timeline.md), [Colour](editor-colour.md), [Audio](editor-audio.md) and [Delivery](editor-delivery.md) for the controls in each workspace. # Create a video from local assets Start with an ordinary Flutter project. Keep your composition in Dart, drop your photos, clips, soundtrack, and story notes into `assets/`, then preview and render the same `Video`. ```sh flutter create cat_story cd cat_story flutter pub add fluvie dart pub global activate fluvie_cli ``` For an unpublished checkout, [activate its CLI directly](installation.md#use-an-unpublished-checkout) with `dart tool/activate_cli.dart` from that repository, then use `fluvie init` instead of `flutter pub add fluvie`. The source-installed CLI discovers its checkout automatically; `--fluvie-path` selects another one. Run `flutter pub get` in your project after initialization. An existing Flutter project works too. `fluvie init` adds a starter composition and merges its dependency and asset setup into the existing project. ## Give the assistant a clear starting point Keep related files together. Nested asset directories are supported: ```text assets/ cat/playing.mp4 cat/sleeping.jpg music/song.mp3 story.txt lib/ my_video.dart ``` Ask your coding assistant: > Create a video about the life of my cat using the files under assets/. Use > Fluvie and write readable Flutter code in lib/my_video.dart with a top-level > Video build(). Read story.txt for the narrative, inspect the real media before > choosing timing, preview the result, and render the MP4. Use `fluvie docs --context` to give an assistant the installed version's offline authoring guide. The [AI and MCP guide](../guides/ai-and-mcp.md) explains the documentation tools and built-in generation workflow. An assistant should use actual asset filenames and supported APIs rather than inventing either. ## Read text files and inspect media Story text files are authoring input. Read the notes before choosing captions or scene order; they do not become a soundtrack automatically. Inspect clip duration, dimensions, and embedded audio before choosing a trim. Keep original filenames in the code so an error identifies the asset that needs attention. ```sh fluvie doctor --json fluvie assets ./assets --json fluvie validate ./lib/my_video.dart --json ``` The inventory is read-only by default. Add `--download-tools` to install missing native tools explicitly; render and preview provision them automatically. It recurses through nested folders and reports original paths, media facts, bounded text previews, and declared font families. It does not invent a story or infer the content of a clip. Validation reads the original Dart file, so its relative imports keep working; it never executes the code. Validation warns about obvious wall-clock and unseeded random reads in video construction with `nondeterministic_video`. Derive animation from the authored frame and use stable seeds or fixed input dates. The [frame-builder guide](../advanced/frame-builder.md) explains the rule and its limits. For a built-in model, select reusable visual and story evidence: ```sh fluvie assets ./assets --contact-sheets \ --catalog-out build/fluvie/assets.catalog.json fluvie generate "the life of my cat" --catalog build/fluvie/assets.catalog.json \ --context-file assets/story.txt --dart-out lib/my_video.dart --no-render ``` The catalog binds observations and pictures to source hashes; local sheet creation does not upload them. Add `--image-evidence` only when you want your selected vision provider to inspect the sheets. See [asset evidence](../guides/asset-evidence.md) for timestamped observations and transcripts. ## The composition is ordinary Flutter code This example expects the filenames shown above; change them to your own files. The music and clip can be edited independently, and Flutter's `Align`, `Text`, `Padding`, and layout widgets work inside the scene. ```dart import 'package:flutter/material.dart' hide Animation, Clip, Image, Tween; import 'package:fluvie/fluvie.dart'; /// A small story using files in the project's assets folder. Video build() => Video( size: VideoSize.hd, poster: 1.seconds, audio: const [Audio.music('assets/music/song.mp3', volume: 0.3)], scenes: [ Scene( duration: 4.seconds, children: [ Clip.asset('assets/cat/playing.mp4', fit: BoxFit.cover, audio: const ClipAudio.muted()), const Align( alignment: Alignment.bottomCenter, child: Text('A day in the life of my cat', style: TextStyle(fontSize: 64)), ).animate([Animation.fadeIn()]), ], ), ], ); ``` The scene defines its own duration. `Video` calculates the total, and timing uses seconds or frames without a second animation clock. Explicitly mute a clip when its original audio should not compete with your soundtrack. ## Preview and render ```sh fluvie preview ./lib/my_video.dart fluvie render ./lib/my_video.dart ``` The default output is `build/fluvie/my_video.mp4`. The authored `Video` supplies its size, FPS, duration, export mode, and poster. With no export mode, Fluvie uses high-quality MP4. Override a choice when needed: ```sh fluvie render ./lib/my_video.dart --out cat_story.mp4 fluvie render ./lib/my_video.dart --frames 30 --quality low fluvie render ./lib/my_video.dart --machine ``` Fluvie prepares its capture harness and tooling in a user cache outside your project. You maintain the composition and assets; you do not add a capture test, registry, or rendering-only dependencies. Flutter may create its normal ignored build output. The CLI provisions its native encoding tools when needed. `--machine` emits JSON-line progress and a final artifact event with the output and receipt paths. The receipt compares actual encoded facts with the requested output. A failed verification exits unsuccessfully and keeps a diagnostic receipt for inspection. For subsequent renders, local inputs invalidate cached frames automatically. Use `--cache-key ` for reliably identified external inputs, or `--no-cache` when their identity can change without being tracked. The retained `my_video.render.json` records source/input fingerprints, tools, settings, actual encoded media metadata, output SHA-256, and any authored poster identity for review. Preview prints a local browser URL. Pass `-d chrome` to open Chrome, or use a Flutter desktop device when you need one. The CLI supplies its local native media bridge automatically, so browser preview can use formats beyond the browser's own codec support. Click the sound control to enable audio. Independently hosted browser rendering has different codec limits; see the [web rendering guide](../guides/on-device-web-rendering.md). To embed the player in your own Flutter app: ```dart /// Embeds the authored composition in your own Flutter app. Widget preview() => const VideoPreview.builder(builder: build); ``` ## Make changes easy to review ```sh fluvie review ./lib/my_video.dart --determinism --json fluvie review ./lib/my_video.dart --render --strict-decode --json fluvie edit ./lib/my_video.dart "make the closing title warmer" --no-render ``` Review combines diagnostics, mounted facts and representative captures. `--determinism` compares reverse seeks and a fresh mount, invoking the entry function again to check factory and widget initialization. Inspect its sampled pictures as well as the diagnostics; a passing check does not judge the story or prove every frame or platform identical. A strict render review also decodes the complete encoded result. A Dart edit preserves unchanged code and keeps the original in a `.fluvie.bak` file after validation. See [reviewing a video](../guides/reviewing-a-video.md) for the report and its limits. Build one function per scene when the story grows. Use meaningful names, explicit trims, and comments explaining editorial choices. Keep generated output in `build/` and keep authored Dart and original assets under version control. A later edit should change the composition rather than requiring a manual timeline operation. For errors, run the same command with `--verbose`. `--keep-temp` retains the capture sandbox. Advanced hosts can use `--renderer` for a custom renderer factory or `--harness` for a complete custom Flutter test; the [export guide](../guides/exporting-your-video.md) describes these escapes. ## Where to next - [Asset evidence](../guides/asset-evidence.md): give an assistant source-bound observations. - [Review a video](../guides/reviewing-a-video.md): inspect samples and verify output. - [AI and MCP](../guides/ai-and-mcp.md): choose a provider or teach an external assistant. # Core concepts Five ideas carry every Fluvie video: `Video`, `Scene`, `Time`, `.animate`, and `Defaults`. Lesson 01 shows four of them in eighteen lines: ```dart Video lesson01Video() { return Video( size: VideoSize.square, poster: 1.seconds, scenes: [ Scene( duration: 4.seconds, background: Background.gradient(const [Color(0xFF1A2980), Color(0xFF26D0CE)]), children: [ const Text( 'Hello, Fluvie', style: TextStyle(color: Colors.white, fontSize: 72, fontWeight: FontWeight.bold), ).animate([Animation.fadeIn(), Animation.pop()]), ], ), ], ); } ``` ## Video and Scene A `Video` is a list of `Scene`s played back to back. The video owns the canvas size and the frame rate; each scene owns its duration and its children. Scene children sit on a centered, canvas-filling stack, so a bare `Text` reads well without any layout code. Size presets cover the common formats: `VideoSize.square`, `VideoSize.reels` (and its alias `VideoSize.story`), `VideoSize.hd`, `VideoSize.fourK`. ## Time You write times symbolically and Fluvie resolves them to frames: - `4.seconds`, `300.ms`, `18.frames` are absolute. - `0.3.relative` means 30 percent of the enclosing window (a scene, or an element's `.show` window). The frame is the only clock. There is no wall time anywhere, which is why renders are reproducible and cacheable. ## .animate `.animate([...])` works on any widget and takes a list of presets such as `Animation.fadeIn()`, `Animation.pop()`, `Animation.slideFadeIn()`. Each preset accepts `duration`, `delay`, `ease` or `spring`, a `Trigger`, and a `Stagger` for multi-child targets. You declare the motion; placement happens during resolution. ## Defaults `Defaults` set shared timing once. The cascade is element over scene over video over package, per field. Lesson 02 pins one duration for everything in the scene: ```dart Scene( duration: 5.seconds, motionDefaults: const Defaults(duration: Time.frames(18)), background: Background.color(_ink), children: [ ``` Every animation inside that scene now runs 18 frames unless it says otherwise. ## The frame is the only clock Capture is headless: there is no wall-clock and no async work inside a frame, so a render is reproducible enough for golden tests, frame caching, and batch rendering. Effects pull randomness from a seed, so the same seed repeats. ## Where to next - [Layouts](../guides/layouts.md): plain Flutter layout plus `Box` and `PhotoFrame`. - [Backgrounds and gradients](../guides/backgrounds-and-gradients.md): fills, textures, and `gradientShift`. - [Timing and triggers](../guides/timing-and-triggers.md): anchors, `Trigger.whenEnds`, and `.show` windows. - [Scenes and transitions](../guides/scenes-and-transitions.md): crossFade, wipe, overlap, shared elements, and the `Camera`. # Installation Fluvie turns a Flutter widget tree into a real MP4. You write the video as code, preview it like an app, and render it with the Fluvie CLI and FFmpeg. In a hurry? `fluvie init` scaffolds a project for you: a composition file, an `assets/` folder, and a pubspec. See [Start a project](start-a-project.md). To set it up by hand, read on. Add the package to your `pubspec.yaml`: ```yaml dependencies: fluvie: ^0.3.1 ``` Then fetch it: ```sh flutter pub get ``` ## What you need - Flutter 3.44 or newer with Dart 3.12 or newer. - Native media tools are automatic. Rendering and local media preview provision a pinned FFmpeg/ffprobe pair in a user cache when needed. Warm it with `fluvie ffmpeg install`, or select your own pair with `--ffmpeg`/`--ffprobe`. See [Managing FFmpeg](../guides/managing-ffmpeg.md). Check Flutter: ```sh flutter --version ``` ## Use an unpublished checkout Activate the CLI directly from the repository root without bootstrapping the whole workspace: ```sh cd /path/to/fluvie dart tool/activate_cli.dart ``` The installer prepares a persistent external CLI host using the checkout's packages, then activates `fluvie`. It keeps authoring setup independent of the workspace's unrelated app dependencies. Rerun it after dependency changes, or after CLI source changes when the installer uses its Windows copy fallback. Linked package source stays live. The default host is under the Fluvie user cache's `cli//fluvie_cli/` directory. `--prepare-only` prints the prepared host path without global activation; `--install-dir ` chooses its external parent. `--offline` uses an already resolved package graph without fetching dependencies. Point a fresh or existing Flutter project at the same unpublished packages: ```sh cd /path/to/cat_story fluvie init flutter pub get ``` The source-installed CLI discovers its own checkout automatically. Use `--fluvie-path /path/to/fluvie` to select another checkout explicitly. For a published release, install the CLI with `dart pub global activate fluvie_cli` and use normal pub dependencies. ## Develop the whole repository The repo is a Melos workspace. To work on its apps and package tests, bootstrap it once: ```sh melos bootstrap ``` The gallery example app in `examples/gallery/` is the lesson gallery and inspector. Run it from the repo root so its render button can find the CLI. ## Previewing in a browser `fluvie preview` runs a composition live, with hot reload: ```sh fluvie preview ./lib/my_video.dart ``` The default prints a local browser URL with hot reload. Pass `-d chrome` to open Chrome, or `-d ` for a Flutter desktop app. The CLI provides its local native media bridge automatically; it can decode formats the browser alone does not support. Enable sound through the preview control. Rendering to a file does not need a preview. The headless render pipeline (the CLI, the API, and the Docker image) produces the final frames correctly on its own, including loading the real fonts so text never falls back to the boxy test font. ## Where to next - [Start a project](start-a-project.md): scaffold a project with `fluvie init`. - [Your first video](your-first-video.md): build and render lesson 01. - [Core concepts](core-concepts.md): the ideas behind every Fluvie video. - [Managing FFmpeg](../guides/managing-ffmpeg.md): how Fluvie finds, downloads, and pins FFmpeg. # Start a Fluvie project A Fluvie project is a directory holding a composition file, an `assets/` folder, and a `pubspec.yaml`. It can also live in an existing Flutter app. You maintain the composition; the CLI manages its preview app and capture host. `fluvie init` scaffolds the composition setup: ```sh dart pub global activate fluvie_cli fluvie init --dir my_reel cd my_reel flutter pub get ``` For unpublished Fluvie changes, use the [source-checkout installer](installation.md#use-an-unpublished-checkout), then run `fluvie init` in your Flutter project. It discovers that checkout automatically; `--fluvie-path /path/to/fluvie` selects another one explicitly. ## What you get Your composition and normal project configuration: ```text my_reel/ ├── pubspec.yaml # the project: a name, and a dependency on fluvie ├── analysis_options.yaml # normal Flutter analysis; optional Fluvie lints ├── lib/ │ └── example_video.dart # your composition ├── assets/ # your images, clips, audio, fonts └── .gitignore ``` `init` is not interactive and it never runs `flutter create`. It writes only new files and merges the required dependency and asset setup into an existing Flutter project. Your app entry point and other dependencies remain yours. The flags: - `--name ` names the composition file. It defaults to `example_video`, so you get `example_video.dart`. - `--dir ` picks the directory to scaffold into. It defaults to the working directory. - `--force` overwrites files that already exist. - `--with-ai` adds the optional AI authoring package. - `--with-lints` adds Fluvie's custom timing and layering lints. - `--fluvie-path ` uses a local Fluvie checkout while developing it. ## The composition A composition file exposes a top-level `Video build()`. That is the only contract: `fluvie preview` and `fluvie render` call it to get your `Video`. Name the function something else and pass `--entry `. Keep it under `lib/`. A preview runs from a generated app that lives outside your project, and it can only reach your composition through a `package:` URI, which only a file under `lib/` has. A composition elsewhere still renders, but it cannot be previewed. The file opens with two imports. Fluvie's `Animation`, `Clip`, `Image`, and `Tween` replace Flutter's, so hide those four: ```dart import 'package:flutter/material.dart' hide Animation, Clip, Image, Tween; import 'package:fluvie/fluvie.dart'; ``` Then a `Video` of `Scene`s. The starter is one square scene, a gradient background, and a title that fades and pops in. You never type a frame number. [Your first video](your-first-video.md) walks the body line by line. ## Preview it `fluvie preview` runs your composition live, with hot reload. Edit the file, save, and the preview redraws: ```sh fluvie preview ./lib/example_video.dart ``` Preview prints a local browser URL by default. `-d chrome` opens Chrome; `-d ` selects a Flutter desktop device. The CLI provides a local native media bridge for browser preview, including clip decoding and audio. Browser sound requires a user gesture. Native encoding tools are managed automatically. The preview app is generated for you and cached in `~/.cache/fluvie/preview/`, outside your project. Your project stays a composition file, an `assets/` folder, and a pubspec. ## Render it `fluvie render` takes the file directly: ```sh fluvie render ./lib/example_video.dart ``` The CLI prepares its capture harness and rendering dependencies in an external user cache, captures every frame with Flutter, then encodes the file. The default output is `build/fluvie/example_video.mp4`. You do not need FFmpeg installed: the first render downloads a pinned build and caches it. See [Managing FFmpeg](../guides/managing-ffmpeg.md). ## Assets Drop images, clips, audio, and story notes anywhere under `assets/`. Nested directories are discovered automatically. Original Flutter asset and font declarations remain available; rendering does not replace your asset block. This is managed for you because Flutter enumerates a declared asset directory non-recursively. An `assets/` entry alone bundles only the files sitting directly in it, and `assets/images/logo.png` goes silently missing at runtime with no build error. Fluvie discovers each subdirectory that holds files when preparing its render resources. Declare font families in the normal Flutter `fonts:` section. ## Where to next - [Create from local assets](authoring-with-assets.md): the fresh Flutter project and AI workflow. - [Your first video](your-first-video.md): a line-by-line tour of the starter. - [Core concepts](core-concepts.md): Video, Scene, Time, animate, Defaults. - [Exporting your video](../guides/exporting-your-video.md): formats, quality, and the full `fluvie render` flag list. - [AI and MCP](../guides/ai-and-mcp.md): have an assistant write real Fluvie code. # Your first video You describe what the video is. Fluvie computes when everything happens. Lesson 01 is the smallest complete example: one scene, one background, one animated title. Start with two imports. Fluvie's `Animation`, `Clip`, `Image`, and `Tween` replace Flutter's, so hide those four: ```dart import 'package:flutter/material.dart' hide Animation, Clip, Image, Tween; import 'package:fluvie/fluvie.dart'; ``` Now the whole video: ```dart Video lesson01Video() { return Video( size: VideoSize.square, poster: 1.seconds, scenes: [ Scene( duration: 4.seconds, background: Background.gradient(const [Color(0xFF1A2980), Color(0xFF26D0CE)]), children: [ const Text( 'Hello, Fluvie', style: TextStyle(color: Colors.white, fontSize: 72, fontWeight: FontWeight.bold), ).animate([Animation.fadeIn(), Animation.pop()]), ], ), ], ); } ``` ## What each line does - `Video` is the root. `VideoSize.square` makes a 1080 by 1080 canvas at the default 30 fps. - `poster: 1.seconds` names the frame that previews and thumbnails show. - `Scene` holds 4 seconds of content. Its children sit on a centered canvas. - `Background.gradient` fills the scene behind everything else. - `.animate([...])` attaches motion to any widget. The fade and the pop both start when the scene starts; you never type a frame number. In your own project the builder is named `build`: a composition file exposes a top-level `Video build()`, and that is what the CLI calls. The gallery names each lesson so thirteen of them can live side by side. ## Render it Point the CLI at the file: ```sh fluvie render ./lib/my_video.dart ``` The CLI captures every frame, then FFmpeg encodes `build/fluvie/my_video.mp4`. From this repo, render the lesson by its key instead, because the gallery keeps a registry: ```sh dart run packages/fluvie_cli/bin/fluvie.dart render 01_hello_video --out build/01_hello_video.mp4 ``` ## Preview it Watch it live, with hot reload: ```sh fluvie preview ./lib/my_video.dart ``` Edit the file, save, and the preview redraws. In this repo you can also open the gallery app and pick "Hello, video" in the lesson list: scrub the slider to step through frames, and the timeline pane shows when each animation plays. ## Where to next - [Start a project](start-a-project.md): scaffold this as a project with `fluvie init`. - [Core concepts](core-concepts.md): Video, Scene, Time, animate, Defaults. - [Timing and triggers](../guides/timing-and-triggers.md): make elements react to each other. # AI and MCP There are three ways to let a model direct Fluvie: 1. **Author from a prompt.** Describe the video you want; a model writes a Fluvie `VideoSpec`; the CLI writes readable Dart and renders that composition. This is the [`fluvie_ai`](https://pub.dev/packages/fluvie_ai) package and the `fluvie generate` command. 2. **Teach an assistant Fluvie.** Run the MCP server in docs mode and a coding assistant like Claude can search and read the Fluvie documentation as it writes your composition. No render backend needed. 3. **Hand Fluvie to an assistant.** Run the server in build mode and the assistant can author and render videos for you, end to end, from your editor or chat. For prompt-to-spec authoring, the model runs at authoring time. The resulting spec records the composition and timing; rendering it needs no authoring model. Generated-media elements can still call their configured generator during resource preparation. Keep their resolved assets to replay that input. The CLI makes Dart the default editable artifact and retains the authoring spec beside the output. Commit the composition and selected assets, diff edits, and render again. See [authoring with specs](authoring-with-specs.md) for the companion format. ## Bring your own key For a coding assistant working in a local Flutter project, start with [Create a video from local assets](../getting-started/authoring-with-assets.md). `fluvie docs --context` prints an offline guide matched to the installed CLI. The MCP server also ships the canonical documentation inside its binary; docs mode needs no repository checkout, website access, or special docs directory. Set `FLUVIE_DOCS_DIR` to an existing Markdown directory only when you want to override that corpus. A missing or empty override fails at startup with a clear error. Public agents can discover the same corpus at [llms.txt](https://docs.fluvie.dev/llms.txt) and [llms-full.txt](https://docs.fluvie.dev/llms-full.txt). We do not run an unmetered public endpoint for your renders. The hosted demo gives you a small free quota to try; for anything beyond that you bring your own key, or run a local model with no key at all. Your own key selects your provider account; it does not keep prompts from that provider. A local model lets you keep authoring requests on your machine. A server or proxy receives the requests you route through it. | Provider | `FLUVIE_AI_PROVIDER` | API key | Sees rendered frames | | --- | --- | --- | --- | | Claude (default) | `claude` | `ANTHROPIC_API_KEY` | yes | | Gemini | `gemini` | `GEMINI_API_KEY` | yes | | Mistral | `mistral` | `MISTRAL_API_KEY` | with a vision-capable model | | Ollama (local) | `ollama` | none | with a vision-capable model | | Variable | Default | What it does | | --- | --- | --- | | `FLUVIE_AI_PROVIDER` | `claude` | Select `claude`, `gemini`, `mistral`, or `ollama`. | | `FLUVIE_AI_MODEL` | provider's default model | Override the model sent to the provider. | | `FLUVIE_AI_ENDPOINT` | provider's default endpoint | Use an absolute HTTP(S) request URL, including its full path, for a local server or compatible proxy. | Pass `--provider ` to `generate`/`edit` to override `FLUVIE_AI_PROVIDER` for a single run; API keys always come from the environment. An endpoint override keeps the selected provider's request format and API-key requirements. For example, Ollama accepts `http://127.0.0.1:11434/api/chat`; a base origin or relative path does not identify the full request endpoint. Explicit image evidence is bounded to four references, at most 4 MiB each, before provider transport. Single-image adapters receive a labeled composite when several references are selected. Mistral and Ollama transport the original selected images; the configured model must support images. These are transport capabilities, not a guarantee that every model can interpret a picture. ## Author from a prompt Install the CLI, set a provider and key, then generate: ```sh dart pub global activate fluvie_cli export FLUVIE_AI_PROVIDER=claude export ANTHROPIC_API_KEY=sk-... fluvie generate "a 6s vertical title card, dark gradient, fade-in headline" \ --spec-out promo.fluvie.json --dart-out lib/promo.dart ``` Generation always writes Dart before capture. With no `--dart-out`, it selects `lib/generated_video.dart`, then a numbered filename when that file already exists. `--no-render` writes the code and spec for review without encoding. Edit that Dart directly to preserve your custom widgets, imports and comments: ```sh fluvie edit lib/promo.dart "make the headline yellow" --no-render fluvie review lib/promo.dart --json ``` Dart edits use bounded exact-text patches with structural and compiler-feedback repairs, validate a sibling candidate with its relative imports intact, and mount it for inspection before replacing the original. Successful edits retain the original as `.fluvie.bak`. Validation failure leaves the original source unchanged. `--dart-out` and `--spec-out` are for spec edits, not in-place Dart edits. You can still refine a saved spec. Multimodal spec edits can include the current rendered frame so the provider sees what it is changing: ```sh fluvie edit promo.fluvie.json "make the headline yellow" --dart-out lib/promo.dart ``` Render a spec again with no model call at all: ```sh fluvie render --spec promo.fluvie.json ``` `--out` optionally names the video; otherwise output goes to `build/fluvie/`. `--dart-out` chooses the native composition filename and `--no-render` lets you review it before capture. Use `fluvie assets ./assets --json` for original filenames, media facts, fonts, and bounded story notes. Missing native tools are reported without downloading; `--download-tools` opts into warming them for inventory. Built-in generation inventories the project's `assets/` by default. Point `--assets ` at a different root, and provide narrative text through `--context ""` or `--context-file assets/story.txt` (repeatable, up to four 8,192-byte files). It supplies up to 100 sorted factual assets and at most 64 KiB of total context. It does not implicitly read story text or infer visual content from filenames. A coding assistant can inspect files with its own tools and pass the facts or narrative it selects. A reusable catalog adds timestamped observations, transcripts and local contact sheets; see [asset evidence](asset-evidence.md). ```sh fluvie generate "the life of my cat" --context-file assets/story.txt \ --dart-out lib/cat_story.dart --spec-out cat_story.fluvie.json --no-render fluvie validate lib/cat_story.dart --json fluvie preview lib/cat_story.dart fluvie render lib/cat_story.dart --machine ``` ## Flutter-style (real code) generation `fluvie generate` already writes Flutter widget code. An external coding assistant can author the full Flutter surface directly after reading the offline docs. For a fresh project, the assistant reaches for the `init_project` tool, which returns the starter composition, the dependencies, and the `fluvie init` command to scaffold a project. What you get back is a composition file exposing a top-level `Video build()`; preview it with `fluvie preview ./.dart` and render it with `fluvie render ./.dart`. See [Start a project](../getting-started/start-a-project.md). Before rendering generated code, the assistant can check it with `validate_code`. That runs static analysis only (it never executes the code) and returns the diagnostics, so a typo or a disallowed import is caught before a render starts. ## Generate editable Dart from a prompt The demo Playground turns a prompt into editable Flutter-style Dart. You type a prompt in the AI Assistant, the browser sends only that text to the Fluvie server, and the server authors a `VideoSpec` with its configured model. The server then prints that spec to a Dart `Video build()` snippet and returns it. The snippet lands in the editor, where you tweak it and press Render. The browser never holds a provider API key in the default server-configured flow, because the model runs server-side. A deployment may still require its own Fluvie authentication token. Two pieces make this work, and you can use either on its own: - The spec-to-Dart printer is `printVideoSpecJson(Map)` in [`fluvie_cli`](https://pub.dev/packages/fluvie_cli). Give it a serialized `VideoSpec`, get back the editable snippet. It is a pure transformation, so it never calls a model or renders. It is `@experimental` while the printed shape settles. - The same transformation is the `spec_to_dart` MCP tool below. The printed Dart is the same code the Playground shows. It uses the public barrel only, so it compiles in a real project. See [the Playground](playground.md) for the editor and [authoring with specs](authoring-with-specs.md) for the spec format. ## Run a local model (no key) [Ollama](https://ollama.com) runs a model on your machine, so there is no API key or per-request provider fee. After downloading a model, you can author offline: ```sh ollama pull llama3.1 export FLUVIE_AI_PROVIDER=ollama export FLUVIE_AI_MODEL=llama3.1 export FLUVIE_AI_ENDPOINT=http://127.0.0.1:11434/api/chat fluvie generate "a calm 4s loop, soft gradient, one word fading in" --out loop.mp4 ``` ## The Fluvie server [`fluvie_server`](https://pub.dev/packages/fluvie_server) is one binary that hosts everything: the [render API](rendering-on-a-server.md), an [MCP](https://modelcontextprotocol.io) server, and a documentation helper. Turn each part on or off with an environment variable, so you install one thing instead of wiring up three. | Variable | Default | What it does | | --- | --- | --- | | `FLUVIE_ENABLE_API` | `true` | Mount the render API at `/v1`. | | `FLUVIE_ENABLE_MCP` | `true` | Enable the MCP server (`/mcp` and `--stdio`). | | `FLUVIE_ENABLE_DOCS` | `true` | Enable the documentation helper. | | `FLUVIE_MCP_MODE` | `build` when a backend exists, else `docs` | What the MCP tools cover. | | `FLUVIE_MCP_TOKEN` | unset | Bearer token required on `/mcp`. | ### Two MCP modes **Docs mode** is the documentation helper. It exposes the docs tools and the schema, needs no render backend, and is perfect for a coding assistant that writes Fluvie code for you: | Tool | What it does | | --- | --- | | `get_authoring_context` | Start with the versioned local assets and Flutter authoring guide. | | `list_docs` | List every documentation page. | | `search_docs` | Full-text search the documentation. | | `get_doc` | Read one page in full. | | `init_project` | Start a project or add a composition in real Flutter/Dart code. | | `get_video_spec_schema` | Fetch the spec schema to author against. | **Build mode** adds the render and authoring tools on top, so the assistant can make the video, not just write the code. It needs a render backend (this server's own API, or a remote one via `FLUVIE_API_URL`): | Tool | What it does | | --- | --- | | `generate_video` | Author from a prompt and render. Returns the download URL and the printed Dart `code`. | | `edit_video` | Refine an existing spec with a plain-language change. Returns the download URL and the printed Dart `code`. | | `spec_to_dart` | Convert a `VideoSpec` (JSON) into an editable `Video build()` snippet. Pure: no model, no render. | | `validate_code` | Statically check a `Video build()` snippet before rendering. | | `render_video` | Render a spec you already have. | | `render_composition` | Render a registered composition by key. | `generate_video` and `edit_video` now return that printed Dart `code` next to the download URL, so the assistant can hand you editable widget code and the finished video in one reply. `spec_to_dart` does only the conversion, for when you have a spec and want the code without a render. ### Run it ```sh dart pub global activate fluvie_server # Docs helper over stdio, for a local coding assistant (no backend needed): FLUVIE_ENABLE_API=false fluvie_server --stdio # The full server over HTTP (render API + MCP + docs on one port): fluvie_server ``` ### Connect Claude Code ```sh # local docs helper, over stdio claude mcp add fluvie -- env FLUVIE_ENABLE_API=false fluvie_server --stdio # remote build server, over HTTP claude mcp add --transport http fluvie https://mcp.fluvie.dev/mcp \ --header "Authorization: Bearer $FLUVIE_MCP_TOKEN" ``` Then ask in plain language: "make me a 6 second vertical title card on a dark gradient, fade the headline in." In build mode the assistant calls `generate_video` and replies with a link; in docs mode it reads the docs and writes the composition for you. ### Connect Claude Desktop Add the server to your Claude Desktop config: ```json { "mcpServers": { "fluvie": { "command": "fluvie_server", "args": ["--stdio"], "env": { "FLUVIE_API_URL": "http://localhost:8080", "FLUVIE_API_TOKEN": "your-render-token" } } } } ``` ## Self-host everything The [render API guide](rendering-on-a-server.md) covers the Docker images in full. The short version: one image, one env file. ```sh cp deploy/env/server.env.example deploy/env/server.env # set API_TOKEN, and a provider key for server-side AI docker compose -f deploy/docker-compose.yml up --build ``` That serves `/v1` (render API), `/mcp` (MCP), and `/v1/docs` (docs) on one port. If you set a provider key, `generate_video` and `edit_video` work end to end; if not, the server still renders specs and registered compositions and returns a clear error for prompt-based calls. For a tiny docs-only endpoint with no render toolchain, use the slim `fluvie-server-docs` image. ## Host server-side AI without overspending You can run the prompt path on your own key and still bound the cost. The hosted demo does this: generation runs on the operator's key, pinned to a cheap model, behind a per-IP rate limit and a daily quota. Pin the model with `FLUVIE_AI_MODEL`. A small model keeps each call cheap: ```sh export ANTHROPIC_API_KEY=sk-... export FLUVIE_AI_MODEL=claude-haiku-... # a cheap model for the public path ``` Then bound how often any one IP can spend your key. These apply to the LLM-cost path only (prompt and edit); spec and code renders are not limited: | Variable | Default | What it does | | --- | --- | --- | | `FLUVIE_AI_RATE_LIMIT` | `5` | Calls allowed per window, per IP. | | `FLUVIE_AI_RATE_WINDOW` | `1m` | Width of the sliding window. | | `FLUVIE_AI_DAILY_QUOTA` | `50` | Calls allowed per UTC day, per IP. | A request over either limit returns HTTP `429` with a `Retry-After` header that says how long to wait. Set a limit to `0` to switch that one check off. ## Where to next - [Authoring with specs](authoring-with-specs.md): the spec format and the Dart API. - [Rendering on a server](rendering-on-a-server.md): the server and its Docker images in full. - [`fluvie_server`](https://pub.dev/packages/fluvie_server) and [`fluvie_ai`](https://pub.dev/packages/fluvie_ai) on pub.dev. - [Server protocol](../reference/server-protocol.md): examples and tool arguments exported from the shipped registry. - [Review a video](reviewing-a-video.md): validate, inspect, sample and verify the generated composition. ## Inspect and share an authoring run [Authoring workspace](authoring-workspace.md) gives a human and an assistant the same native frame, review and export session. [Portable projects](portable-projects.md) preserve source, assets and dependency resolution for replay. [Authoring benchmarks](authoring-benchmarks.md) measure real model calls, preservation assertions and verified output separately from human visual review. Multiline CLI prompts are encoded losslessly before reaching Flutter’s test launcher. Compiler feedback uses the same transport, so line breaks and Unicode do not become test-file arguments. # Build a Fluvie video with an AI assistant Give a coding assistant a topic, the scenes you want, and a link to Fluvie's AI entry page. The assistant can use the Fluvie CLI and your project files directly; MCP is optional. ```text Create a video using Fluvie: https://fluvie.dev/for-ai Topic: [what the video is about] Scenes: [the scenes, in order] Use the quick path. Use assets in ./assets, write the composition to lib/my_video.dart, preview it, and render the MP4. ``` Use **quick** for direct creation. The assistant follows your scene direction, inspects available assets, makes reasonable choices for missing details, and builds and reviews the video. It asks only when an answer would materially change the result and cannot be inferred. Use **guided** when you want to approve the creative direction before rendering. The assistant checks the story beats, then the visual look, then a numbered storyboard with sound and transitions. You can approve or revise each checkpoint before it moves on to the next stage. The reusable [Fluvie video skill](https://fluvie.dev/skills/fluvie-video/SKILL.md) contains the agent workflow. In an installed Fluvie project, start with `fluvie docs --context` for version-matched offline guidance. The [AI and MCP guide](ai-and-mcp.md) explains the CLI, local models, and optional MCP tools. ## What the assistant should deliver - Readable Dart composition code that remains editable. - A preview and rendered video when the local project and required tools allow it. - A concise report of the output paths and checks performed. For real projects, ask the assistant to read story notes and inspect the actual media before choosing scene order or timing. The `fluvie assets` command reports file facts; it does not determine what an image or video depicts. # Animating elements Motion is one list. Attach `.animate([...])` to any widget and put each motion in the list. Fluvie works out when each one plays: ```dart const Text('Hello', style: _title).animate([ Animation.fadeIn(), Animation.pop(), ]); ``` The fade and the pop both start when the element's window opens. You never type a frame number. This page covers the presets, how to compose them, how to time them, and how triggers and stagger work. ## The preset menu Reach for a preset first. Each is one entry in the list: ```dart Animation.fadeIn(), // opacity 0 to natural Animation.slideFadeIn(from: Edge.left), // rise in while fading Animation.pop(overshoot: 1.2), // springy scale, peaks at 120% Animation.scaleIn(from: 0.7), // settle up from 70% Animation.blurIn(sigma: 16), // sharpen from a 16 px blur Animation.float(amplitude: 0.05), // bob forever, ambient ``` The presets fall into groups by when they play: - **Enter** plays at the start of the window: `fadeIn`, `slideIn`, `slideFadeIn`, `pop`, `scaleIn`, `blurIn`, `maskWipeIn`, and `gradientShift`. - **Exit** plays at the end of the window: `fadeOut`, `slideOut`, `slideFadeOut`, `scaleOut`, `blurOut`, `maskWipeOut`, and `color`. - **Ambient** plays the whole window, usually on a loop: `float`, `pulse`, `drift`, `spin`, `kenBurns`, and `parallax`. `scaleY` and `pulse(on:)` follow an audio band instead. - **Pixel post-effects** post-process the finished frame and always apply last: `grain`, `vignette`, `scanlines`, `chromatic`, `bloom`, `glitchIn`, `glitchOut`, `particles`, and `shader`. They sit in the same list. See [Shaders and effects](../advanced/shaders-and-effects.md). For the complete list, with exactly what each preset does and its defaults, see [Animation presets](../reference/animation-presets.md). ## Compose enter and exit Put an enter and an exit on the same element. Each preset knows its phase, so you do not say when: ```dart const Text('In and out', style: _line).animate([ Animation.slideFadeIn(), Animation.fadeOut(), ]); ``` The slide-fade plays at the start of the window. The fade-out plays at its end. List order does not set timing here; the phase does. ## Shape the timing Every preset takes the same tail of timing arguments. Set a `duration`, an `ease`, and a `delay`: ```dart const Text('Late and slow', style: _line).animate([ Animation.fadeIn( duration: const Time.seconds(0.6), // run for 600 ms ease: Ease.out, // decelerate into place delay: const Time.seconds(0.2), // start 200 ms after the trigger ), ]); ``` Leave them unset and the animation inherits the `Defaults` cascade. See [Defaults below](#defaults-set-the-feel-once). Pass a `spring` instead of a `duration` and `ease`, and the spring wins. Its settle time becomes the animation's span: ```dart const Text('Bouncy', style: _line).animate([ Animation.scaleIn(spring: Spring.bouncy), ]); ``` The springs are `Spring.gentle`, `Spring.snappy`, `Spring.bouncy`, and `Spring.stiff`, or build your own with `Spring(stiffness:, damping:)`. ## Trigger one animation off another By default an animation plays at its phase. A `Trigger` changes the start. Use `Trigger.whenEnds` to wait for an anchored element to finish: ```dart const Text('Then me', style: _line).animate([ Animation.slideFadeIn(at: Trigger.whenEnds(intro)), ]); ``` `intro` is an `Anchor` you put on another element with `.animate(..., anchor:)`. Move the anchored timing and this one follows. The full trigger vocabulary, including `whenStarts`, `previous`, `sceneStart`, and `beat`, lives in [Timing and triggers](timing-and-triggers.md). ## Stagger a group One animation can play across a group of children, offset child by child. Put the `stagger` on the container's animation: ```dart const Column( mainAxisSize: MainAxisSize.min, children: [ Text('One', style: _line), Text('Two', style: _line), Text('Three', style: _line), ], ).animate([ Animation.slideFadeIn(stagger: const Stagger.each(Time.frames(8))), ]); ``` `Stagger.each(gap)` offsets each child by a fixed gap. `Stagger.evenly(over:)` spreads the children across one span whatever their count. `Stagger.from(origin)` starts the wave from the center or an edge. ## Repeat a loop Loop an animation inside its span with `repeat`: ```dart Animation.pulse(repeat: const Repeat.forever(yoyo: true)), // breathe back and forth Animation.spin(repeat: const Repeat.times(2)), // two turns, then hold ``` `Repeat.forever()` loops until the window ends. `Repeat.times(n)` plays `n` cycles, then holds. `yoyo: true` plays every other cycle in reverse. ## Defaults set the feel once Set the duration and ease once on a `Scene`. Every animation inside inherits them unless it overrides: ```dart Scene( duration: const Time.seconds(5), motionDefaults: const Defaults(duration: Time.frames(18), ease: Ease.smooth), children: [ const Text('Inherits 18 frames', style: _line).animate([Animation.fadeIn()]), ], ); ``` Defaults cascade: animation over `Scene` over `Video` over the package. Each field falls through on its own, so a scene can pin the ease while the duration comes from the video. ## Build your own When no preset fits, animate from a `Keyframe`. `Animation.from` enters from it; `Animation.to` exits to it. Offsets are fractions of the element's own size: ```dart const Text('From the side', style: _line).animate([ Animation.from(const Keyframe(opacity: 0, x: -0.5, scale: 0.9)), ]); ``` For multi-stop motion use `Animation.keyframes([...])`, for a path use `Animation.along(path)`, and for a fully custom effect use `Animation.custom`. When no animation form fits at all, drive the pixels per frame with the [FrameBuilder escape hatch](../advanced/frame-builder.md). ## Keep the list stable The resolver must see the same animations on every frame. Inside a per-frame `Builder`, hoist the list to a field rather than writing a fresh literal each build. See [Performance](../advanced/performance.md#keep-animation-lists-stable). ## Where to next - [Timing and triggers](timing-and-triggers.md): the full trigger vocabulary and `.show` windows. - [Shaders and effects](../advanced/shaders-and-effects.md): grain, particles, parallax, and fragment shaders in the same animate list. - [Cheatsheet](../reference/cheatsheet.md): every preset on one page. # Give AI evidence about your assets Prepare a local catalog before asking a model to tell a story. The catalog binds media facts, selected observations and transcripts to the source file's SHA-256. Contact sheets record actual source frames and presentation times. Creating a catalog does not call an authoring provider or invent visual descriptions. ```sh fluvie assets ./assets --contact-sheets \ --catalog-out build/fluvie/assets.catalog.json fluvie generate "the life of my cat" \ --catalog build/fluvie/assets.catalog.json --context-file assets/story.txt \ --dart-out lib/cat_story.dart --no-render ``` The catalog and sheets remain in your project. Authoring verifies their source and image hashes before using them; replacing an asset requires rebuilding its catalog. A stale observation must not silently describe a different video. Each sheet records its selected frames, source times, layout and toolchain provenance. Its cache key covers those inputs and the source hash; generated filenames are an implementation detail. Read the sheet path and `cacheKey` from the catalog rather than deriving a filename from the video name or source hash. ## Supply observations with their certainty Write a JSON array of selected observations. Asset names are exact paths relative to the selected assets directory; times are source seconds. Keep facts separate from your interpretation through `observed`, `inferred` or `unknown` certainty. ```json [ { "asset": "cat/playing.mp4", "fromSeconds": 1, "toSeconds": 2.5, "text": "The cat jumps onto the sofa.", "certainty": "observed" } ] ``` Save this as `assets/observations.json` and select it explicitly: ```sh fluvie assets ./assets --catalog-out build/fluvie/assets.catalog.json \ --contact-sheets --evidence observations.json ``` Observations record the selected file's provenance. Text alone does not imply that the model viewed the footage. Uncertain cues should remain uncertain in the authored story. ## Bind timestamped transcripts Use an SRT or WebVTT file that already exists; Fluvie does not transcribe audio automatically. Both sides of `--transcript` are relative to the assets directory unless the caption path is absolute. Repeat it for several sources: ```sh fluvie assets ./assets --catalog-out build/fluvie/assets.catalog.json \ --transcript cat/playing.mp4=cat/playing.vtt ``` The catalog preserves source-second ranges, caption text and provenance. Selected transcript files and observations are bounded; excessively large inputs fail with an actionable message rather than entering an unlimited prompt. ## Let a vision provider inspect selected sheets Contact-sheet creation is local. Uploading them to your selected provider requires `--image-evidence` on authoring: ```sh fluvie generate "the life of my cat" \ --catalog build/fluvie/assets.catalog.json --image-evidence \ --context-file assets/story.txt --no-render ``` Authoring selects at most four verified sheets, each up to 4 MiB. Use a vision-capable provider and select an image-capable `--model` when needed; Ollama's default `llama3.1` model is text-only. Adapters preserve selected cues through their image transport, combining labeled sheets for a single-image provider API when necessary. These cues remain available during repair attempts; the model should not claim to see footage when only metadata or text was supplied. Your provider receives the selected pictures. Use your own local inspection and explicit observations when you want to keep pictures on your machine. ## Where to next - [AI and MCP](ai-and-mcp.md): provider setup and code-preserving edits. - [Create a video from local assets](../getting-started/authoring-with-assets.md): the complete workflow. - [Review a video](reviewing-a-video.md): examine authored timing and sample output. # Audio and captions Add a music bed, make the picture react to the bass, and burn in subtitles. Lesson 10 does all three in one scene. Start with the music bed: pass an `Audio.music` to `Video.audio` and the encoder mixes it under the frames. ```dart audio: const [ Audio.music(_track, fadeIn: Time.seconds(0.3), fadeOut: Time.seconds(0.5)), ], ``` That plays `_track` for the length of the video, fades it up over the first 0.3 seconds, and fades it out over the last 0.5 seconds. The picture stays the same; only the soundtrack changes. This page covers the three jobs audio does (it plays, it drives reactive motion, and it sits under captions), then closes with the annotation elements that point, frame, and label a scene. ## Audio tracks and mixing `Video.audio` takes a list of tracks. Each track is one `Audio`: ```dart Audio.music(path), // a looping or one-shot bed for the whole video Audio.sfx(path), // a one-shot effect placed at a moment ``` Both constructors take a `volume` that scales the track from 0.0 (silent) to 1.0 (full) and above. The rest depend on which track you build: - `Audio.music` adds `fadeIn` and `fadeOut` (each a `Time` that ramps the bed in or out), `trim` (a span of the source file, for example seconds 4 to 12), `loop` (repeat the file to fill the owner's duration), and `track` (an `Anchor` that tags the bed's beat grid for `Trigger.beat`). - `Audio.sfx` adds `at`, a `Trigger` that places the one-shot at a moment. Use `Trigger.at(Time)` for an absolute moment, or a beat or anchor trigger to pin it to the timeline. ### Typed sources Both constructors classify their string by shape: a URL, an absolute file path, or an asset key. When the audio has no path-shaped string, for example bytes imported in the browser that never touched disk, build the track over a typed `AudioSource` instead: ```dart Audio.musicSource(AudioSource.memory(bytes, debugLabel: 'bed.mp3'), loop: true), Audio.sfxSource(AudioSource.memory(bytes), at: const Trigger.at(Time.seconds(2))), ``` `Audio.musicSource` and `Audio.sfxSource` take the same fields as their string twins and carry the source verbatim; the encoder materializes the bytes itself. `AudioSource.asset`, `AudioSource.file`, and `AudioSource.network` work here too, when you already hold a typed source. A memory track's `source` reads as a stable `memory:` label for diagnostics; the encoder consumes the typed source, never that label. The encoder mixes the tracks. Each track becomes one input with its own trim, delay, volume, and fade filters, and the encoder sums them with `amix` into the final soundtrack. A clip's own audio (`ClipAudio.included`) joins the mix as one more track, so a video clip with sound layers under your music bed without extra work. One note on the encode. Audio bytes are per-machine: different FFmpeg builds encode the same mix to slightly different bytes, so the audio stream of your MP4 can differ between two machines. That is expected; validate a render by how it plays, not by byte-comparing files. ## Beat-reactive motion You can make elements react to the energy in a frequency band. The reactive presets read the audio's per-frame energy and drive a transform. Pulse a badge on the bass band: ```dart .animate([Animation.fadeIn(), Animation.pulse(on: AudioBand.bass, gain: 0.4)]); ``` Each frame the badge scales by `1 + bassEnergy * gain`, so it grows on the kick and settles between beats. `Animation.scaleY(on:, gain:)` does the same on the Y axis only, for a bar that stretches vertically with the band. `gain` scales how far the motion travels. Three bands are available: `AudioBand.bass`, `AudioBand.mid`, and `AudioBand.treble`. With no `track`, a reactive preset reads the first declared audible track. Pass a `track` to read one specific named audio track instead. Analysis follows that track's trim, placement and loop. The normalized source energies do not include its volume, fades, automation or the final mixed output; see [bounded audio analysis](../advanced/performance.md). The `Bars` element draws a frequency visualizer: ```dart Widget _bars() => const Bars(count: 32, gain: 1.2); ``` That paints 32 bars whose heights follow the band energy each frame. `count` sets how many bars, `gain` scales their height, and `band` picks which band to read (it defaults to `AudioBand.bass`). ### Audio is analysed before frame 0 The frame loop never touches live audio. Every reactive input is analysed once before frame 0. Before the first frame, Fluvie decodes the audio file, runs the beat detector and the band analyzer over it, and writes a per-frame band table. That table is one energy value per frame per band. It is cached by content hash, the same way media is. During the frame loop, a reactive preset is a pure lookup: it reads `bandTable.energyAt(frame, band)` and applies the transform. No decoding, no analysis, no live audio happens inside a frame. This is what keeps reactive renders stable. The same audio file produces the same band table, and the same band table paints the same on frame 0 and frame 200. ## Captions `Video.captions` burns a caption track over every scene. Read subtitles from an SRT file: ```dart captions: const Captions.fromSrt(_captions, style: _captionStyle), ``` Three constructors build a track: ```dart Captions.fromSrt(path), // parse a SubRip .srt file Captions.fromVtt(path), // parse a WebVTT .vtt file Captions.words(cues), // inline, per-word timed cues ``` `fromSrt` and `fromVtt` read and parse the file once before frame 0, the same pre-pass that resolves media. `words` needs no file: you pass `CaptionWord` cues with their own `at` times. Lesson 08 narrates its scenes word by word this way: ```dart captions: Captions.words( const [ CaptionWord('Type', at: Time.seconds(2.4)), CaptionWord('it', at: Time.seconds(3)), CaptionWord('out,', at: Time.seconds(3.4)), CaptionWord('then', at: Time.seconds(4.2)), CaptionWord('run', at: Time.seconds(6.4)), CaptionWord('it.', at: Time.seconds(7)), ], style: const CaptionStyle.tikTok(), ), ``` ### Styles `CaptionStyle` controls typography, the background and word highlights. For a small canvas, pass a custom style through `Captions.fromSrt(..., style:)`. Its background and highlight are Flutter `Color` values. The style belongs to the caption track; `Video` receives the track through `captions:`. The top/bottom placement presets cap their 64-pixel safe inset at one twelfth of the canvas's shorter side, so small canvases retain room for text. Custom positions keep their exact inset; opt into scaling with `adaptiveSafeArea: true`. Font sizes remain explicit, so choose a readable style for your output size. ```dart /// A compact caption style for a small video canvas. const benchmarkCaptionStyle = CaptionStyle( textStyle: TextStyle(fontSize: 14, color: Colors.white), background: Color(0x80000000), highlight: Colors.white, ); ``` Three presets also ship: ```dart CaptionStyle.subtitle(), // a plain, readable lower-third band CaptionStyle.tikTok(), // bold words that pop in one at a time CaptionStyle.karaoke(), // a line that highlights each word as it lands ``` The word-pop in `tikTok` reuses the same stagger and reveal you use elsewhere, so the words enter on their own cues. The `karaoke` style fills each word's color as its timestamp arrives. ### Positions `CaptionPosition` sets where the track sits: ```dart CaptionPosition.bottomThird(), // the default subtitle band CaptionPosition.topThird(), // above the action CaptionPosition.center(), // mid-screen CaptionPosition.custom(Alignment.bottomCenter, safeArea: 96), // any alignment, with an inset ``` Pass `position:` to any caption constructor alongside `style:`. ## Annotations Annotations draw on top of a scene to point, frame, and label. They are plain widgets, so `.animate()` adds an outer reveal. An arrow draws on toward a point: ```dart Positioned.fill( child: Arrow.to( from: const Offset(720, 200), to: const Offset(910, 300), reveal: 500.ms, ), ), ``` That draws a shaft from `(720, 200)` to `(910, 300)` over 0.5 seconds, with a head at the end. A spotlight dims the scene and opens a clear hole over a region: ```dart Spotlight.on( region: const Rect.fromLTWH(780, 240, 240, 240), reveal: 500.ms, child: Padding( padding: const EdgeInsets.fromLTRB(64, 120, 64, 96), child: _themed( Chart.line(data: _signups, reveal: 1500.ms).animate([Animation.fadeIn()]), ), ), ), ``` The hole grows over the `reveal` window, so the eye lands on the surge. The annotation family: - `Shape` draws a line, rectangle, circle, or path. - `Arrow` draws a shaft with a head toward a point. - `Connector` joins two explicit points. - `Spotlight` dims the scene and opens a hole over a region. - `Callout` points an arrow at a target and labels it. - `LowerThird` slides a name and title in along the bottom. - `TitleCard` centers a title and subtitle and reveals them. A title card opens lesson 08: ```dart TitleCard( title: 'Code, on screen', subtitle: 'typed, highlighted, focused', reveal: Time.seconds(0.6), ), ``` `Shape`, `Arrow`, and `Connector` draw on with `.animate()`. `Spotlight` grows its hole over `reveal`. `LowerThird` and `TitleCard` slide and fade in over their own windows. All of them read colors from `context.fluvie`, so they match your theme. `Connector` and `Spotlight` take explicit positions in this version. Anchoring them to another element's rectangle is forthcoming. ## Two ways to move with the music Beat-reactive motion works now, with one scope dependency. `Animation.pulse(on:)`, `Animation.scaleY(on:)`, and `Bars` all read the precomputed band table and drive a transform per frame. Like media (which reads an `ImageResolverScope`), reactive motion needs the render shell's reactive pre-pass and a mounted `ReactiveScope` to read from. The example and render paths mount it for you. If you build your own capture shell, mount it yourself. That is the surface to reach for when you want the picture to move with the music. Beat-synced timing is a separate idea, and it works in 0.2.0. Reactive motion scales a transform with band energy; `Trigger.beat` starts an animation on the beat grid instead. Name a beat-tagged `Audio.music` with an `Anchor` through its `track:`, then fire an animation on that track's grid with `Trigger.beat(track:)`. The pre-pass finds the beat grid before frame 0, and the resolver snaps the animation to the first qualifying beat. Lesson 12 pops a brand chip on the music beat with `Animation.pop(at: Trigger.beat(track: music))`. Pass `every:` to fire on every second or fourth beat instead of every one. ## Bounded reactive analysis on desktop Reactive beat and spectrum analysis decodes compressed audio before capture. The desktop default accepts at most 16 million mono samples at 44.1 kHz, about six minutes, and limits one FFmpeg decode to two minutes. Native diagnostics are bounded to 16 KiB. Cancellation, a timeout or an exhausted sample limit kills and reaps the owned decoder; an oversized track reports its source and remedy instead of allocating an unbounded analysis buffer. Audible playback and mixing are separate from this reactive analysis limit. Trim the analysis source when you only need a short section. A custom host can instead configure its own budget through the public rendering barrel: ```dart import 'package:fluvie/rendering.dart'; /// A custom host shares this cancellation signal with its composition session. ({BeatDetectionService beats, FrequencyAnalyzer bands}) boundedDesktopAnalysis( RenderCancellation cancellation, ) { final decoder = FfmpegPcmDecoder( decoder: const FfmpegAudioDecoder( maxSamples: 32000000, timeout: Duration(minutes: 4), ), whenCancelled: cancellation.whenCancelled, ); return ( beats: SpectralBeatDetectionService(decoder: decoder), bands: SpectralFrequencyAnalyzer(decoder: decoder), ); } ``` Use the returned `beats` and `bands` as `CompositionSession.beatDetector` and `CompositionSession.analyzer`, and give that session the same cancellation signal. Increasing the limit also increases PCM and DSP memory use. An injected `PcmDecoder` can supply a different preparation backend without changing your authored `Audio`, beat triggers or spectrum animations. ## Audio across platforms The same `Audio` you declare works on every renderer. The mix math (`resolveAudioMix`) is shared, so delay, volume, trim, and fades resolve identically; only the encoder differs. This is the canonical support table. | Platform | Asset | Local file | Network (allowlist) | Looping beds | SFX / multi-track | Fades / trim / volume | Codec | | --- | --- | --- | --- | --- | --- | --- | --- | | [Desktop / Server](rendering-on-a-server.md) (FFmpeg) | yes | yes | yes | yes | yes | yes | AAC 192k / MP4 | | [Android](on-device-mobile-rendering.md#audio) | yes | yes | opt-in | yes | yes | yes | AAC / MP4 | | [iOS](on-device-mobile-rendering.md#audio) | yes | yes | opt-in | yes | yes | yes | AAC / MP4 | | [Web](on-device-web-rendering.md#audio) (ffmpeg.wasm) | yes | no | yes | yes | yes | yes | AAC 192k / MP4 | Notes: - A `Clip`'s embedded audio is demuxed from the video and folded into this same mix on every renderer, including the browser, where `ffmpeg.wasm` demuxes the clip's track. A `ClipAudio.muted` clip stays out of the mix. - Audio rides the MP4 export only. GIF, transparent WebM, and image sequences carry no sound. - "Network (allowlist)" needs an explicit allowlist of hosts. On-device it is opt-in: the web renderer takes a `WebAudioMaterializer`, the mobile renderer a `NetworkAudioMaterializer`. Browser fetches are also subject to CORS. - The web has no file system, so a local file path is not a valid source there. Bundle the audio as an asset or serve it over an allowlisted URL. - Audio bytes are per-machine on every backend (FFmpeg builds differ). - Reactive beat and spectrum analysis is separate from audible mixing. Desktop uses its PCM backend; the mobile renderer supplies bounded native PCM decoding or accepts an injected `PcmDecoder`. The independently hosted browser renderer still needs a suitable analysis backend. See the [mobile analysis contract](on-device-mobile-rendering.md#current-composition-limits). ## Where to next - [Timing and triggers](timing-and-triggers.md): the trigger vocabulary the reactive presets and `Audio.sfx` placement sit beside. - [Charts and data](charts-and-data.md): the data story the arrow and spotlight annotate. # Measure AI authoring The authoring benchmark runs ordinary generate, edit and review commands against a fixture project. It records model identity, prompts, readable Dart, preservation assertions, mounted review evidence, verified exports and elapsed time. ```sh fluvie benchmark suite.json --project fixture_project \ --provider gemini --model gemini-2.5-flash --out-dir benchmark_run ``` Configure the chosen provider through the normal environment variables. A model identity is required through `--model` or `FLUVIE_AI_MODEL`. `--fixture-mode` labels a simulated provider explicitly. Reports from fakes are never real-model evidence. A custom endpoint remains the caller's responsibility; the benchmark does not authenticate a model's claimed identity. From a checkout, create the reproducible synthetic fixture first: ```sh python3 tool/benchmarks/create_fixture.py /tmp/fluvie-authoring-fixture --ffmpeg ffmpeg fluvie benchmark tool/benchmarks/authoring_suite.json \ --project /tmp/fluvie-authoring-fixture --provider gemini \ --model gemini-2.5-flash --out-dir /tmp/fluvie-authoring-run ``` The helper uses `flutter create`, initializes the local package checkout, resolves dependencies and generates geometry, a tone, story notes, captions and a custom Flutter widget. It never calls a model. Choose a new destination for each fixture and a new output directory for each benchmark run. Provider runs are opt-in and use your configured provider account. ## Define a suite ```json { "schemaVersion": 1, "cases": [ { "id": "create", "action": "generate", "prompt": "Create a short video using assets/cat.png.", "requiredSourceText": ["assets/cat.png"] }, { "id": "title", "action": "edit", "base": "create", "prompt": "Change the title to Milo's afternoon." } ] } ``` Use 1–20 cases with unique lowercase identifiers. A `generate` case can include `contextFiles` to supply explicit story files. An `edit` case names a previous case through `base`, or a project-local Dart file through `source`. The benchmark copies the source beside its original before editing, so relative imports retain their meaning and the original authored file remains unchanged. A `formats` case exports its base for square, reels and landscape. `preserve` contains exact text that must survive an edit. `preserveRegions` contains named `// #docregion name` blocks that must remain byte-for-byte equal, including their markers. Use a region around custom widget code to detect an unrelated rewrite. `requiredSourceText` checks exact asset or API references. It does not establish whether the chosen image tells the intended story. The repository's `tool/benchmarks/authoring_suite.json` covers creation from synthetic image/clip/music assets, pacing, a custom Flutter widget, captions and multiple formats. Its fixture includes a factual `story.txt` and captions; do not describe synthetic geometric fixtures as photographs of a cat. ## Read the evidence Each case retains `prompt.txt`, `before.dart` when applicable, `after.dart`, command diagnostics, a model trace and its review/export files. `benchmark.json` records every case, including failures. A missing base fails explicitly. Edit cases must change source and preserve their selected regions. The default checks the full rendered output and selected-frame repeatability. Use `--frames N` for a bounded draft and record that prefix as the measurement scope. Timings include authoring, validation and review; they are not pure model-inference latency. The case clock starts after CLI startup and excludes fixture provisioning. Raw traces record per-attempt provider latency. Visual quality is always `requires_human_review`. Watch the video and inspect its frames. Codec verification, a preserved class and a correct asset string cannot establish storytelling, framing or visual polish. ## Trace and repair Dart edits ```sh fluvie edit lib/my_video.dart "Shorten the opening" --no-render \ --ai-trace build/fluvie/opening-edit.trace.json ``` `--ai-trace` on generate/edit explicitly retains prompts, replies, repair turns and provider-attempt latency. Transport credentials and headers are excluded; the trace can contain the authored source and selected private asset context. Keep it with the project's review evidence and select what to publish. `DartEditService` is the package API for exact edits. It requests a bounded edits object, validates unique non-overlapping original ranges through the same pure validator used by the CLI, and repairs malformed replies within three attempts by default. The CLI also makes at most two compiler-feedback repairs against the unchanged original source. Each author request has at most three structural attempts, for at most nine provider attempts per edit. Operational mount failures and concurrent source changes stop publication. Static analysis and mounted validation happen before source publication. Repair traces are kept alongside the initial trace. `RecordingAiClient` supplies the same evidence seam to custom hosts. The installed CLI supplies the current API cheat sheet and relevant canonical guides to Dart edits, capped at 32 KiB of UTF-8. Caption requests include compiled `Captions.fromSrt` and `CaptionStyle` examples. Documentation version and content digest identify the supplied API context. Exact-match failures identify the offending original text and ask for enough surrounding Dart to select one range. Source, patch replies and patched output are each limited to 256 KiB of UTF-8. Multiline prompts are transported losslessly through the managed Flutter host. ## Publish a recorded demonstration The local marketing site includes a recorded five-case Gemini run and eight exports at `/authoring`. Its geometric fixtures, prompts, original and edited Dart, native-frame posters, videos and portable bundle are downloadable. The page labels its provider and the scope of its automated checks. From a checkout, publish your own successful real-provider report: ```sh entry=$(python3 -c 'import json; print(json.load(open("/tmp/fluvie-authoring-run/benchmark.json"))["cases"][0]["sourcePath"])') fluvie bundle create "$entry" \ --out /tmp/fluvie-authoring-project.fluvie.zip node tool/benchmarks/publish_evidence.mjs \ /tmp/fluvie-authoring-run/benchmark.json /tmp/fluvie-authoring-project.fluvie.zip node tool/benchmarks/verify_evidence.mjs ``` The command selects the creation case's `sourcePath` from this five-case suite. The bundle must contain the recorded case sources. The publisher checks their hashes against the bundle, verifies receipts and matches each poster's decoded RGBA pixels to a sampled native frame. The site build checks the published bytes and displayed Dart against the recorded identities. Provider traces stay private unless you explicitly select them; publication copies a sanitized report. These checks establish the recorded workflow and artifact identities. Review storytelling and layout yourself. ## Where to next - [AI and MCP](ai-and-mcp.md): provider setup and installed documentation. - [Authoring workspace](authoring-workspace.md): inspect the result in one session. - [Portable projects](portable-projects.md): share replayable evidence. # Authoring videos as data A Fluvie video can be a JSON document. Save a video as a spec, load it back, and render it. The same format is what an AI uses to write a video from a prompt. A spec is one object: a size, an fps, and a list of scenes. Each scene has a duration, an optional background, and a list of children. Each child has a type, its content, and an `animate` list: ```json { "fluvieSpec": 1, "size": "reels", "fps": 30, "scenes": [ { "duration": "4s", "background": { "kind": "gradient", "colors": ["#1A2980", "#26D0CE"] }, "children": [ { "type": "Text", "text": "Hello, Fluvie", "style": { "color": "#FFFFFF", "fontSize": 72, "fontWeight": "w700" }, "animate": [{ "preset": "fadeIn" }, { "preset": "pop" }] } ] } ] } ``` ## Load and build Read a spec with `VideoSpec.fromJson`, then `buildVideo` turns it into a real `Video` you can render: ```dart final spec = VideoSpec.fromJson(jsonDecode(jsonText) as Map); final video = buildVideo(spec); ``` `buildVideo` is a pure function. The same spec always builds the same video. The model that wrote the spec runs once, at authoring time, never inside the frame loop. ## Save Write a spec back to JSON with `toJson`: ```dart final jsonText = jsonEncode(spec.toJson()); ``` Re-reading the saved form is stable: the serialization is canonical, so a load-then-save round trip settles after one pass. ## Anchors are names In code an anchor is a token you pass around. In a spec it is a string id. Give an element an `anchor`, then point a trigger at the same id: ```json { "type": "Text", "text": "Title", "anchor": "intro", "animate": [{ "preset": "fadeIn", "duration": "30f" }] } ``` ```json { "type": "Text", "text": "Subtitle", "animate": [{ "preset": "fadeIn", "at": { "kind": "after", "anchor": "intro" } }] } ``` The loader mints one anchor per id for the whole document, so the trigger that points at `"intro"` and the element that declares `"intro"` resolve to the same anchor. The subtitle starts when the title finishes. ## Time is a string Durations and delays are unit-tagged strings: `"2s"` seconds, `"30f"` frames, `"500ms"` milliseconds, and `"0.3r"` a fraction of the window. A relative time can carry a cap, as in `"0.2r@0.8s"`. ## A stable id Every spec has a content digest. Identical specs share a digest, so an AI-authored video keys the frame cache and names its output reproducibly: ```dart final id = spec.digest(); ``` ## What a spec can hold - **Elements**: `Text` (with `style`, `textAlign`, `maxLines`, or styled `spans` instead of `text` — each span an optional `style` and a `link` that underlines and lands on the span's semantics, never a tap target), `Box`, `Image` (with `fit`, `cornerRadius`, `crop`, and a `frame` style), `Counter` (with `ease` and `currency`/`percent` variants), `Shape` (`line`, `rect`, `circle`, and SVG-subset `path` kinds), `Arrow`, `Connector`, `Clip` (source, `trim`, `fit`, `volume`, audio `fadeIn`/`fadeOut`, a playback `speed`, and a preview `poster`), `Typewriter` (`speed`, `caret`, `style`), `Markdown` (`source`, `reveal`), `Terminal` (`lines` of `cmd`/`out`, `prompt`, `chrome`, `typingSpeed`, `lineGap`), and `Code` (`language`, a `dark`/`light` `theme`, a typed or line-by-line `reveal`, `focusLines`, `highlightLines`, and a diff form via `after`), and `Chart` (every `variant`: `bar`, `pie`, `donut`, `line`, `area`, `scatter`, with `data`, multi-`series`, scatter `points`, `reveal`, `stagger`, and a donut `innerRadius`). The experimental snapshot surfaces serialize too: `Mermaid` (`theme`, a node/edge `reveal`, `fit`) and `WebView`/`Html` (an absolute `uri` or inline `source`, a required `viewport`, plus `scroll`, `clip`, `fit`). So do the audio `Bars` (`count`, `band`, `gain`, and an `Audio.track` anchor id in `track`) and the title annotations `LowerThird` (`name`, `title`, `reveal`, `color`) and `TitleCard` (`title`, `subtitle`, `reveal`, `color`). The wrapper elements nest one full element in a `child` (itself animatable and placeable, to any depth): `Snapshot` (`fit`), `DeviceFrame` (a `phone`/`browser`/`tablet` `variant`, a phone `notch`, a browser `url`), `Callout` (`label`, `target`, `labelAt`, `color`), and `Spotlight` (`region`, `reveal`, `color`); `LowerThird` and `TitleCard` take the same optional `child`. A `Box` also takes a `decoration` (color, corner radius, border, gradient, shadow). Every element additionally takes a `shared` string id, a sibling of `anchor`: two elements naming the same id in adjacent scenes pair into one hero morph across the transition between them. A `Group` nests a whole `children` list inside one box: the group's `transform` places the box, each child's `transform` is a fraction of it, and `animate` on the group moves everything inside as one unit. Groups nest to any depth; an empty group renders nothing. Every element also takes `visible`: set it to `false` and the element renders nothing while keeping its place in the document, and the flag counts into the digest because hiding changes the render. - **Placement**: a fractional `transform` per element (`x`, `y`, `w`, `h`, `rotation`, `opacity`, `anchor`) on a `layout: canvas` scene; without one, elements center-stack. - **Time windows**: every element takes `show`, the serialized form of the runtime's `show({from, to})` — the element appears at `from` and disappears at `to`, both inside its scene: ```json { "type": "Clip", "source": { "kind": "asset", "value": "media/b-roll.mp4" }, "show": { "from": "2s", "to": "6.5s" } } ``` A missing `from` means the scene start and a missing `to` the scene end; an empty `show` is invalid (drop the key instead). The window rides the element's one `.animate(...)` call as its `window:` argument, so the element's animations resolve inside it: a clip that enters at `2s` plays its `fadeIn` at `2s`. On a `Group` the whole group windows as one unit, and `visible: false` still wins — a hidden element never mounts, window or not. - **Backgrounds**: `color`, `gradient`, `radial`, `image`, `video`, `noise`, `vhs`. The gradient kinds (and a decoration's `gradient`) take an optional `stops` list: one 0..1 offset per color, non-decreasing; leave it out and the colors space evenly. - **Animations**: the named presets (`fadeIn`, `slideFadeIn`, `pop`, `kenBurns`, `maskWipeIn`, `glitchIn`, `float`, `pulse`, and more), the color and pixel effects (`color`, `gradientShift`, `scanlines`, `chromatic`, `bloom`, `parallax`, `particles`, the experimental `shader`), the audio-reactive `scaleY` and `pulse` (an `on` band, a `gain`, an `Audio.track` anchor id in `track`), the path-following `along` (an SVG `path` string, `orient`, `phase`), raw `from`/`to`/`fromTo` keyframes, and multi-stop `keyframes`: a list of at least two stops, optional per-segment `easings` (one per segment), optional `positions` (one time per stop, strictly increasing), and a `phase`. Offsets in a stop are element-relative (`y: 0.6` is 0.6 element heights down). The stop positions are `positions`, so `at` keeps meaning the start trigger: ```json { "keyframes": [ { "opacity": 0, "y": 0.6 }, { "opacity": 1, "y": -0.15 }, { "y": 0 } ], "easings": ["out", "smooth"], "positions": ["0f", "10f", "24f"], "duration": "24f", "at": "sceneStart" } ``` A `shader` asset must be a plain relative asset path. `Animation.custom` stays code-only: an arbitrary Dart effect has no data form. - **Transitions**: `cut`, `crossFade`, `wipe`, `zoom`, `slide`. - **Theme tokens**: a top-level `theme` block holds named design tokens: a `palette` of colors, a `typeScale` of text styles, `spacing` sizes, and `motion` defaults. Any color field may then reference the palette as `{"token": "accent"}` instead of a literal, and a style object may adopt a type-scale entry whole through its own `"token"`, with sibling literal fields winning per field: ```json { "theme": { "palette": { "accent": "#FF6C5CE7" }, "typeScale": { "heading": { "fontSize": 42, "fontWeight": "w700" } } } } ``` Then `"color": {"token": "accent"}` colors an element and `"style": {"token": "heading", "fontSize": 90}` styles one with the heading scale at size 90. Literals keep working everywhere. Tokens resolve while the document builds; an unknown name (or a token without a theme) fails loudly with the known names and the document path. The theme counts into the render digest, so retinting one token re-renders everything bound to it. Theme values themselves stay literal (a token cannot reference a token), `spacing` is stored, validated, and digested for editing tools but resolved by nothing in the engine yet, and `motion` composes *under* an explicit `motionDefaults` per field (the explicit value wins). Printed Dart resolves every token to its literal and leads with a comment saying so, because plain fluvie code has no theme object. - **Masters**: a top-level `masters` block holds named slide layouts. A master is an optional `background`, a `layout` intent, and `children` that mix fixed chrome (full elements: logos, footers) with named `Placeholder` slots: ```json { "masters": { "content": { "background": { "kind": "color", "color": "#FF101018" }, "children": [ { "type": "Box", "color": "#FF6C5CE7", "transform": { "x": 0.5, "y": 0.94, "w": 1.0, "h": 0.06 } }, { "type": "Placeholder", "slot": "title", "transform": { "x": 0.5, "y": 0.3, "w": 0.9, "h": 0.3 }, "style": { "fontSize": 34, "fontWeight": "w700" } } ] } } } ``` A scene adopts one by name and fills its slots: `"master": "content", "fills": { "title": { "type": "Text", "id": "s1-title", "text": "Hello" } }`. The master applies at build time with no copies, so editing a master changes every adopting scene. The layering is: master background (unless the scene declares its own; the scene wins), master children in order (each placeholder replaced by its fill, unfilled slots rendering nothing), then the scene's own children on top. A fill is a scene-owned element: it carries its own `id` (a step may reveal it), and its own `transform` overrides the placeholder's; a placeholder's `style` defaults merge *under* the fill's style per field. Master children carry no `id`, `anchor`, or `shared` (they are chrome, not per-scene elements), a `Placeholder` is legal only inside a master, and an unknown master name or slot fails loudly at parse. A scene without a master is fully freeform. Masters count into the render digest; printed Dart prints adopting scenes resolved, behind a `// master "..." applied for the printed build` comment. - **Audio**: a top-level `audio` list of tracks spanning the video, and an optional `audio` list per scene starting with it. Each track mirrors `Audio.music` or `Audio.sfx` field for field: ```json { "audio": [ { "kind": "music", "source": { "kind": "file", "value": "/home/ada/music/bed.mp3" }, "volume": 0.8, "fadeIn": "30f", "fadeOut": "60f", "loop": true, "trim": { "from": "0f", "to": "900f" }, "track": "bed" } ], "scenes": [ { "duration": "150f", "audio": [ { "kind": "sfx", "source": { "kind": "asset", "value": "audio/whoosh.mp3" }, "at": { "kind": "at", "time": "500ms" } } ] } ] } ``` The `source` is the same `{kind, value}` object images and clips use. A music track carries `volume`, `fadeIn`/`fadeOut`, `loop`, `trim`, and `track` — an anchor id naming its analysed beat grid, so `{"kind": "beat", "track": "bed"}` triggers resolve against it. An sfx track carries `at` (any trigger; missing means the owner's start) and `volume`. `at` on a music track and a music-only key on an sfx track fail loudly, because the constructors force exactly those fields. The engine consumes audio: the build hands the lists to `Video.audio` and `Scene.audio`, the mix collects them video-first in declaration order, and they count into the digest. The shape is fixed in the [video-mode ADR](../contributing/video-mode-document.md). - **Lanes**: a top-level `lanes` list declaring the rows an editing timeline draws material on, and an optional `lane` on any element or audio track naming one of them: ```json { "lanes": [ { "id": "v1", "name": "Video 1" }, { "id": "a1", "name": "Music", "kind": "audio", "height": 56, "muted": true } ] } ``` A lane says **where material is shown, never what order it paints in**: paint order stays the `children` list. A lane takes an `id` (required, and unique — a reference has to name exactly one row), an optional `name`, a `kind` of `video` or `audio`, `locked`, `muted`, and a `height`. A `lane` that names no declared lane fails loudly rather than being dropped. Only `muted` reaches the render: a muted lane's audio tracks are left out of the build, and out of the Dart `fluvie print` writes, because a mute the export ignored would be a lie you only find in the file. `locked`, `height` and `name` are for the tool drawing the timeline. The key is `lane` and never `track`. `track` is already a content property in three places — the `Bars` beat grid, a music track's beat anchor, and the reactive `pulse` and `scaleY` arguments — and reserving that name would pull it out of an element's properties and silently kill every beat grid. - **Effects**: an ordered `effects` list on any element — thirteen surfaces that wrap it: ```json { "type": "Clip", "source": { "kind": "asset", "value": "media/b-roll.mp4" }, "effects": [ { "kind": "grain", "amount": 0.35 }, { "kind": "vignette", "amount": 0.55 }, { "kind": "bloom", "amount": 0.2, "enabled": false } ] } ``` The thirteen: `grain` (amount), `vignette` (amount), `scanlines` (spacing, opacity), `chromatic` (px), `grade` (exposure, contrast, saturation, temperature, tint), `curves` (a `curves` object, intensity), `lut` (asset, intensity), `blur` (sigma), `bloom` (amount), `glitch` (intensity, from, reverse), `particles` (a `particles` object), `shader` (asset, uniforms), and `parallax` (depth). Every default is the effect's own current value, so a stack that names nothing renders what it always rendered. A bare grade composes to the identity matrix and is a pixel-for-pixel no-op. `curves` holds channel point lists under `master`, `red`, `green` and `blue`, each a list of `[x, y]` pairs on the unit square, evaluated as a monotone cubic through the points. `lut` names a `.cube` file: at most 4 MB, `LUT_3D_SIZE` 2 to 64, unit domain only, validated before anything reads it, because a LUT file is external input. Both apply through a warm fragment shader over the rendered element, and both carry an `intensity` that mixes toward the untouched frame. The colour-space contract is simple on purpose: non-linear sRGB in, non-linear sRGB out, no transfer function on either side. At intensity zero, and for all-identity curves, the element mounts unwrapped: an exact no-op, not a near one. The stack composes by **class, then list order**: transform-class effects (`parallax`) innermost and pixel-class outermost, each keeping the order it was written in. That is the same transform-then-pixel discipline `animate` already applies, so a stack reads the same however it was typed. Every numeric parameter has an honest range, and a value outside it is refused rather than silently clamped into something you did not write. `enabled: false` mounts nothing and stays in the document, exactly as `visible: false` does for an element — you turned it off, you did not delete it. In Dart the same stack is `.effects([Effect.grain(amount: 0.35), ...])`, in the same slot: inside the element's `animate` wrapper and outside the element itself. **Keyframed parameters.** Any numeric parameter takes either a literal or a keyframed value: ordered stops, one position per stop, one easing per segment. The vocabulary is the `keyframes` animation form's on purpose, so you learn it once: ```json { "kind": "vignette", "amount": { "values": [0, 0.9], "positions": ["0f", "90f"], "easings": ["smooth"] } } ``` The ramp runs over the element's own life: `0f` is the frame the element comes alive, and outside its stops the value holds rather than extrapolates. Two stops minimum, because one stop is a plain number wearing a list. Every stop faces the same range a literal would, because a ramp to 5 is as wrong as a 5. `positions` is required, one per stop, strictly increasing; `easings` is optional and defaults to linear segments. In Dart a keyframed effect speaks the spec spelling, because the named factories take plain numbers and a parameter that changes says so through its own declaration: ```dart return child.effects([ Effect.grain(amount: 0.35), Effect.spec( EffectSpec( EffectSpecKind.vignette, params: { 'amount': KeyframedNumber.linear( values: const [0, 0.9], positions: const [Time.zero, Time.frames(90)], ), }, ), ), ]); ``` - **Overlays**: a top-level `overlays` list of elements that live outside every scene, on the whole video's clock: ```json { "overlays": [ { "id": "ov-logo", "type": "Image", "source": { "kind": "asset", "value": "media/logo.png" }, "transform": { "x": 0.9, "y": 0.12, "w": 0.12, "h": 0.12 }, "show": { "from": "0f", "to": "180f" } } ] } ``` An overlay is **one element for the whole video**. It is mounted once, never re-parented across a boundary, and its `show` window resolves against the video's own length rather than a scene's — so it holds through every cut and every blend without blinking. That is the one thing a `shared` hero morph can never be: a morph is two elements made to look like one across a cut, and an overlay *is* one. Overlays take no part in the offset math. Adding one never lengthens the video and never moves a boundary. They paint above every scene, in declaration order, and below the captions. An overlay may not declare `shared` — it already runs the whole video, so there is no boundary for it to morph across, and a document that tries is refused rather than quietly ignored. Which slide an editor draws an overlay on is editorial, so it lives in the `editor` block (`overlayHomes`) and never moves the content digest. - **Steps and notes**: a scene-level `steps` list (each entry a group of child ids to reveal together, the list order being the step order; children in no step show on entry) and `notes` objects (`text`, `highlights`) on the scene and on any step. Fluvie stores, validates, and round-trips both, and they count into the digest, but rendering ignores them: a rendered video plays straight through. Only `fluvie_presenter` interprets them, through `deckFromSpec`; the shapes are fixed in the [steps-and-notes ADR](../contributing/steps-notes-digest.md). A node the format does not support fails loudly: `VideoSpec.fromJson` throws a `FluvieSpecError` that names the document path of the problem, so a bad spec never renders the wrong thing. ## Author with AI from Dart The companion package `fluvie_ai` writes a spec from a prompt. Add it: ```sh dart pub add fluvie_ai ``` Pick a provider, set its key in the environment, then author a spec and build it like any other: ```dart final client = aiClientFromEnv(Platform.environment); final service = LlmVideoAuthorService(client: client); final spec = await service.author(prompt); final video = buildVideo(spec); ``` `author` runs the model once and returns a validated `VideoSpec`. When the model returns an invalid spec, the service feeds the validation error back for up to three repair rounds before it gives up. Save the spec and you have a reproducible artifact: rendering it never calls the model again. ### Providers | Provider | `FLUVIE_AI_PROVIDER` | API key | Sees images | | --- | --- | --- | --- | | Claude (default) | `claude` | `ANTHROPIC_API_KEY` | yes | | Gemini | `gemini` | `GEMINI_API_KEY` | yes | | Mistral | `mistral` | `MISTRAL_API_KEY` | no | | Ollama (local) | `ollama` | none | no | `FLUVIE_AI_MODEL` overrides the model. `ollama` needs no key and runs against a local server, the easiest way to try this offline. ## From the command line Render an existing spec to a file: ```sh fluvie render --spec promo.fluvie.json --out promo.mp4 ``` Write a spec from a prompt with an LLM, save it, and render it in one step. The provider and API keys come from the environment, so set them first: ```sh export FLUVIE_AI_PROVIDER=claude # or gemini, mistral, ollama export ANTHROPIC_API_KEY=sk-... fluvie generate "a 6s vertical title card, dark gradient, fade-in headline" \ --out promo.mp4 --spec-out promo.fluvie.json ``` Refine the saved spec conversationally; re-rendering the same spec gives the same video: ```sh fluvie edit promo.fluvie.json "make the headline yellow and add a logo" \ --out promo.mp4 ``` On an `edit`, the harness renders a frame of the current video and sends it to the model alongside the change, so a multimodal provider (Claude or Gemini) can see what it is editing. The committed `.fluvie.json` stays the reproducible artifact; the image only grounds the next edit. ## In the example app The example inspector has a "Generate with AI" action in its app bar. It opens a prompt panel that authors a spec with the same `VideoAuthorService`, then shows a summary and the validated JSON. It reads the provider and key from the same environment variables, so export them before launching the app. ## Where to next - [Animating elements](animating-elements.md) for the full preset menu a spec can name. - [Timing and triggers](timing-and-triggers.md) for how anchors and triggers resolve. - [Exporting your video](exporting-your-video.md) to render a built spec to a file. ## Keep generated Dart readable `fluvie generate "a short cat story" --dart-out lib/my_video.dart --no-render` writes native Flutter composition code for review before capture. Element IDs and clip transitions print as `ElementId`, `ClipTransition`, and `ClipTransitionGroup`; clip-lane gain prints through `ClipAudio.scaledBy`, preserving authored fades and automation. The runtime algorithms are shared with the spec adapter. You can edit the Dart without routing ordinary authoring through `VideoSpec.fromJson`. # A shared authoring workspace Open the package-owned workspace for a Dart composition: ```sh fluvie workspace lib/my_video.dart ``` Open the printed local URL. Capture an exact frame, compare it with the previous capture, review representative frames, inspect diagnostics and export the video. Review findings show their code, interval and remedy, with an **Inspect frame** action tied to the reviewed source revision. The page also shows the current Dart source. Edit that source in your normal editor. The workspace creates no app or rendering harness in your project. The browser displays PNGs captured by the native Flutter test engine. Its export uses that same capture backend and the managed FFmpeg pair. Use `--enable-impeller` when your composition needs that backend. Use `fluvie preview lib/my_video.dart` for continuous browser or device playback. ## One worker per source revision The first request starts a Flutter worker. Subsequent frame, inspection, review and export requests reuse its compilation and engine. Each request mounts a new composition and releases its resources. Source or resolved dependency changes retire the worker before the next request. A change during capture rejects the result as stale. Every result records `sourceRevision`, `backend`, `workerPid`, `startupMilliseconds`, `captureMilliseconds` and `elapsedMilliseconds`. Startup includes staging and compilation; capture measures the engine request; elapsed time also includes fingerprinting, encoding and verification. Compare warm requests separately from first startup. Worker readiness and engine requests each allow five minutes by default. Cold Flutter compilation can take longer on a large or busy project. Set `--startup-timeout ` and `--request-timeout ` on `workspace` when needed; both require positive whole seconds. Custom hosts pass `startupTimeout`/`requestTimeout` to `NativeRenderWorker.start`, or `workerStartupTimeout`/`workerRequestTimeout` to `WorkspaceSession`. The descriptor records these budgets. The session CLI allows fifteen minutes for the whole HTTP request; override it with `--timeout ` when using longer worker budgets or exports. The revision covers local source, resolved dependency libraries and declared resources through the existing content fingerprint. The watcher detects ordinary filesystem metadata changes. Runtime network content, undeclared external files and changes that preserve filesystem metadata require restarting the workspace and reviewing their identity separately. ## Let an assistant inspect the same session The workspace prints the path to a private `session.json` descriptor under `build/fluvie/.workspace/`. Pass it to the session command: ```sh fluvie session build/fluvie/my_video.workspace/session.json status fluvie session build/fluvie/my_video.workspace/session.json frame --frame 45 fluvie session build/fluvie/my_video.workspace/session.json review fluvie session build/fluvie/my_video.workspace/session.json render --frames 60 ``` These requests use the running worker. Frame results name a local PNG an assistant can open. Review returns samples, mounted facts and repeatability evidence. Export returns the verified artifact and receipt. `source` returns the authored Dart. `inspect` returns mounted timeline and resource facts. Use `--revision ` when a request must refer to a previously inspected revision. A mismatch fails before rendering. The descriptor is removed when the workspace stops. Press Ctrl+C to stop the server and reap its worker; the result files remain available. ## HTTP interface The descriptor contains a loopback `endpoint` and a per-session `token`. Requests carry `X-Fluvie-Token`. Redirects and remote descriptors are rejected by the session command. The server accepts only its own origin and loopback host. | Request | Result | | --- | --- | | `GET /status` | Source, revision, backend and worker state | | `GET /source` | Entry source, limited to 256 KiB | | `POST /jobs` | Serialized capture, review, inspection or export | | `GET /artifact?path=` | An existing file inside the result directory | A job is a JSON object with `operation`: `frame`, `review`, `inspect` or `render`. Optional fields are `frameIndex`, `frameCount`, `reviewFrames`, `reviewDeterminism`, `aspect`, `quality`, `format` and `sourceRevision`. Indexes must fit the authored timeline. Review accepts at most 24 sample frames. The queue admits at most four requests and job bodies are limited to 64 KiB. Unknown fields and invalid types fail explicitly. The token grants access to this local source and its artifacts. It is not a provider API key. Keep the descriptor private. This host executes your Dart composition and provides no sandbox for untrusted code. ## Custom hosts `runFluvieWorker` is exported from `package:fluvie/rendering.dart`. A custom host supplies its entry factory and `RenderHostContext` callbacks. Runtime requests use `RenderInvocation.fromJson`; rendering stays in `runFluvieRender`. The launcher owns the private mailbox, process lifetime and source invalidation. For a different rendering engine, retain the existing `--renderer` or `--harness` render extension. Workspace requests use the managed engine. For intentional quality findings, send `allowQuality` with known finding codes and `strictQuality: true` to fail on remaining warnings. The session CLI exposes `--allow-quality` and `--strict-quality`. Findings stay in the result, including explicit exceptions. See [review diagnostics](reviewing-a-video.md). ## Where to next - [Reviewing a video](reviewing-a-video.md): text, audio and repeatability checks. - [Portable projects](portable-projects.md): restore and replay a recorded project. - [Authoring benchmarks](authoring-benchmarks.md): measure model edits and exports. # Backgrounds and gradients A `Background` fills the whole scene behind your content. Pass it to `Scene(background: ...)` or mount it as a plain child; both paint the same pixels. Lesson 03 animates one with `gradientShift`: ```dart Background.gradient(const [Color(0xFFE74C3C), Color(0xFF27AE60)]).animate([ Animation.gradientShift( to: const [Color(0xFF2980B9), Color(0xFF27AE60)], duration: 0.3.relative, // 30% of the 10 s scene delay: 0.1.relative, // begins 1 s in ), ], anchor: bg), ``` ## The factories | Constructor | What it paints | | --- | --- | | `Background.color(color)` | one solid fill | | `Background.gradient(colors, begin:, end:)` | linear gradient, top left to bottom right by default | | `Background.radial(colors)` | radial gradient from the center | | `Background.noise(scale: 1)` | deterministic seeded noise texture | | `Background.vhs()` | scanline and band texture | | `Background.image(source, fit:)` | an image fill | | `Background.video(source)` | a video fill | `image` and `video` resolve their source through the media pipeline before capture, so a frame never blocks on IO. A source that cannot be resolved throws a clear error naming it, so a typo never fails silently. ## gradientShift `Animation.gradientShift(to: [...])` lerps each base color to its counterpart in `to`, pairwise. The two lists must have the same length. Before the animation starts you see the base colors; after it settles you keep the shifted ones. Timing composes like any other preset: the lesson above uses a relative delay and duration, so the shift spans 1 s to 4 s of its 10 s scene. ## Animating a solid fill `Animation.color(to: ...)` works on `Background.color` the same way: the background paints the animated color for as long as the animation defines one. ## Where to next - [Timing and triggers](timing-and-triggers.md): the anchor on that gradient is the start of a chain. - [Layouts](layouts.md): what sits in front of the background. # Charts and data Turn a `Map` into an animated chart with one call. Each `Chart` factory grows, draws, or sweeps itself in over its own window, so you describe the data and the reveal happens for you: ```dart Chart.bar( data: _revenue, reveal: 1.seconds, stagger: const Stagger.each(Time.frames(6)), ).animate([Animation.slideFadeIn()]), ``` That paints four bars from `{'Q1': 42, 'Q2': 58, 'Q3': 71, 'Q4': 96}`, grows each one from the baseline over one second, and offsets each bar's growth six frames so the columns rise in a wave. Lesson 07 builds the whole data story. ## The chart family Every chart is one public type, `Chart`, with a named factory per shape: ```dart Chart.bar(data: _revenue), // columns growing from the baseline Chart.line(data: _revenue), // a polyline drawing on left to right Chart.area(data: _revenue), // a line sweep filled to the baseline Chart.pie(data: _revenue), // wedges sweeping clockwise from 12 o'clock Chart.donut(data: _revenue), // a pie with an inner-radius hole Chart.scatter(points: _points), // markers popping in with a spring ``` `bar`, `pie`, and `donut` take a `Map` of category to value, in the order you write it. `line`, `area`, and `scatter` take the same single-series map, or call `.series([...])` with `ChartSeries` values for several colored series at once. ## The reveal is built in A chart's reveal is part of its constructor, not its `.animate()` list. You pass a `Time` to the reveal parameter, and the chart resolves it against its own window: - `Chart.bar` and `Chart.area` grow over `reveal`. - `Chart.line` and `Chart.area` draw on over `reveal`. - `Chart.pie` and `Chart.donut` sweep over `reveal`. - `Chart.scatter` pops over `reveal`. A relative time scales with the window. `reveal: 0.6.relative` grows over the first 60 percent of the scene; `reveal: 1.seconds` grows over one second. The default for every reveal is `0.6.relative`. A line draws on by trimming its path left to right: ```dart Chart.line(data: _signups, reveal: 1500.ms).animate([Animation.fadeIn()]), ``` A donut sweeps its wedges round and leaves a hole. `innerRadius` is the hole size as a fraction of the outer radius: ```dart Chart.donut( data: _channels, reveal: 1.seconds, innerRadius: 0.62, ).animate([Animation.slideFadeIn()]), ``` ## Stagger across segments `Chart.bar` and `Chart.scatter` take a `stagger` that offsets each segment's reveal, so the bars rise or the markers pop one after another. It reuses the same `Stagger` you pass to a multi-child `.animate()`: ```dart Chart.bar(data: _revenue, stagger: const Stagger.each(Time.frames(6))); ``` The stagger delays the reveal of each bar, not the chart's window. Bar zero starts at frame zero, bar one six frames later, and so on. ## .animate() for outer transforms The reveal is intrinsic; `.animate()` adds outer transforms on top. A chart is a plain widget, so it animates like any other element. The slide, fade, or camera move composes with the grow or sweep: ```dart Chart.bar(data: _revenue).animate([Animation.slideFadeIn()]); ``` Keep pixel data in the reveal and motion in the list. The two never fight: the chart paints its bars at the reveal progress, and the transform moves the whole result. ## Theming with context.fluvie Charts read their colors from `context.fluvie`. Wrap a subtree in a `FluvieTokensScope` with a `FluvieTokens` value, and every chart inside picks up the palette: ```dart FluvieTokensScope( tokens: const FluvieTokens( palette: ChartPalette([Color(0xFF00E0B0), Color(0xFF5B8DEF)]), axisColor: Color(0xFF546E7A), gridColor: Color(0x22FFFFFF), labelColor: Color(0xFFCFD8DC), ), child: Chart.bar(data: _revenue), ); ``` A chart with no scope above it uses the package fallback palette, so charts work without any theme. A bar, segment, or marker cycles the palette by index; a `ChartSeries.color` override wins over the slot the palette would pick. `FluvieTheme` ships in 0.2.0. It sets a subtree's brand palette, type scale, and motion defaults, and mounts a `FluvieTokensScope` for you, so charts, `Code`, and captions read the brand through the same `context.fluvie`. It does not set the chart-series `ChartPalette` though. Your series colors stay on the `FluvieTokensScope` above, so wrap a `FluvieTokensScope` where you want to recolor the series. See [Theming](../advanced/theming.md) for the full theme. A counter headline reads like the charts it sits above: ```dart Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Text('Revenue this year', style: _headline), Counter.currency( to: 267000, reveal: 1500.ms, style: _metric, ).animate([Animation.slideFadeIn()]), const Text('up 38% over last year', style: _caption), ], ), ), ``` ## A pure function of your data A chart is a pure function of its data, its reveal progress, and its theme tokens. The same frame paints the same way every time, so charts cache and golden like every other element. ## Where to next - [Text and typography](text-and-typography.md): `Counter` and `Typewriter`, the elements that headline a data story. - [Animating elements](animating-elements.md): how `.animate()` and `Stagger` compose the outer motion a chart rides. # Code and terminal videos Show source the way a screencast does: type it out, highlight the lines that matter, then run it in a terminal. `Code` and `Terminal` are frame-driven elements, so you describe the content and the reveal happens for you: ```dart child: Code( _snippet, language: 'dart', reveal: CodeReveal.typing(1.frames), focusLines: const {5}, highlightLines: const {5}, ).animate([Animation.slideFadeIn()]), ``` That highlights the snippet in Dart, types it out one glyph per frame, dims every line except line 5, and tints line 5's background. The reveal is built in; `.animate()` only adds the outer slide. Lesson 08 builds the whole explainer. ## Code `Code` takes the source as its first argument and the highlight language as `language`. The source is highlighted once per content and cached by content hash, so frame N never re-parses and the same frame paints the same pixels every time. The highlighter is the highlight.js Dart port, which covers around 190 languages: ```dart Code('def main():\n print("hi")', language: 'python'), Code('const x = 1;', language: 'javascript'), Code('SELECT * FROM users;', language: 'sql'), ``` An unknown language renders the source as plain, unhighlighted text rather than throwing. ### Reveal modes `reveal` is a `CodeReveal` and has three modes: ```dart Code(src, reveal: CodeReveal.instant), // everything at once (default) Code(src, reveal: CodeReveal.typing(2.frames)), // glyph by glyph, with a caret Code(src, reveal: CodeReveal.lineByLine(8.frames)), // whole lines in sequence ``` `typing` reveals the joined source one glyph at a time and blinks a caret while it runs, reusing the same arithmetic `Typewriter` does. `lineByLine` reveals whole lines in turn: line `i` appears once the elapsed frames pass `i` times the per-line time. Each mode carries a `Time` that resolves against the element window, so a relative time scales with the scene. ### Focus and highlight `focusLines` and `highlightLines` are sets of 1-based line numbers. `focusLines` dims every other line to the theme's dim opacity, so the eye lands on the lines you name. `highlightLines` tints those lines' backgrounds: ```dart Code(src, language: 'dart', focusLines: {3, 4}, highlightLines: {4}); ``` Both are content parameters, so the frame clock and scene placement drive which focus is active. To move the focus over time, re-issue the `Code` with a different set at the next scene or timeline position, the way a chart re-issues its data. A cross-fade between two focus states is a plain `.animate([Animation.fadeIn()])` on the swapped widget. ### Theming with context.fluvie `Code` reads its colors from `context.fluvie.code`, a `CodeTheme` that maps every token kind to a color and carries the editor background, gutter, line-number, dim opacity, and highlight colors. Wrap a subtree in a `FluvieTokensScope` to theme every `Code` and `Terminal` inside it: ```dart FluvieTokensScope( tokens: const FluvieTokens.fallback(), child: const Code('void main() {}', language: 'dart'), ); ``` A `Code(theme:)` override wins over the inherited theme for that one element. Ship `CodeTheme.dark()` or `CodeTheme.light()`, or build a custom theme. ### Code.diff `Code.diff(before, after)` animates the change from one version to another over a pure line diff: removed lines fade out and collapse behind a red gutter, inserted lines fade in and expand behind a green gutter, and kept lines slide to their new position: ```dart Code.diff( 'final x = 1;', 'final x = 2;', language: 'dart', reveal: CodeReveal.lineByLine(12.frames), ); ``` Both sides are highlighted once and cached, so the diff colors its tokens too. ## Terminal `Terminal` plays a list of `TerminalLine` values in sequence. A `cmd` line types out glyph by glyph after a prompt with a blinking caret; an `out` line streams in whole once its turn arrives: ```dart child: const Terminal( chrome: TerminalChrome.macos(title: 'zsh'), lines: [ TerminalLine.cmd('dart run fluvie render hello'), TerminalLine.out('Rendering 270 frames...'), TerminalLine.out('Wrote hello.mp4 (9.0s, 1080x1080)'), ], ).animate([Animation.slideFadeIn()]), ``` The prompt is `$ ` by default; pass `prompt:` to change it for the whole terminal, or `TerminalLine.cmd('...', prompt: '> ')` for one line. `typingSpeed` sets how fast a command types and `lineGap` sets how long after one line settles the next begins. Each line reveals in sequence with the same stagger machinery a multi-child `.animate()` uses. `chrome` adds an optional window bar. `TerminalChrome.macos(title:)` draws a title and the three traffic-light dots; leave `chrome` null for a bare terminal. Terminal colors come from `context.fluvie.code` too. ## Markdown `Markdown` parses a CommonMark document once and renders it to widgets: headings, paragraphs, lists, blockquotes, and inline `code`, **bold**, and *italic* runs. ```dart const Markdown( '# Release notes\n\n' '- Faster renders\n' '- Highlighted `Code` blocks\n\n' '> On-device rendering is the headline.', ); ``` A fenced code block in the source delegates to a `Code` widget highlighted in its fence language, and an image delegates to an `Image` widget, so the same highlighting and pre-resolved media you use elsewhere apply inside a document. The rest of the source, headings, paragraphs, and lists, renders as styled text. Pass `reveal:` a `Time` to bring the top-level blocks in one after another over the element window: ```dart Markdown(source, reveal: 1.seconds); ``` Each block fades and slides up as its turn arrives. With no `reveal` the whole document shows at once. Colors follow `context.fluvie`, or pass a `MarkdownStyle` to `style:`. ## The bundled font `Code`, `Terminal`, and the fenced blocks inside `Markdown` default their font to JetBrains Mono, bundled with the package. You do not register anything: the font ships to every render, so your monospace text looks the same on every machine. Pass a `style:` with your own `fontFamily` to override it. ## Parsed once, cached by content Every one of these elements is a pure function of its parsed content, its reveal progress, and its theme tokens. The parse and the highlight run once per content and are cached by content hash, never per frame. The same frame paints the same way every time, so code, terminal, and Markdown videos cache and golden like every other element. ## Where to next - [Text and typography](text-and-typography.md): `Typewriter` and `Counter`, the text elements a code explainer sits beside. - [Charts and data](charts-and-data.md): the other data-driven element family, with the same reveal-is-intrinsic contract. # Diagrams and web pages Draw a Mermaid diagram, render a web page, or rasterize any Flutter subtree, then paint the result as a still in your video. Each of these elements turns into one decoded image before frame 0 and the same image paints every frame: ```dart child: const Mermaid( _flow, theme: MermaidTheme.dark(), reveal: MermaidReveal.drawEdges(Time.seconds(1)), ).animate([Animation.slideFadeIn()]), ``` That lays out the Mermaid source, rasterizes it to one image, and draws the edges in over one second while `.animate()` slides and fades the whole diagram. Lesson 09 builds the full three-scene explainer. ## The rule: rasterize once, paint every frame This is the headline for every element on this page. A diagram, a web page, or a subtree is rasterized once, before frame 0, into a decoded image. That image is cached by content hash and painted synchronously on every frame after. The frame loop never runs a live browser or a live platform view. This is what keeps a snapshot stable across the render. The same source produces the same image, and that image paints the same on frame 0 and frame 200. A snapshot is just another resolved media, so it caches and goldens like an `Image` or a `Clip`. Because resolution happens before the frame loop, the diagram or page is present from the first frame. There is no async pop-in. A reveal animation runs over the already-rendered raster, not over the act of rendering it. ## What works today `Snapshot`, `DeviceFrame`, and the full rasterize-once API work now. Live Mermaid and live web rasterization need a renderer that is not wired in this version yet. See [The live renderer is experimental](#the-live-renderer-is-experimental) below for the exact state and how to supply your own. Read this page top to bottom: the API is final, and the parts that need a renderer are called out where they apply. ## Snapshot `Snapshot(child)` rasterizes a Flutter subtree to one image, in process, with no browser. This path is fully deterministic and runs in the gate today. ```dart Snapshot( child: Center( child: Container( padding: const EdgeInsets.all(24), color: const Color(0xFF1E2A36), child: const Text('rasterized once'), ), ), ); ``` Fluvie wraps the child in a hidden boundary, captures it once before frame 0, and paints the cached image on every frame. In preview the child renders live so you can iterate, then capture takes over at render time. Use `Snapshot` to freeze an expensive or non-deterministic subtree into one stable image. ## Mermaid `Mermaid(source, {theme, reveal})` takes the diagram source as its first argument. The source string is the only required input: ```dart const Mermaid('graph LR; A --> B; B --> C;'); ``` ### Theming Pass a `MermaidTheme` to `theme`. Two presets ship: ```dart Mermaid(source, theme: const MermaidTheme.dark()), Mermaid(source, theme: const MermaidTheme.light()), ``` The theme feeds the content hash, so a dark diagram and a light diagram from the same source rasterize to two distinct cached images. With no `theme` the diagram reads `context.fluvie.mermaid`, the inherited token theme. A `theme:` override wins over the inherited one for that element. ### The staged reveal `reveal` is a `MermaidReveal` and has three modes: ```dart Mermaid(src, reveal: MermaidReveal.none), // the whole diagram at once (default) Mermaid(src, reveal: MermaidReveal.fadeNodes(1.seconds)), // nodes fade in over the window Mermaid(src, reveal: MermaidReveal.drawEdges(1.seconds)), // edges draw on over the window ``` The reveal carries a `Time` that resolves against the element window, so a relative time scales with the scene. The reveal drives per-frame opacity or a clip over the single rendered raster. It does not re-rasterize the diagram per frame, so a 4 second reveal costs the same as no reveal at render time. ## WebView and Html `Html(source, {viewport})` renders an HTML string to one image at a fixed viewport. `WebView.url(uri, {viewport, scroll, clip})` does the same for a URL: ```dart Html('

fluvie.dev

', viewport: const SnapshotViewport(width: 720, height: 405)), WebView.url('https://fluvie.dev', viewport: const SnapshotViewport(width: 1280, height: 720)), ``` `SnapshotViewport` fixes the layout box in logical pixels (`width`, `height`, and `deviceScale`, which defaults to `1.0`). A fixed viewport is what makes the raster deterministic: the same page laid out in the same box produces the same image. `WebView.url` also takes an optional `scroll` (an `Offset`) and `clip` (a `Rect`) to capture part of a tall page. Every `WebView.url` host passes through the network allowlist before any navigation. A host that is not on the allowlist throws a `FluvieRenderException` during resolution, so a render never reaches out to an address you did not permit. ## DeviceFrame `DeviceFrame.phone({child})`, `DeviceFrame.browser({child})`, and `DeviceFrame.tablet({child})` wrap any child in presentational chrome: a phone bezel and notch, a browser address bar and traffic lights, or a tablet bezel. The frame draws no raster and runs no service. It composes over any child, including a snapshot: ```dart child: const DeviceFrame.browser( url: 'https://fluvie.dev', child: SizedBox.expand(child: Html(_page, viewport: _viewport)), ).animate([Animation.slideFadeIn()]), ``` That captures the inline HTML to a raster, paints it inside a browser window with the URL in the address bar, and slides the framed page in. `DeviceFrame.browser` takes an optional `url:` string for the address bar. The chrome colors come from `context.fluvie`, so the frame matches your theme. ## Reusing Markdown `Markdown` from the code-and-terminal phase composes here too. It parses a document once and renders it to widgets, with the same intrinsic reveal: ```dart child: const Markdown( _notes, reveal: Time.seconds(1), ).animate([Animation.fadeIn()]), ``` Lesson 09 pairs a Mermaid diagram, a Markdown explainer, and a framed web page in one explainer. See [Code and terminal videos](code-and-terminal-videos.md) for the full `Markdown` reference. ## The live renderer is experimental `Mermaid`, `WebView`, and `Html` resolve through an injected `SnapshotService`. In this version the bundled headless-Chrome renderer is experimental and not yet wired. Two failure modes name what is wrong rather than painting a blank frame: the bundled `ChromeSnapshotService` raises a `FluvieRenderException` ("live capture is not wired in this build"), and when no service is supplied at all a `Mermaid`/`WebView`/`Html` capture raises a `FluvieRenderException` naming the source and the pre-resolution pass. So live diagram and page rasterization is not available out of the box yet. To rasterize a `Mermaid`, `WebView`, or `Html` today, you supply a `SnapshotService`. The example app uses an offline fixture service that maps known requests to committed images, which is why lesson 09 renders offline with no Chromium and no network. What works now: - `Snapshot(child)` rasterizes any subtree in process, fully deterministic. - `DeviceFrame.phone/browser/tablet` chrome over any child. - The full API for `Mermaid`, `WebView`, and `Html`, plus the rasterize-once caching model. - Your own `SnapshotService` (an offline fixture one is enough). What is forthcoming: - The bundled Mermaid and WebView live renderer, so live rasterization works with no service to supply. When the bundled renderer is enabled and Chromium is missing, the service throws a typed `FluvieSnapshotUnavailableError`. That error names the missing capability and the install fix, so a fresh clone gets a clear message rather than a blank frame. ## Rasterized once, cached by content Every element here is a pure function of its source, its viewport or theme, and its reveal progress. The rasterize step runs once per content and is cached by content hash, never per frame. The same input paints the same way every time, so diagrams, pages, and snapshots cache and golden like every other element. ## Where to next - [Code and terminal videos](code-and-terminal-videos.md): the `Markdown`, `Code`, and `Terminal` elements a diagram sits beside. - [Images and video clips](images-and-video-clips.md): the media pipeline a snapshot rides, pre-resolved before the frame loop. # Example apps Fluvie ships a set of small, kitten-themed example apps under `examples/`. Each one exercises a different way to turn a Fluvie composition into a real MP4: the encoder backends, the server, and the in-process render. They share one cohesive look through the `examples/kitten_kit` package (theme, sample media, and reusable composition builders), so each app stays tiny. These are **apps that host a render**, so each keeps a composition registry and a committed capture harness. That is not the shape of a project you write. If you just want a video, you need no app at all: `fluvie init` scaffolds a composition file, `fluvie preview ./lib/my_video.dart` runs it live, and `fluvie render ./lib/my_video.dart --out out.mp4` writes the file. See [Start a project](../getting-started/start-a-project.md). | App | What it shows | Renders with | |---|---|---| | `gallery` | The thirteen lessons and the scrubbable inspector | CLI (desktop) and the server (web) | | `cli_quickstart` | Install the CLI and render from the terminal | `fluvie_cli` | | `desktop_studio` | A Linux desktop studio that renders to a file | `fluvie_cli`, in-process | | `mobile_purrfect` | An Android app that renders on the phone | `fluvie_mobile_encoder` | | `web_browser_studio` | A meme maker that renders in the browser | `fluvie_web_encoder` (ffmpeg.wasm) | | `web_server_studio` | A promo studio that renders on a server | `fluvie_server` | ## Run the CLI quickstart A tiny project with one composition and a capture harness. Render it with the CLI and you get an MP4. ```sh cd examples/cli_quickstart dart run fluvie_cli:fluvie render whisker_standup --out build/whisker.mp4 ``` ## Run the desktop studio (Linux) Pick a template, then render it to a file. The app shells out to the CLI. ```sh cd examples/desktop_studio flutter run -d linux ``` ## Run the mobile app (Android) Name your cat, optionally add a photo, and render a birthday card on the device. Nothing leaves the phone. ```sh cd examples/mobile_purrfect flutter run -d android ``` ## Run the in-browser meme maker Renders fully in the browser with ffmpeg.wasm, no backend. Vendor the wasm core once, then run. ```sh cd examples/web_browser_studio bash tool/fetch_ffmpeg.sh flutter run -d chrome ``` ## Run the server-render studio Customize a promo and render it on a Fluvie render server. Point it at a running server (see [Rendering on a server](rendering-on-a-server.md)). ```sh cd examples/web_server_studio flutter run -d chrome --dart-define=FLUVIE_API_URL=http://localhost:8080 ``` ## Run the gallery The thirteen lessons plus the inspector. Run it from the repo root so its render button can find the CLI. ```sh cd examples/gallery flutter run ``` ## How they are tested Each app is verified end to end in CI: the build compiles, unit tests cover the view-models and services, and a real render produces an MP4 that is probed for a valid video stream. The web apps print a `FLUVIE_E2E_RESULT` marker the headless harness reads; the desktop and mobile apps assert the written file. See [Testing](../contributing/testing.md). ## Where to next - [Your first video](../getting-started/your-first-video.md): write a composition from scratch. - [On-device mobile rendering](on-device-mobile-rendering.md) and [in the browser](on-device-web-rendering.md). - [Rendering on a server](rendering-on-a-server.md): stand up the render API the server studio calls. # Exporting your video Pick what the render writes: an MP4, a GIF, an image sequence, or an alpha-capable overlay. Set `Video.export` to one of the four modes and Fluvie encodes that container. Here are all four: ```dart Export sharable() => const Export.mp4(quality: Quality.max); // H.264 MP4, CRF 14 Export loopingThumb() => const Export.gif(fps: 12); // animated GIF at 12 fps Export forCompositing() => const Export.imageSequence(); // one PNG per frame Export overlay() => const Export.transparent(); // WebM with an alpha channel ``` With no `export`, a render writes an MP4 at the default quality. The rest of this page covers the four modes, the poster frame, and the command-line renderer. ## MP4 quality `Export.mp4(quality:)` writes an H.264 MP4. The `quality` picks the encoder's constant-rate factor (CRF), where a lower CRF means a bigger file and less compression: ```dart Export.mp4(quality: Quality.low), // CRF 28, smallest file, visible compression Export.mp4(quality: Quality.medium), // CRF 23, a rough-cut trade-off Export.mp4(quality: Quality.high), // CRF 18, the default for published videos Export.mp4(quality: Quality.max), // CRF 14, near-lossless, the largest file ``` `Quality.high` is the default, so `const Export.mp4()` writes a published-grade file. Reach for `Quality.low` for quick draft renders and `Quality.max` for an archival master. ## GIF `Export.gif(fps:)` writes an animated GIF. The `fps` samples the frames, since a GIF rarely needs the full frame rate. A lower `fps` makes a smaller file: ```dart Export.gif(fps: 15), // the default sample rate Export.gif(fps: 12), // a smaller, choppier loop ``` The encoder builds an optimized 256-color palette from your frames in one pass, then maps the frames onto it with dithering, so a GIF keeps its color and stays small. A GIF carries no audio. ## Image sequence `Export.imageSequence()` writes one lossless PNG per frame, named `frame_000000.png`, `frame_000001.png`, and so on. Reach for it when a compositing pipeline downstream wants individual frames rather than a container: ```dart const Export.imageSequence(); // one PNG per frame, into the output directory ``` The sequence carries no audio. Each still is lossless, so the pipeline starts from the exact captured pixels. ## Transparent overlay `Export.transparent()` writes a WebM with an alpha channel, so the video can layer over other footage. The captured RGBA alpha is preserved end to end: ```dart const Export.transparent(); // VP9 WebM with a yuva420p alpha plane ``` Reach for it when you render a lower-third, a logo sting, or a caption pass that sits on top of a clip in another editor. An alpha-capable overlay carries no audio. ProRes `.mov` with alpha is forthcoming; WebM ships today. ## A poster frame `Video.poster` names a `Time`, and the render grabs that one frame as a still thumbnail alongside the main output. Set it on the same `Video` as the export: ```dart Video exportedReel() => Video( size: VideoSize.reels, export: const Export.mp4(quality: Quality.max), // near-lossless, CRF 14 poster: const Time.seconds(1.5), // the thumbnail frame scenes: [ Scene.centered( duration: const Time.seconds(3), background: Background.color(const Color(0xFF0E1116)), child: const Text('Exported', style: TextStyle(fontSize: 72, color: Color(0xFFE6EDF3))), ), ], ); ``` The poster is a second output from the same frames, so it costs one extra encode of one frame. Pick a `Time` that lands on a representative moment, for example 1.5 seconds into a 3 second card. ## The command-line renderer `fluvie render` captures a composition and encodes it, with no app to open. Point it at the file: ```sh fluvie render ./lib/my_video.dart ``` It calls the file's top-level `Video build()` using a cached harness outside your project and encodes the frames. Output defaults to `build/fluvie/my_video.mp4`, with the extension or directory chosen for the authored export mode. Size, FPS, duration, quality, export mode, and poster come from the `Video`; explicit flags override the authored choices: ```sh fluvie render ./lib/my_video.dart --out reel.mp4 --aspect reels --quality high fluvie render ./lib/my_video.dart --out clip.gif --format gif fluvie render ./lib/my_video.dart --out frames/ --format imageSequence fluvie render ./lib/my_video.dart --out overlay.webm --format transparent fluvie render ./lib/my_video.dart --out hero.mp4 --poster 1.5s ``` The flags: - `--out ` overrides the automatic output path. For image sequences it names a directory. - `--entry ` names the top-level function returning the `Video`. It defaults to `build`. - `--aspect ` picks the aspect: `reels`, `square`, `landscape`, or `portrait45`. With no `--aspect` the composition renders at its declared size; pass an aspect to re-frame it. - `--quality ` picks the MP4 quality: `low`, `medium`, `high`, or `max`. - `--format ` picks the export mode: `mp4`, `gif`, `imageSequence`, or `transparent`. With no flag, the authored `Video.export` wins; otherwise MP4 is the default. - `--poster