From 83707ef757689b5e43c8ecb925e2d8d9e674b0d8 Mon Sep 17 00:00:00 2001 From: Rob Coenen <753704+rcoenen@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:25:44 +0100 Subject: [PATCH] feat(fla): legacy texts, bitmaps, sounds, buttons, scripts and library folders Wires the CPicText decoder and the anicraft-flamedia payload decoder into the legacy importer. Contents' CMediaBits/CMediaSound items become library bitmaps and sounds; CPicBitmap instances are placed as the XFL importer places them; frame sound blocks carry sound, sync, loops and envelope. CPicButton settings give instance names; handler scripts are reported and frame scripts kept verbatim as ActionScript source, never run. Label kinds, shape hints (CMorphHintItem) and library folders come across too. Filters, component settings, bitmap fills and dashed strokes stay skipped and counted. Verified against the Animate twins on every corpus pair: 335/335 texts on keyframes, 9/9 bitmap instances and items, 5/5 frame sounds, 4/4 sound items, 4457/4457 instance symbols and names, 328/328 symbol types and library paths, 39/39 folders. kinefox frame 1 and movietemplate frames 1, 120 and 500 render byte-identical to the twin's. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/fla/Cargo.toml | 2 + crates/fla/src/archive.rs | 244 ++++++++-- crates/fla/src/doc.rs | 290 ++++++++++-- crates/fla/src/lib.rs | 6 +- crates/fla/src/library.rs | 273 ++++++++++++ crates/fla/src/tests.rs | 358 ++++++++++++++- crates/fla/src/text_tests.rs | 50 +-- crates/fla/tests/corpus.rs | 421 ++++++++++++++++++ .../0096-legacy-fla-compound-binary-import.md | 94 +++- docs/roadmap.md | 2 +- 11 files changed, 1628 insertions(+), 113 deletions(-) create mode 100644 crates/fla/src/library.rs diff --git a/Cargo.lock b/Cargo.lock index c683555d..79916450 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -341,6 +341,7 @@ name = "anicraft-fla" version = "0.3.0" dependencies = [ "anicraft-doc", + "anicraft-flamedia", "anicraft-geom", "anicraft-text", "anicraft-xml", diff --git a/crates/fla/Cargo.toml b/crates/fla/Cargo.toml index 5da6dd64..9dc6eea3 100644 --- a/crates/fla/Cargo.toml +++ b/crates/fla/Cargo.toml @@ -12,6 +12,8 @@ anicraft-doc.workspace = true anicraft-geom.workspace = true # Lays imported text out with the fonts on this computer, as the XFL importer does (ADR 0012). anicraft-text.workspace = true +# Animate's own bitmap and sound payloads: the `Media` streams are the XFL twins' `bin/*.dat` files. +anicraft-flamedia.workspace = true thiserror.workspace = true [dev-dependencies] diff --git a/crates/fla/src/archive.rs b/crates/fla/src/archive.rs index 58613da3..20a23cc1 100644 --- a/crates/fla/src/archive.rs +++ b/crates/fla/src/archive.rs @@ -22,12 +22,14 @@ //! frame children: the keyframe's objects · its raw artwork (a shape body, see //! [`crate::shape`]) · u32 n · n × 32 (cubic drawing hints) · 18 · u16 duration · //! u8 tween (0 none, 1 classic, 2 shape) · u8 tween flags · i16 ease · -//! u16 sound · u16 n · n × 8 (envelope) · u16 loops · u8 sync · u32 in · u32 out · -//! u16 zoom · label · frame actions (16 bytes, the script) · 8 bytes · u32 label kind (1 comment) · -//! shape-tween cache (an object) · 4 bytes · shape hints (an object) · string · -//! 5 × u32, the last 1 when custom eases follow: 6 curves (position, rotation, scale, -//! colour, filters, all), each u32 n and n anchors of 3 points (in handle, anchor, -//! out handle) as f64 x, y +//! u16 sound (a `Contents` media item id, 0 none) · u16 n · n × (u32 mark44, u16 +//! left, u16 right) (envelope) · u16 loops · u8 sync · u32 in · u32 out (0x3FFFFFFF +//! unset) · u16 zoom · label · actions (16 bytes, then the frame script string) · +//! 8 bytes · u32 label kind (1 comment) · shape-tween cache (an object) · 4 bytes · +//! shape hints (an object: a `CObList` of `CMorphHintItem`s, each i32 start x, y, +//! end x, y in twips and a u32 key) · string · 5 × u32, the last 1 when custom eases +//! follow: 6 curves (position, rotation, scale, colour, filters, all), each u32 n +//! and n anchors of 3 points (in handle, anchor, out handle) as f64 x, y //! shape children: a group's members · a shape body · cubic hints; the base u16 is 1 for a //! drawing object; without members, flag bit 0 marks a loose (raw) shape and no //! bit a group of one @@ -37,18 +39,26 @@ //! 4 alpha) · u8 · i16 percent · RGBA tint · instance name · u16 library item id · //! 3 bytes · persistent data (u8 flag; u32 1, u32 n, n × (u8 5, name, value)) · u8 · //! u8 filter count · u8 blend (SWF numbering) · u16; movie clips (`CPicSprite`) and -//! buttons (`CPicButton`) carry more after it +//! buttons (`CPicButton`) carry more after it: +//! button 0B · actions (16 bytes, then the handler script string) · u8 (track as menu, a +//! hypothesis: 0 throughout the corpus) · instance name · u32 0 +//! sprite 08 · actions (16 bytes, then the clip-event script string) · instance name · +//! component settings (not decoded, skipped) +//! text see [`crate::text`] +//! bitmap a, b, c, d (16.16), tx, ty (twips) · u16 media item id (`Contents`) · u8 (0) //! ``` //! //! The instance's two base i32 are its transformation point already placed on the stage //! (`M · p`). Strings are UTF-16 behind `FF FE FF` and a u8 length (`FF`, then a u16, past 254). //! -//! What isn't decoded — texts, bitmaps, a movie clip's or button's extra settings — is skipped -//! by finding where the parent continues: its own end (`00 00`, then its base with its kind +//! What isn't decoded — a movie clip's component settings, filter lists, objects of other +//! classes, a text or bitmap record in a layout not seen — is skipped by finding where the +//! parent continues: its own end (`00 00`, then its base with its kind //! byte) or the next sibling object, checked by parsing that sibling. Nothing here panics or //! reads past the end; a stream that doesn't make sense is refused as a whole. use crate::shape::{self, ShapeRecord}; +use crate::text::TextRecord; use anicraft_geom::Affine; /// Most objects one stream may hold. @@ -70,6 +80,12 @@ pub const KIND_PAGE: u8 = 0x07; pub const KIND_LAYER: u8 = 0x0B; pub const KIND_SHAPE: u8 = 0x03; pub const KIND_INSTANCE: u8 = 0x13; +pub const KIND_BITMAP: u8 = 0x02; +/// A frame's sound out point when none is set (the sound plays to its end). +pub const NO_OUT_POINT: u32 = 0x3FFF_FFFF; +/// The first byte of a button instance's own settings, and of a movie clip's. +const BUTTON_EXTRAS: u8 = 0x0B; +const SPRITE_EXTRAS: u8 = 0x08; /// The stream doesn't follow the grammar here. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -94,6 +110,9 @@ pub struct LayerRec { pub frames: Vec, } +/// A shape hint as stored: its start and its end point, in twips. +pub type HintRec = ((i32, i32), (i32, i32)); + /// A keyframe record. #[derive(Clone, Debug, Default)] pub struct FrameRec { @@ -105,8 +124,19 @@ pub struct FrameRec { pub ease: i16, /// The sound's library item id (0: none). pub sound: u16, + /// The sound's volume envelope: (time in samples at 44.1 kHz, left, right level 0..=32768). + pub envelope: Vec<(u32, u16, u16)>, + /// Times the sound plays (1 = once). + pub loops: u16, + /// The sound's sync byte (3 stream on every corpus sound frame; 0 event, 1 start, 2 stop + /// by Flash's menu order, a hypothesis). + pub sync: u8, + /// The sound's in and out points in samples at 44.1 kHz ([`NO_OUT_POINT`]: none). + pub in_point: u32, + pub out_point: u32, pub label: String, - /// 1: the label is a comment. + /// 1: the label is a comment (0, a name, and 2, an anchor, are hypotheses: the corpus + /// labels are all comments). pub label_kind: u32, /// Custom ease curves by group (position, rotation, scale, colour, filters, all): each a /// list of anchors (in handle x, y, anchor x, y, out handle x, y). Empty: no custom ease. @@ -115,9 +145,10 @@ pub struct FrameRec { pub raw: Option, /// Why the raw artwork didn't decode, when it didn't. pub raw_error: Option, - pub hints: bool, - /// The keyframe has a frame script (kept for a later pass). - pub script: bool, + /// The shape hints listed on the keyframe, in letter order: (start, end) in twips. + pub hints: Vec, + /// The frame script, as written (empty: none). + pub script: String, /// The keyframe's objects, bottom first, as nodes. pub elements: Vec, } @@ -159,10 +190,22 @@ pub struct InstanceRec { pub item: u16, pub blend: u8, pub filters: u8, - /// The record's tail (a movie clip's or button's settings, filters) was skipped. + /// A button's handler or a movie clip's clip-event script, as written (empty: none). + pub script: String, + /// A button's track-as-menu byte (a hypothesis: 0 throughout the corpus). + pub track_as_menu: bool, + /// The record's tail (a movie clip's component settings, filters) was skipped. pub extras_skipped: bool, } +/// A bitmap instance record. +#[derive(Clone, Debug)] +pub struct BitmapRec { + pub matrix: Affine, + /// The bitmap's media item id (`Contents`). + pub item: u16, +} + /// A shape object: a drawing object, a loose shape, or a group. #[derive(Clone, Debug, Default)] pub struct ShapeObj { @@ -182,9 +225,14 @@ pub enum Node { Frame(Box), Shape(ShapeObj), Instance(Box), - /// A shape tween's cache, or its hints: rebuilt by AniCraft. + Text(Box), + Bitmap(BitmapRec), + /// A shape tween's cache: rebuilt by AniCraft. Morph, - Hints, + /// A list of objects (`CObList`, the shape-hint list). + List(Vec), + /// One shape hint: start and end in twips. + Hint((i32, i32), (i32, i32)), /// An object not decoded, by class name. Skipped(String), } @@ -452,16 +500,22 @@ impl<'a> Parser<'a> { } "CObList" => { let n = self.u16()?; + let mut items = Vec::with_capacity(usize::from(n).min(64)); for _ in 0..n { - self.obj(None)?; + if let Some(i) = self.obj(None)? { + items.push(i); + } } - Ok(Node::Hints) + Ok(Node::List(items)) } "CMorphHintItem" => { - self.skip(20)?; - Ok(Node::Hints) + let (sx, sy, ex, ey) = (self.i32()?, self.i32()?, self.i32()?, self.i32()?); + self.skip(4)?; // the key + Ok(Node::Hint((sx, sy), (ex, ey))) } - // Texts, bitmaps and anything newer: skipped to where their parent continues. + "CPicText" => self.text(parent), + "CPicBitmap" => self.bitmap(parent), + // Anything newer: skipped to where its parent continues. _ => { self.resync(parent)?; Ok(Node::Skipped(name)) @@ -707,16 +761,26 @@ impl<'a> Parser<'a> { let sound = self.u16()?; let n = self.u16()?; let n = self.count(n as u32)?; - self.skip(n.checked_mul(8).ok_or(Bad)?)?; - self.skip(2 + 1 + 4 + 4 + 2)?; // loops, sync, in, out, zoom + let mut envelope = Vec::with_capacity(n.min(64)); + for _ in 0..n { + envelope.push((self.u32()?, self.u16()?, self.u16()?)); + } + let loops = self.u16()?; + let sync = self.u8()?; + let in_point = self.u32()?; + let out_point = self.u32()?; + self.skip(2)?; // the sound's zoom in the editor let label = self.string()?; self.skip(16)?; // the frame actions' header - let script = !self.string()?.trim().is_empty(); + let script = self.string()?; self.skip(8)?; let label_kind = self.u32()?; self.obj(None)?; // the shape tween's cache self.skip(4)?; - let hints = self.obj(None)?.is_some(); + let hints = match self.obj(None)? { + Some(list) => self.hints_of(list), + None => Vec::new(), + }; self.string()?; let mut flags = [0u32; 5]; for v in flags.iter_mut() { @@ -738,7 +802,63 @@ impl<'a> Parser<'a> { eases.push(curve); } } - Ok(FrameRec { duration, tween, tween_flags, ease, sound, label, label_kind, eases, raw: None, raw_error: None, hints, script, elements: Vec::new() }) + Ok(FrameRec { duration, tween, tween_flags, ease, sound, envelope, loops, sync, in_point, out_point, label, label_kind, eases, raw: None, raw_error: None, hints, script, elements: Vec::new() }) + } + + /// The hints in a decoded hint list, in order. + fn hints_of(&self, list: usize) -> Vec { + let Some(Node::List(items)) = self.nodes.get(list) else { return Vec::new() }; + items.iter().filter_map(|&i| match self.nodes.get(i) { + Some(Node::Hint(a, b)) => Some((*a, *b)), + _ => None, + }).collect() + } + + /// Whether the bytes at `i` are where an object's parent (of kind `parent`) continues: its + /// end, or a next sibling's head. Without a known parent, anything goes. + fn continues_at(&self, i: usize, parent: Option) -> bool { + match parent { + Some(k) => self.parent_end_at(i, k) || self.sibling_head_at(i), + None => true, + } + } + + /// A text record (its head here), decoded by [`crate::text`]; one in a layout not seen, + /// or that doesn't end where its parent continues, is skipped. + fn text(&mut self, parent: Option) -> R { + if let Ok(t) = crate::text::decode(self.d, self.at) + && self.continues_at(t.end, parent) + { + self.budget = self.budget.saturating_sub(t.end.saturating_sub(self.at)); + self.at = t.end; + return Ok(Node::Text(Box::new(t))); + } + self.resync(parent)?; + Ok(Node::Skipped("CPicText".into())) + } + + /// A bitmap instance: the common head (kind 02, no children), its matrix, its media item + /// id and a byte (0 on every corpus instance); one in a layout not seen is skipped. + fn bitmap(&mut self, parent: Option) -> R { + let snap = self.snap(); + let decoded = (|| -> R { + let base = self.base(KIND_BITMAP)?; + if !base.children.is_empty() { + return Err(Bad); + } + let matrix = self.matrix()?; + let item = self.u16()?; + self.skip(1)?; // 0 throughout the corpus + Ok(BitmapRec { matrix, item }) + })(); + match decoded { + Ok(b) if self.continues_at(self.at, parent) => Ok(Node::Bitmap(b)), + _ => { + self.restore(snap); + self.resync(parent)?; + Ok(Node::Skipped("CPicBitmap".into())) + } + } } fn instance(&mut self, class: InstanceClass, parent: Option) -> R { @@ -777,19 +897,77 @@ impl<'a> Parser<'a> { } self.skip(1)?; let filters = self.u8()?; - let mut rec = InstanceRec { class, locked: base.flag & 0x04 != 0, matrix, point: (base.x, base.y), first_frame, loop_mode, color, name, item, blend: 1, filters, extras_skipped: false }; - if filters == 0 { - rec.blend = self.u8()?; - self.skip(2)?; - } - if filters != 0 || class != InstanceClass::Graphic { - // Filters (layout not decoded) and a movie clip's or button's settings. + let mut rec = InstanceRec { + class, + locked: base.flag & 0x04 != 0, + matrix, + point: (base.x, base.y), + first_frame, + loop_mode, + color, + name, + item, + blend: 1, + filters, + script: String::new(), + track_as_menu: false, + extras_skipped: false, + }; + if filters != 0 { + // A filter list (layout not decoded), the blend after it, and any settings. self.resync(parent)?; rec.extras_skipped = true; + return Ok(Node::Instance(Box::new(rec))); + } + rec.blend = self.u8()?; + self.skip(2)?; + if class != InstanceClass::Graphic { + let snap = self.snap(); + if !self.extras(&mut rec, parent) { + // Settings in a layout not seen: skipped whole. + self.restore(snap); + rec.script.clear(); + rec.track_as_menu = false; + self.resync(parent)?; + rec.extras_skipped = true; + } } Ok(Node::Instance(Box::new(rec))) } + /// A button's or movie clip's own settings after the common instance fields: whether they + /// decoded (a movie clip's component settings after its name are skipped, and say so). + fn extras(&mut self, rec: &mut InstanceRec, parent: Option) -> bool { + let want = if rec.class == InstanceClass::Button { BUTTON_EXTRAS } else { SPRITE_EXTRAS }; + let head = (|| -> R<()> { + if self.u8()? != want { + return Err(Bad); + } + self.skip(16)?; // the actions' header + rec.script = self.string()?; + if rec.class == InstanceClass::Button { + rec.track_as_menu = self.u8()? != 0; + } + let name = self.string()?; + if !name.trim().is_empty() { + rec.name = name; + } + Ok(()) + })(); + if head.is_err() { + return false; + } + if rec.class == InstanceClass::Button { + return self.u32().is_ok_and(|z| z == 0) && self.continues_at(self.at, parent); + } + // A movie clip's component settings: not decoded. + if self.resync(parent).is_err() { + return false; + } + rec.extras_skipped = true; + true + } + /// A shape tween's cache: version 2, two matrices, 8 bytes, its segments (objects), then /// its fill styles (RGBA, kind, a byte; a gradient adds a matrix, a count and 5-byte /// stops) and strokes (10 bytes each). diff --git a/crates/fla/src/doc.rs b/crates/fla/src/doc.rs index 9d734bdc..3bd874b9 100644 --- a/crates/fla/src/doc.rs +++ b/crates/fla/src/doc.rs @@ -7,25 +7,32 @@ //! stream (`P `) and library stream (`S `, `Symbol `) holds one //! timeline as an object graph ([`crate::archive`]): layers (stored bottom-first), their //! keyframes, each keyframe's raw artwork and objects (symbol instances, drawing objects, -//! groups). The mapping mirrors the XFL importer's, so a legacy file and its Animate twin open -//! with the same structure: folder layers hold no frames, raw shapes merge (ADR 0042), comments -//! are reported, classic and shape tweens with their eases. +//! groups, texts, bitmaps). `Contents` also lists the library's folders, bitmaps and sounds +//! ([`crate::library`]); their data streams decode through `anicraft_flamedia`. The mapping +//! mirrors the XFL importer's, so a legacy file and its Animate twin open with the same +//! structure: folder layers hold no frames, raw shapes merge (ADR 0042), comments are reported, +//! classic and shape tweens with their eases and hints, frame sounds with their sync, repeats +//! and envelope, frame scripts kept as written (never run here), instance handlers reported. //! -//! What isn't decoded yet — texts, bitmaps, sounds, a movie clip's or button's extra settings -//! — is left out and counted in the report; a timeline that doesn't decode at all falls back -//! to the structure-only reading (layer names, a symbol's first shape). +//! What isn't decoded yet — a movie clip's component settings, filters, bitmap fills — is left +//! out and counted in the report; a timeline that doesn't decode at all falls back to the +//! structure-only reading (layer names, a symbol's first shape). use crate::archive::{self, Graph, InstanceClass, Node}; use crate::cfb::Compound; +use crate::library::{self, ItemId, MediaKind}; use crate::shape; use crate::report::{ImportError, Report}; +use crate::text::Faces; use anicraft_doc::ColorTransform; use anicraft_doc::{ - BlendMode, ColorEffect, CustomEase, Document, EaseGroup, Easing, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Rgba, Scene, Stage, Symbol, - SymbolId, SymbolKind, Timeline, Tween, TweenKind, + Bitmap, BitmapId, BlendMode, ColorEffect, CustomEase, Document, EaseGroup, Easing, Element, ElementId, ElementKind, EnvelopePoint, FrameScript, FrameSound, Keyframe, + Language, Layer, LayerId, LayerKind, LibraryEntry, LibraryItem as DocItem, LoopMode, Paint, Rgba, Scene, Shape, ShapeHint, Sound, SoundEffect, SoundId, SoundSync, SourceScript, + Stage, Symbol, SymbolId, SymbolKind, Timeline, Tween, TweenKind, }; -use anicraft_geom::Vec2; -use std::collections::HashMap; +use anicraft_geom::{FillRule, Path, Vec2}; +use anicraft_text::Fonts; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; /// The `Contents` stream's version byte on every corpus file of the Flash 8–CS4 era. @@ -60,6 +67,8 @@ pub struct LibraryItem { pub id: u32, /// 0 graphic, 1 button, 2 movie clip. pub kind: u8, + /// The folder it sits in, when its entry says (`library::ROOT`: the library's root). + pub parent: Option, } /// What the mapping needs while it builds timelines. @@ -68,6 +77,14 @@ struct Ctx<'a> { report: &'a mut Report, /// Library item id → symbol. symbols: &'a HashMap, + /// Media item id → bitmap, and → sound. + bitmaps: &'a HashMap, + sounds: &'a HashMap, + /// The fonts texts are laid out with, and the faces looked up so far. + fonts: &'a Fonts, + faces: &'a mut Faces, + /// The language frame scripts are written in. + language: Language, } /// Imports a legacy `.fla` into the AniCraft model. @@ -88,6 +105,23 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> { doc.scenes.clear(); doc.library.clear(); doc.stage = stage(&contents).unwrap_or_default(); + // The library's folders first (empty ones come across too, as in the XFL importer). + let folder_list = library::folders(&contents); + let folders = library::folder_paths(&folder_list); + for f in &folder_list { + if let Some(path) = folders.get(&f.id) { + doc.ensure_folder_path(path); + } + } + if !doc.library_tree.folders.is_empty() { + report.keep("library folders"); + } + let language = match library::script_version(&contents).as_deref() { + Some("1" | "2") => Language::ActionScript1or2, + // As the XFL importer: ActionScript 3.0 unless the file says otherwise. + _ => Language::ActionScript3, + }; + let (bitmaps, sounds) = media(&file, &contents, &folders, &mut doc, &mut report); // Symbols first, so instances can refer to any of them. let mut symbols: HashMap = HashMap::new(); let mut ids = Vec::with_capacity(items.len()); @@ -96,9 +130,14 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> { symbols.insert(item.id, id); ids.push(id); } + let fonts = Fonts::get(); + let mut faces = Faces::new(); for (item, &id) in items.iter().zip(&ids) { let timeline = match file.stream(&item.stream) { - Ok(bytes) => library_timeline(&bytes, &item.label, &mut doc, &mut report, &symbols), + Ok(bytes) => { + let mut ctx = Ctx { doc: &mut doc, report: &mut report, symbols: &symbols, bitmaps: &bitmaps, sounds: &sounds, fonts, faces: &mut faces, language }; + library_timeline(&bytes, &item.label, &mut ctx) + } Err(_) => { report.skip_named("library symbols whose stream is missing", item.label.clone()); Timeline { layers: vec![Arc::new(Layer::new(LayerId(doc.alloc_id()), "Layer 1"))] } @@ -110,6 +149,7 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> { _ => SymbolKind::MovieClip, }; doc.library.push(Arc::new(Symbol { id, name: item.label.clone(), kind, linkage: None, scale_grid: None, scale_grid_kept: None, timeline })); + place_in_folder(&mut doc, &folders, item.parent, DocItem::Symbol(id)); report.keep("library symbols"); } for page in &pages { @@ -117,7 +157,7 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> { match file.stream(&page.stream) { Ok(bytes) => match archive::parse(&bytes) { Ok(graph) => { - let mut ctx = Ctx { doc: &mut doc, report: &mut report, symbols: &symbols }; + let mut ctx = Ctx { doc: &mut doc, report: &mut report, symbols: &symbols, bitmaps: &bitmaps, sounds: &sounds, fonts, faces: &mut faces, language }; timeline = build_timeline(&graph, &mut ctx); } Err(_) => { @@ -144,16 +184,100 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> { Ok((doc, report)) } +/// Puts a library item in its folder (when its entry names one `Contents` lists). +fn place_in_folder(doc: &mut Document, folders: &HashMap, parent: Option, item: DocItem) { + if let Some(path) = parent.and_then(|p| folders.get(&p)) + && let Some(f) = doc.ensure_folder_path(path) + { + doc.place_entry(LibraryEntry::Item(item), Some(f)); + } +} + +/// The library's bitmaps and sounds (`Contents`' media items), their data decoded from their +/// streams the way the XFL importer decodes the same payloads in `bin/` (`anicraft_flamedia`): +/// a bitmap in Animate's own lossless layout, or a PNG or JPEG; a sound as raw 16-bit PCM of +/// its item's format and sample count (it comes across as a WAV), or a WAV, Ogg Vorbis or MP3 +/// file. What doesn't decode is reported by name, with why. +fn media(file: &Compound, contents: &[u8], folders: &HashMap, doc: &mut Document, report: &mut Report) -> (HashMap, HashMap) { + let streams: HashSet = file.entries().iter().filter(|e| e.kind == crate::cfb::Kind::Stream).map(|e| e.path.clone()).collect(); + let (mut bitmaps, mut sounds) = (HashMap::new(), HashMap::new()); + for item in library::media_items(contents, |s| streams.contains(s)) { + if bitmaps.contains_key(&item.id) || sounds.contains_key(&item.id) { + continue; + } + let shown = item.name.clone(); + let Ok(bytes) = file.stream(&item.stream) else { + report.skip_named("media whose stream couldn't be read", shown); + continue; + }; + let kind = item.kind.unwrap_or(if anicraft_flamedia::is_bitmap(&bytes) { MediaKind::Bitmap } else { MediaKind::Sound }); + match kind { + MediaKind::Bitmap => { + let decoded = if anicraft_flamedia::is_bitmap(&bytes) { + anicraft_flamedia::decode_bitmap(&bytes).map_err(|e| e.to_string()).and_then(|px| { + Bitmap::from_rgba(BitmapId(0), item.name.clone(), px.width, px.height, px.rgba).ok_or_else(|| anicraft_flamedia::DatError::BadSize.to_string()) + }) + } else { + Bitmap::from_image(BitmapId(0), item.name.clone(), bytes).map_err(|_| "not a format AniCraft reads".to_string()) + }; + match decoded { + Ok(mut b) => { + b.id = BitmapId(doc.alloc_id()); + b.smoothing = true; + bitmaps.insert(item.id, b.id); + place_in_folder(doc, folders, Some(item.parent), DocItem::Bitmap(b.id)); + doc.bitmaps.push(Arc::new(b)); + report.keep("bitmaps"); + } + Err(why) => report.skip_named("bitmaps in Animate's own format AniCraft can't decode", format!("{shown}: {why}")), + } + } + MediaKind::Sound => { + // Raw PCM when it is exactly the item's sample count of its format; otherwise a + // sound file kept as it came. + let mut raw_why = None; + let mut sound = None; + if let Some((format, count)) = item.sound { + match anicraft_flamedia::SoundFormat::from_legacy(format).and_then(|f| anicraft_flamedia::decode_sound(&bytes, f, Some(u64::from(count)))) { + Ok(pcm) => match pcm.to_wav().map(|wav| Sound::from_data(SoundId(0), item.name.clone(), wav)) { + Some(Ok(s)) => sound = Some(s), + Some(Err(e)) => raw_why = Some(e.to_string()), + None => raw_why = Some(anicraft_flamedia::DatError::TooLong.to_string()), + }, + Err(anicraft_flamedia::DatError::LengthMismatch { .. }) => {} + Err(e) => raw_why = Some(e.to_string()), + } + } + let sound = match sound { + Some(s) => Ok(s), + None => Sound::from_data(SoundId(0), item.name.clone(), bytes).map_err(|e| raw_why.map_or_else(|| e.to_string(), |r| format!("Animate's own sound data ({r})"))), + }; + match sound { + Ok(mut s) => { + s.id = SoundId(doc.alloc_id()); + sounds.insert(item.id, s.id); + place_in_folder(doc, folders, Some(item.parent), DocItem::Sound(s.id)); + doc.sounds.push(Arc::new(s)); + report.keep("sounds"); + } + Err(why) => report.skip_named("sounds in formats AniCraft can't decode", format!("{shown}: {why}")), + } + } + } + } + (bitmaps, sounds) +} + /// A library item's timeline: its stream's object graph, or (when that doesn't decode) its /// first shape record on one keyframe. -fn library_timeline(bytes: &[u8], label: &str, doc: &mut Document, report: &mut Report, symbols: &HashMap) -> Timeline { +fn library_timeline(bytes: &[u8], label: &str, ctx: &mut Ctx) -> Timeline { if let Ok(graph) = archive::parse(bytes) { - let mut ctx = Ctx { doc, report, symbols }; - let tl = build_timeline(&graph, &mut ctx); + let tl = build_timeline(&graph, ctx); if !tl.layers.is_empty() { return tl; } } + let (doc, report) = (&mut *ctx.doc, &mut *ctx.report); let shapes = shapes(bytes, report); let layer = Layer::new(LayerId(doc.alloc_id()), "artwork"); if shapes.is_empty() { @@ -200,6 +324,7 @@ fn build_timeline(graph: &Graph, ctx: &mut Ctx) -> Timeline { continue; } let mut keys = Vec::new(); + let mut hints: HashMap> = HashMap::new(); let mut start = 0u32; for &f in &rec.frames { let Some(Node::Frame(frame)) = graph.node(f) else { @@ -213,6 +338,9 @@ fn build_timeline(graph: &Graph, ctx: &mut Ctx) -> Timeline { if duration == 0 { continue; } + if !frame.hints.is_empty() { + hints.insert(at, frame.hints.clone()); + } keys.push(Arc::new(keyframe(graph, frame, at, duration.clamp(1, MAX_FRAME), ctx))); ctx.report.keep("keyframes"); } @@ -220,6 +348,9 @@ fn build_timeline(graph: &Graph, ctx: &mut Ctx) -> Timeline { layer.keyframes = keys; } layer.normalize(); + if !hints.is_empty() { + pair_hints(&mut layer, &hints, ctx.report); + } layers.push(Arc::new(layer)); } let mut tl = Timeline { layers }; @@ -230,6 +361,8 @@ fn build_timeline(graph: &Graph, ctx: &mut Ctx) -> Timeline { fn keyframe(graph: &Graph, frame: &archive::FrameRec, start: u32, duration: u32, ctx: &mut Ctx) -> Keyframe { let mut k = Keyframe::new(start, duration); if !frame.label.is_empty() { + // Label kind 1 is a comment (every corpus label); 0, a name, and 2, an anchor, are a + // hypothesis (Flash's menu order) and both a label, as XFL's names and anchors are. if frame.label_kind == 1 { // A note to the animator that nothing can go to: no place for it yet. ctx.report.skip("frame comments"); @@ -246,18 +379,15 @@ fn keyframe(graph: &Graph, frame: &archive::FrameRec, start: u32, duration: u32, t.set_ease(g, Some(e)); } k.tween = Some(t); - if frame.hints { - ctx.report.skip("shape hints (left out)"); - } } 0 => {} _ => ctx.report.skip("tweens of an unknown kind (kept as keyframes)"), } - if frame.script { - ctx.report.skip("frame scripts (decode pending)"); + if !frame.script.trim().is_empty() { + k.script = frame_script(&frame.script, ctx); } if frame.sound != 0 { - ctx.report.skip("frame sounds (decode pending)"); + k.sound = frame_sound(frame, ctx); } let mut elements = Vec::new(); // The keyframe's raw artwork sits below its objects, its shapes merging (ADR 0042). @@ -276,6 +406,87 @@ fn keyframe(graph: &Graph, frame: &archive::FrameRec, start: u32, duration: u32, k } +/// A frame script, exactly as written, in the document's language: kept (ADR 0013 tier 1), as +/// the XFL importer keeps ``; nothing here runs it. +fn frame_script(text: &str, ctx: &mut Ctx) -> Option { + let script = SourceScript::new(ctx.language, text); + if script.check().is_err() { + ctx.report.skip("frame scripts over 1 MiB (left out)"); + return None; + } + let what = format!("frame scripts in {}", ctx.language.label()); + if script.runs() { + *ctx.report.runs.entry(what).or_default() += 1; + } else { + ctx.report.keep(&what); + } + Some(FrameScript::Source(Arc::new(script))) +} + +/// The sound on a keyframe, as the XFL importer reads a frame's `soundName`: its sync (by +/// Flash's menu order, 0 event, 1 start, 2 stop, 3 stream; only stream is in the corpus), +/// repeats and envelope (time in samples at 44.1 kHz, levels `0..=32768`). In and out points +/// are reported (played whole), as there. +fn frame_sound(frame: &archive::FrameRec, ctx: &mut Ctx) -> Option { + let Some(&id) = ctx.sounds.get(&frame.sound) else { + ctx.report.skip("frame sounds whose sound isn't in the file"); + return None; + }; + let mut fs = FrameSound::new(id); + fs.sync = match frame.sync { + 0 => SoundSync::Event, + 1 => SoundSync::Start, + 2 => SoundSync::Stop, + 3 => SoundSync::Stream, + _ => { + ctx.report.skip("sound syncs of an unknown kind (played as event)"); + SoundSync::Event + } + }; + fs.repeat = u32::from(frame.loops).clamp(1, anicraft_doc::sound::MAX_REPEAT); + let points: Vec = frame + .envelope + .iter() + .take(anicraft_doc::sound::MAX_ENVELOPE_POINTS) + .map(|&(mark, left, right)| EnvelopePoint::new(f64::from(mark) / 44_100.0, f32::from(left) / 32_768.0, f32::from(right) / 32_768.0)) + .collect(); + // The format has no effect byte: an envelope plays as its points (as the XFL importer + // reads an envelope without a preset name). + if !points.is_empty() { + fs.effect = SoundEffect::Custom(anicraft_doc::sound::clean_points(&points)); + } + if frame.in_point != 0 || frame.out_point != archive::NO_OUT_POINT { + ctx.report.skip("sound in and out points (played whole)"); + } + Some(fs) +} + +/// Gives each shape tween on `layer` the hints its start keyframe lists (each with its start +/// and its end point, twips), snapped onto the outlines when they sit within a couple of +/// pixels of one, as the XFL importer pairs them. +fn pair_hints(layer: &mut Layer, raw: &HashMap>, report: &mut Report) { + const SNAP: f32 = 2.0; + let snap = |els: &[Arc], p: Vec2| match anicraft_doc::nearest_outline(els, p) { + Some((_, q, d)) if d <= SNAP => q, + _ => p, + }; + let px = |(x, y): (i32, i32)| Vec2::new(x as f32 / 20.0, y as f32 / 20.0); + for i in 0..layer.keyframes.len() { + let (Some(k), Some(next)) = (layer.keyframes.get(i), layer.keyframes.get(i + 1)) else { continue }; + let Some(list) = raw.get(&k.start) else { continue }; + if !layer.is_shape_tween(i) { + continue; + } + if list.len() > anicraft_doc::MAX_SHAPE_HINTS { + report.skip("shape hints past z"); + } + let hints: Vec = list.iter().take(anicraft_doc::MAX_SHAPE_HINTS).map(|&(a, b)| ShapeHint { start: snap(&k.elements, px(a)), end: snap(&next.elements, px(b)) }).collect(); + if let Some(k) = layer.keyframes.get_mut(i) { + Arc::make_mut(k).hints = hints; + } + } +} + /// A tween's ease (as the XFL importer reads it): the classic slider, or the custom curves — /// one for everything, or one per property group. fn easing(frame: &archive::FrameRec, report: &mut Report) -> (Easing, Vec<(EaseGroup, Easing)>) { @@ -328,6 +539,24 @@ fn element(graph: &Graph, n: usize, ctx: &mut Ctx, out: &mut Vec>, out.push(Arc::new(e)); } } + Some(Node::Text(t)) => { + let id = ElementId(ctx.doc.alloc_id()); + if let Some(e) = t.to_element(id, ctx.fonts, ctx.faces, ctx.report) { + out.push(Arc::new(e)); + ctx.report.keep("texts"); + } + } + Some(Node::Bitmap(b)) => { + // As the XFL importer's bitmap instance: the image's rectangle, filled with it. + let found = ctx.bitmaps.get(&b.item).and_then(|&id| ctx.doc.bitmap(id).map(|bm| (id, bm.width as f32, bm.height as f32))); + let Some((bitmap, w, h)) = found else { + ctx.report.skip("instances of missing bitmaps"); + return; + }; + let shape = Shape { path: Arc::new(Path::rect(0.0, 0.0, w, h)), fill: Some(Paint::Bitmap { bitmap, repeat: false, matrix: anicraft_geom::Affine::IDENTITY }), stroke: None, fill_rule: FillRule::NonZero, merge: false, warp: None }; + out.push(Arc::new(Element { id: ElementId(ctx.doc.alloc_id()), name: String::new(), transform: b.matrix, color: ColorEffect::default(), kind: ElementKind::Shape(shape) })); + ctx.report.keep("bitmap instances"); + } Some(Node::Shape(s)) => { let group = !s.drawing_object && (!s.members.is_empty() || s.flag & 1 == 0); if !group { @@ -358,14 +587,14 @@ fn element(graph: &Graph, n: usize, ctx: &mut Ctx, out: &mut Vec>, Some(Node::Skipped(class)) => { let what = match class.as_str() { "CPicShape" => "shapes whose edge records didn't decode", - "CPicText" => "texts (decode pending)", - "CPicBitmap" => "bitmaps (decode pending)", + "CPicText" => "texts whose records didn't decode", + "CPicBitmap" => "bitmap instances whose records didn't decode", "CPicVideo" => "videos (decode pending)", _ => "objects of a kind not decoded (left out)", }; ctx.report.skip(what); } - Some(Node::Morph | Node::Hints | Node::Pending) | None => {} + Some(Node::Morph | Node::List(_) | Node::Hint(..) | Node::Pending) | None => {} Some(_) => ctx.report.skip("objects of a kind not decoded (left out)"), } } @@ -422,7 +651,15 @@ fn instance(inst: &archive::InstanceRec, ctx: &mut Ctx) -> Option { if inst.filters != 0 { ctx.report.skip("filters and blend modes on filtered instances (left out)"); } else if inst.extras_skipped { - ctx.report.skip("movie clip and button settings (scripts, component data; left out)"); + ctx.report.skip(match inst.class { + InstanceClass::MovieClip => "movie clip component settings (left out)", + _ => "button settings in a layout not decoded (left out)", + }); + } + // Older documents put handlers (`on (release) { … }`) on instances; only frame scripts + // have a place yet (as in the XFL importer). + if !inst.script.trim().is_empty() { + ctx.report.skip("scripts on instances (left out; frame scripts are kept)"); } let m = inst.matrix; // The stored point is the transformation point placed by the matrix: back into the @@ -621,7 +858,8 @@ pub fn library_items(contents: &[u8]) -> Vec { if let (Some(id), Some(kind)) = (id, kind) && (name.starts_with("S ") || name.starts_with("Symbol ")) { - out.push(LibraryItem { stream: name, label, id, kind }); + let parent = library::symbol_parent(contents, end + 5); + out.push(LibraryItem { stream: name, label, id, kind, parent }); } break; } diff --git a/crates/fla/src/lib.rs b/crates/fla/src/lib.rs index 7dc69b79..34e9ced9 100644 --- a/crates/fla/src/lib.rs +++ b/crates/fla/src/lib.rs @@ -14,14 +14,16 @@ //! is written to disk, and hostile or damaged input is refused with a one-sentence error — //! never a panic. [`archive`] reads an item stream's object graph (layers, keyframes, symbol //! instances, tweens), [`shape`] the shape records' styles and straight and curved edges, -//! [`text`] the `CPicText` records' static and dynamic text fields, and [`doc`] maps them into -//! the AniCraft model the way the XFL importer maps Animate's (ADR 0096). +//! [`text`] the `CPicText` records' static and dynamic text fields, [`library`] the folders, +//! bitmaps and sounds `Contents` lists, and [`doc`] maps them into the AniCraft model the way the +//! XFL importer maps Animate's (ADR 0096). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod archive; pub mod cfb; pub mod doc; +pub mod library; pub mod records; pub mod report; pub mod shape; diff --git a/crates/fla/src/library.rs b/crates/fla/src/library.rs new file mode 100644 index 00000000..1273ca70 --- /dev/null +++ b/crates/fla/src/library.rs @@ -0,0 +1,273 @@ +//! The library as `Contents` lists it beyond its symbols: folders, bitmaps and sounds, and the +//! document's script language (ADR 0096). +//! +//! Learned differentially from the corpus's legacy files and their Animate twins +//! (`DOMFolderItem`, `DOMBitmapItem`, `DOMSoundItem`, `PublishSettings.xml`); no Flash or +//! Animate code involved. Every library item carries the same identity block — u32 6, u32 1, +//! the parent folder's item id, u32 1, its own item id — where an item id is two u32 (a time +//! stamp and a counter, the twin's `itemID` `"%08x-%08x"`) and `0, 0` is the library's root: +//! +//! ```text +//! folder u32 4 · name (string) · identity · u32 0 · u32 7 · … +//! symbol 01 80 17 · stream name · label · u32 item id · u8 type · string · u32 1 · identity · … +//! media class tag (CMediaBits, CMediaSound) · 06 · stream name (u8 n, n UTF-16 units) · name · +//! u16 media id · source path · u32 import time · identity · u32 0 · u32 7 · u8 · +//! 3 strings · u8 · u32 2 · 2 strings · 8 bytes · u32 1 · u32 0 · u32 −1 · u8 · string · +//! u8 · u32 1 · then a bitmap's 03 … or a sound's 0a · u8 format · u8 · u32 sample count +//! ``` +//! +//! A folder's path is its parents' names joined with `/`. The media id is what bitmap +//! instances and frame sounds refer to; it is not the stream's number. Strings are MFC +//! `CArchive` strings ([`crate::text::cstring`]). Every read is bounded: what doesn't parse is +//! left out (and counted by the importer), never guessed at. + +use std::collections::HashMap; + +/// A library item's id: (time stamp, counter); `(0, 0)` is the library's root. +pub type ItemId = (u32, u32); + +/// The root's id. +pub const ROOT: ItemId = (0, 0); +/// Most folders and media items read. +const MAX_ITEMS: usize = 1 << 14; +/// Longest stream name (UTF-16 units). +const MAX_STREAM_NAME: usize = 64; + +/// A library folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Folder { + pub name: String, + pub parent: ItemId, + pub id: ItemId, +} + +/// A media item's kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MediaKind { + Bitmap, + Sound, +} + +/// A bitmap or sound library item. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MediaItem { + /// By its class (declared by name) or its own tail; `None` when neither says. + pub kind: Option, + /// The stream holding its data (`Media 4`, `M 10 1522496704`). + pub stream: String, + /// Its name in the library (the leaf: `logo CC88x31.png`, `blink1`). + pub name: String, + /// The id placements refer to it by. + pub id: u16, + pub parent: ItemId, + /// A sound's format byte and sample count (frames), when its tail decoded. + pub sound: Option<(u8, u32)>, +} + +/// Bounded little-endian reads. +struct Reader<'a> { + d: &'a [u8], + at: usize, +} + +impl<'a> Reader<'a> { + fn take(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.at.checked_add(n)?; + let s = self.d.get(self.at..end)?; + self.at = end; + Some(s) + } + fn u8(&mut self) -> Option { + self.take(1)?.first().copied() + } + fn u16(&mut self) -> Option { + Some(u16::from_le_bytes(self.take(2)?.try_into().ok()?)) + } + fn u32(&mut self) -> Option { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } + fn expect(&mut self, v: u32) -> Option<()> { + (self.u32()? == v).then_some(()) + } + fn string(&mut self) -> Option { + let (s, end) = crate::text::cstring(self.d, self.at).ok()?; + self.at = end; + Some(s) + } + /// The identity block: u32 6, u32 1, parent id, u32 1, own id. + fn identity(&mut self) -> Option<(ItemId, ItemId)> { + self.expect(6)?; + self.expect(1)?; + let parent = (self.u32()?, self.u32()?); + self.expect(1)?; + let id = (self.u32()?, self.u32()?); + Some((parent, id)) + } + /// A stream name: a bare u8 length, then UTF-16 units. + fn stream_name(&mut self) -> Option { + let n = usize::from(self.u8()?); + if n == 0 || n > MAX_STREAM_NAME { + return None; + } + let units: Vec = self.take(n * 2)?.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let s = String::from_utf16(&units).ok()?; + s.chars().all(|c| c.is_ascii_graphic() || c == ' ').then_some(s) + } +} + +/// The library's folders, in the order `Contents` lists them: each `u32 4`, its name, then the +/// identity block and the fixed `u32 0, u32 7` that starts every item's settings. +pub fn folders(contents: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut i = 0usize; + while i + 8 <= contents.len() && out.len() < MAX_ITEMS { + if contents.get(i..i + 7) == Some(&[0x04, 0x00, 0x00, 0x00, 0xFF, 0xFE, 0xFF][..]) { + let mut r = Reader { d: contents, at: i + 4 }; + let folder = (|| { + let name = r.string()?; + let (parent, id) = r.identity()?; + r.expect(0)?; + r.expect(7)?; + let name = name.trim().to_string(); + (!name.is_empty() && id != ROOT && !name.contains('/')).then_some(Folder { name, parent, id }) + })(); + if let Some(f) = folder { + out.push(f); + i = r.at; + continue; + } + } + i += 1; + } + out +} + +/// Each folder's path (its parents' names and its own, joined with `/`), by id. A folder whose +/// parent chain is broken or loops sits at the root. +pub fn folder_paths(folders: &[Folder]) -> HashMap { + let by_id: HashMap = folders.iter().map(|f| (f.id, f)).collect(); + let mut out = HashMap::new(); + for f in folders { + let mut parts = vec![f.name.as_str()]; + let mut at = f.parent; + let mut seen = vec![f.id]; + while at != ROOT && parts.len() < anicraft_doc::library::MAX_FOLDER_DEPTH { + let Some(p) = by_id.get(&at).filter(|_| !seen.contains(&at)) else { break }; + seen.push(at); + parts.push(p.name.as_str()); + at = p.parent; + } + parts.reverse(); + out.insert(f.id, parts.join("/")); + } + out +} + +/// A library symbol's parent folder: its entry continues, after the label, item id and type +/// byte at `after` (the type byte's offset + 1), with a string, `u32 1` and the identity block. +pub fn symbol_parent(contents: &[u8], after: usize) -> Option { + let mut r = Reader { d: contents, at: after }; + r.string()?; + r.expect(1)?; + r.identity().map(|(parent, _)| parent) +} + +/// The bitmap and sound items, each found at its class tag (a `CMediaBits` / `CMediaSound` +/// declaration or a class reference) followed by version 6 and the name of a stream the file +/// has (`has_stream`). +pub fn media_items(contents: &[u8], has_stream: impl Fn(&str) -> bool) -> Vec { + const BITS: &[u8] = b"CMediaBits"; + const SOUND: &[u8] = b"CMediaSound"; + let mut out = Vec::new(); + let mut i = 2usize; + while i < contents.len() && out.len() < MAX_ITEMS { + if contents.get(i) != Some(&0x06) { + i += 1; + continue; + } + let before = |n: usize| i.checked_sub(n).and_then(|s| contents.get(s..i)); + let declared = if before(SOUND.len()) == Some(SOUND) { + Some(MediaKind::Sound) + } else if before(BITS.len()) == Some(BITS) { + Some(MediaKind::Bitmap) + } else { + None + }; + let referenced = contents.get(i - 1) == Some(&0x80); + if declared.is_none() && !referenced { + i += 1; + continue; + } + match media_at(contents, i + 1, declared) { + Some((item, end)) if has_stream(&item.stream) => { + out.push(item); + i = end.max(i + 1); + } + _ => i += 1, + } + } + out +} + +/// One media record from just after its version byte. +fn media_at(contents: &[u8], at: usize, declared: Option) -> Option<(MediaItem, usize)> { + let mut r = Reader { d: contents, at }; + let stream = r.stream_name()?; + let name = r.string()?; + let id = r.u16()?; + r.string()?; // the source file's path + r.u32()?; // its import time + let (parent, _) = r.identity()?; + let mut item = MediaItem { kind: declared, stream, name: name.chars().take(256).collect(), id, parent, sound: None }; + let identity_end = r.at; + // The common settings, then the class's own. + let tail = (|| { + r.expect(0)?; + r.expect(7)?; + r.u8()?; + for _ in 0..3 { + r.string()?; + } + r.u8()?; + r.expect(2)?; + for _ in 0..2 { + r.string()?; + } + r.take(8)?; + r.expect(1)?; + r.expect(0)?; + r.expect(u32::MAX)?; + r.u8()?; + r.string()?; + r.u8()?; + r.expect(1)?; + match r.u8()? { + 0x03 => Some((MediaKind::Bitmap, None)), + 0x0A => { + let format = r.u8()?; + r.u8()?; + Some((MediaKind::Sound, Some((format, r.u32()?)))) + } + _ => None, + } + })(); + match tail { + Some((kind, sound)) if declared.is_none_or(|d| d == kind) => { + item.kind = Some(kind); + item.sound = sound; + Some((item, r.at)) + } + _ => Some((item, identity_end)), + } +} + +/// The document's `ActionScriptVersion` publish setting (`"2"`), from the `Vector::` key and +/// value strings `Contents` holds. +pub fn script_version(contents: &[u8]) -> Option { + let key: Vec = "Vector::ActionScriptVersion".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut needle = vec![0xFF, 0xFE, 0xFF, 27]; + needle.extend_from_slice(&key); + let at = contents.windows(needle.len()).position(|w| w == needle.as_slice())?; + let (value, _) = crate::text::cstring(contents, at.checked_add(needle.len())?).ok()?; + Some(value.trim().chars().take(16).collect()) +} diff --git a/crates/fla/src/tests.rs b/crates/fla/src/tests.rs index f2bfd1ac..7c80a176 100644 --- a/crates/fla/src/tests.rs +++ b/crates/fla/src/tests.rs @@ -720,6 +720,15 @@ struct FrameSpec { /// Custom ease anchors for the `all` group: (in, anchor, out) points. ease_all: Vec<[f64; 6]>, script: &'static str, + /// The sound's media id (0: none), its envelope (mark44, left, right), loops, sync, in + /// and out points. + sound: u16, + envelope: Vec<(u32, u16, u16)>, + loops: u16, + sync: u8, + in_out: (u32, u32), + /// Shape hints: (start, end) in twips. + hints: Vec<((i32, i32), (i32, i32))>, } /// A symbol instance as written. @@ -848,12 +857,18 @@ impl Ar { self.u16(spec.duration); self.out.extend_from_slice(&[spec.tween, 0x06]); self.out.extend_from_slice(&spec.ease.to_le_bytes()); - self.u16(0); // no sound - self.u16(0); // no envelope - self.u16(1); // loops - self.out.push(0); // sync - self.i32(0); - self.i32(0x3FFF_FFFF); + self.u16(spec.sound); + self.u16(spec.envelope.len() as u16); + for &(mark, left, right) in &spec.envelope { + self.i32(mark as i32); + self.u16(left); + self.u16(right); + } + self.u16(spec.loops.max(1)); + self.out.push(spec.sync); + let (in_point, out_point) = if spec.sound == 0 { (0, 0x3FFF_FFFF) } else { spec.in_out }; + self.i32(in_point as i32); + self.i32(out_point as i32); self.u16(0xFFFF); self.string(spec.label); self.out.extend_from_slice(&[4, 0, 0, 0, 1, 0, 0, 0, 0x33, 0x0D, 0, 0, 0, 0, 0, 0]); @@ -862,7 +877,19 @@ impl Ar { self.i32(spec.comment as i32); self.u16(0); // no shape-tween cache self.out.extend_from_slice(&[0; 4]); - self.u16(0); // no hints + if spec.hints.is_empty() { + self.u16(0); // no hints + } else { + // A `CObList` (schema 0) of `CMorphHintItem`s. + self.tag("CObList"); + self.u16(spec.hints.len() as u16); + for (n, &((sx, sy), (ex, ey))) in spec.hints.iter().enumerate() { + self.tag("CMorphHintItem"); + for v in [sx, sy, ex, ey, n as i32] { + self.i32(v); + } + } + } self.string(""); for v in [1, 0, 0, 1, (!spec.ease_all.is_empty()) as i32] { self.i32(v); @@ -1079,8 +1106,11 @@ fn a_synthetic_timeline_decodes_its_layers_keyframes_tweens_and_instances() { assert_eq!(spans, [(0, 2), (2, 3)]); // The report: what was left out, by kind. assert_eq!(report.skipped.get("frame comments"), Some(&1), "{:?}", report.skipped); - assert_eq!(report.skipped.get("frame scripts (decode pending)"), Some(&1), "{:?}", report.skipped); - assert_eq!(report.skipped.get("movie clip and button settings (scripts, component data; left out)"), Some(&1), "{:?}", report.skipped); + // The guide's frame script is kept as written (no publish setting: ActionScript 3.0). + let Some(anicraft_doc::FrameScript::Source(script)) = &tl.layers[0].keyframes[0].script else { panic!("a frame script: {:?}", tl.layers[0].keyframes[0].script) }; + assert_eq!((script.text.as_str(), script.language), ("stop();", anicraft_doc::Language::ActionScript3)); + assert!(report.kept.contains_key("frame scripts in ActionScript 3.0") || report.runs.contains_key("frame scripts in ActionScript 3.0"), "{:?}", report.kept); + assert_eq!(report.skipped.get("movie clip component settings (left out)"), Some(&1), "{:?}", report.skipped); assert_eq!(report.kept.get("symbol instances"), Some(&2)); } @@ -1111,7 +1141,7 @@ fn an_object_of_a_kind_not_decoded_is_skipped_and_its_siblings_still_place() { assert_eq!((k.start, k.duration), (0, 5)); assert_eq!(k.elements.len(), 1); assert!(matches!(k.elements[0].kind, ElementKind::Symbol { .. })); - assert_eq!(report.skipped.get("texts (decode pending)"), Some(&2), "{:?}", report.skipped); + assert_eq!(report.skipped.get("texts whose records didn't decode"), Some(&2), "{:?}", report.skipped); } #[test] @@ -1146,3 +1176,311 @@ fn the_object_graph_refuses_what_it_cannot_number() { w.layer("x", 0, None, |_| {}); assert!(parse(&w.out).is_err()); } + +// Texts, media, buttons, scripts, hints and folders on a synthetic document, every byte +// written here from the grammar in `crate::archive` and `crate::library` (no corpus bytes). + +/// An MFC Unicode string (`FF FE FF` and a u8 length). +fn cstr(s: &str) -> Vec { + let mut w = Ar::new(); + w.out.clear(); + w.string(s); + w.out +} + +/// A zlib stream of stored (uncompressed) deflate blocks: the header, blocks of at most +/// 65535 bytes, and the Adler-32 of the data. +fn zlib_stored(data: &[u8]) -> Vec { + let mut out = vec![0x78, 0x01]; + let chunks: Vec<&[u8]> = if data.is_empty() { vec![&[][..]] } else { data.chunks(65535).collect() }; + for (i, c) in chunks.iter().enumerate() { + out.push(u8::from(i + 1 == chunks.len())); + out.extend((c.len() as u16).to_le_bytes()); + out.extend((!(c.len() as u16)).to_le_bytes()); + out.extend_from_slice(c); + } + let (mut a, mut b) = (1u32, 0u32); + for &x in data { + a = (a + u32::from(x)) % 65521; + b = (b + a) % 65521; + } + out.extend(((b << 16) | a).to_be_bytes()); + out +} + +/// Animate's lossless bitmap payload: header, then the zlib stream in chunks of at most 2048 +/// bytes, then a zero length. `argb` is premultiplied A, R, G, B rows. +fn bitmap_payload(w: u16, h: u16, argb: &[u8]) -> Vec { + let mut out = vec![0x03, 0x05]; + out.extend((w * 4).to_le_bytes()); + out.extend(w.to_le_bytes()); + out.extend(h.to_le_bytes()); + for v in [0i32, i32::from(w) * 20, 0, i32::from(h) * 20] { + out.extend(v.to_le_bytes()); + } + out.extend([1, 1]); + for c in zlib_stored(argb).chunks(2048) { + out.extend((c.len() as u16).to_le_bytes()); + out.extend_from_slice(c); + } + out.extend([0, 0]); + out +} + +/// An item's identity block: u32 6, u32 1, its parent folder's id, u32 1, its own id. +fn identity(parent: (u32, u32), id: (u32, u32)) -> Vec { + let mut out = Vec::new(); + for v in [6, 1, parent.0, parent.1, 1, id.0, id.1] { + out.extend(v.to_le_bytes()); + } + out +} + +/// Every item's common settings after its identity block. +fn common_settings() -> Vec { + let mut out = Vec::new(); + out.extend(0u32.to_le_bytes()); + out.extend(7u32.to_le_bytes()); + out.push(0); + for _ in 0..3 { + out.extend(cstr("")); + } + out.push(0); + out.extend(2u32.to_le_bytes()); + for _ in 0..2 { + out.extend(cstr("")); + } + out.extend([0; 8]); + out.extend(1u32.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + out.extend(u32::MAX.to_le_bytes()); + out.push(0); + out.extend(cstr("")); + out.push(0); + out.extend(1u32.to_le_bytes()); + out +} + +const ART: (u32, u32) = (0x5A00_0001, 0x11); +const SOUNDS: (u32, u32) = (0x5A00_0001, 0x12); + +/// `Contents` with the scene, the symbol (in "Art"), two folders ("Art" and "Art/Sounds"), a +/// bitmap (id 7, in "Art"), a sound (id 8, in "Art/Sounds") and the ActionScript 2 setting. +fn media_contents() -> Vec { + let mut c = synthetic_contents(); + // `synthetic_contents` ends its symbol entry with 8 zero bytes: write the entry's own + // settings there instead (a string, u32 1, the identity block). + c.truncate(c.len() - 8); + c.extend(cstr("")); + c.extend(1u32.to_le_bytes()); + c.extend(identity(ART, (0x5A00_0002, 0x31))); + c.extend(common_settings()); + // The bitmap. + c.extend([0xFF, 0xFF, 0x01, 0x00, 0x0A, 0x00]); + c.extend(b"CMediaBits"); + c.push(0x06); + c.push(7); + c.extend("Media 1".encode_utf16().flat_map(u16::to_le_bytes)); + c.extend(cstr("badge.png")); + c.extend(7u16.to_le_bytes()); + c.extend(cstr("..\\art\\badge.png")); + c.extend(1_300_000_000u32.to_le_bytes()); + c.extend(identity(ART, (0x5A00_0003, 0x41))); + c.extend(common_settings()); + c.extend([0x03, 0x01, 0x32, 0x01, 0, 0, 0, 0]); + // The sound: 44.1 kHz 16-bit mono, 4 frames. + c.extend([0xFF, 0xFF, 0x01, 0x00, 0x0B, 0x00]); + c.extend(b"CMediaSound"); + c.push(0x06); + c.push(5); + c.extend("M 2 1".encode_utf16().flat_map(u16::to_le_bytes)); + c.extend(cstr("beep")); + c.extend(8u16.to_le_bytes()); + c.extend(cstr("..\\beep.wav")); + c.extend(1_300_000_001u32.to_le_bytes()); + c.extend(identity(SOUNDS, (0x5A00_0004, 0x51))); + c.extend(common_settings()); + c.extend([0x0A, 0x0E, 0x00]); + c.extend(4u32.to_le_bytes()); + c.extend(u32::MAX.to_le_bytes()); + c.extend([0; 12]); + // The folders: a count, then each. + c.extend(1u32.to_le_bytes()); + c.extend(2u32.to_le_bytes()); + for (name, parent, id) in [("Art", (0, 0), ART), ("Sounds", ART, SOUNDS)] { + c.extend(4u32.to_le_bytes()); + c.extend(cstr(name)); + c.extend(identity(parent, id)); + c.extend(common_settings()); + } + // The publish settings. + c.extend(cstr("Vector::ActionScriptVersion")); + c.extend(cstr("2")); + c +} + +/// A page with a dynamic text, a bitmap instance and a named button with a handler on one +/// keyframe; a sound frame; and a shape tween with two hints. +fn media_page() -> Vec { + use crate::text_tests::{record, units, Head, Style}; + let mut w = Ar::new(); + w.page(|w| { + w.layer("tween", 0, None, |w| { + let spec = FrameSpec { duration: 4, tween: 2, hints: vec![((200, 400), (-100, 60)), ((0, 0), (20, 40))], ..FrameSpec::default() }; + w.frame(&[], &spec, |_| {}); + w.frame(&[], &FrameSpec { duration: 1, ..FrameSpec::default() }, |_| {}); + }); + w.layer("sound", 0, None, |w| { + let spec = FrameSpec { duration: 5, sound: 8, envelope: vec![(44_100, 32768, 16384)], loops: 3, sync: 3, in_out: (0, 0x3FFF_FFFF), script: "gotoAndPlay(1);\r\n", ..FrameSpec::default() }; + w.frame(&[], &spec, |_| {}); + }); + w.layer("objects", 0, None, |w| { + w.frame(&[], &FrameSpec { duration: 5, ..FrameSpec::default() }, |w| { + // A dynamic text field (kept with or without fonts). + w.tag("CPicText"); + let head = Head { field: 0x0003, matrix: [65536, 0, 0, 65536, 400, 600], bounds: [0, 2000, 0, 400], ..Head::default() }; + w.out.extend(record(&head, &[(units("Score"), Style::default())])); + // A bitmap, scaled 2× and moved (10, 20) px. + w.object("CPicBitmap", 0, None, 0, 0x02, |_| {}); + for v in [131072, 0, 0, 131072, 200, 400] { + w.i32(v); + } + w.u16(7); + w.out.push(0); + // A button: its handler, track as menu off, its name, then u32 0. + w.instance(&InstSpec { class: "CPicButton", ..InstSpec::default() }); + w.out.push(0x0B); + w.out.extend_from_slice(&[4, 0, 0, 0, 1, 0, 0, 0, 0x10, 0x20, 0, 0, 0, 0, 0, 0]); + w.string("on (release) {\r\n\tgetURL(\"https://example.org\", \"_self\");\r\n}"); + w.out.push(0); + w.string("CC"); + w.i32(0); + }); + }); + }); + w.out +} + +fn media_document() -> Vec { + // A 2 × 1 bitmap: opaque red, then half-transparent white (premultiplied). + let bitmap = bitmap_payload(2, 1, &[255, 255, 0, 0, 128, 128, 128, 128]); + let pcm: Vec = [0i16, 1000, -1000, 32767].iter().flat_map(|v| v.to_le_bytes()).collect(); + write(&[("Contents", media_contents()), ("P 1 1", media_page()), ("Symbol 9", one_frame_stream(&rectangle_body())), ("Media 1", bitmap), ("M 2 1", pcm)]) +} + +#[test] +fn texts_bitmaps_buttons_sounds_scripts_and_hints_come_in_on_their_keyframes() { + use anicraft_doc::{ElementKind, FrameScript, Language, LibraryEntry, LibraryItem, Paint, SoundEffect, SoundSync}; + let (doc, report) = super::doc::import(&media_document()).expect("the synthetic document opens"); + let tl = scene(&doc); + let names: Vec<&str> = tl.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["objects", "sound", "tween"]); + // The library: the bitmap's pixels (straight alpha), the sound as a WAV, both in folders. + assert_eq!(doc.bitmaps.len(), 1); + let b = &doc.bitmaps[0]; + assert_eq!((b.name.as_str(), b.width, b.height), ("badge.png", 2, 1)); + let px = b.pixels().expect("the bitmap decodes"); + assert_eq!(&px.rgba[..8], &[255, 0, 0, 255, 255, 255, 255, 128]); + assert_eq!(doc.entry_path(LibraryEntry::Item(LibraryItem::Bitmap(b.id))), "Art/badge.png"); + assert_eq!(doc.sounds.len(), 1); + let s = &doc.sounds[0]; + assert_eq!((s.name.as_str(), s.rate, s.channels, s.frames), ("beep", 44_100, 1, 4)); + assert_eq!(doc.entry_path(LibraryEntry::Item(LibraryItem::Sound(s.id))), "Art/Sounds/beep"); + let sym = &doc.library[0]; + assert_eq!(doc.entry_path(LibraryEntry::Item(LibraryItem::Symbol(sym.id))), "Art/UFO mask"); + // The objects: the dynamic text, the bitmap's rectangle, the named button. + let k = &tl.layers[0].keyframes[0]; + assert_eq!(k.elements.len(), 3, "{:?}", k.elements.iter().map(|e| &e.kind).collect::>()); + let ElementKind::Text(block) = &k.elements[0].kind else { panic!("a text: {:?}", k.elements[0].kind) }; + assert_eq!(block.text, "Score"); + assert!(block.field.is_some(), "a dynamic field"); + // Its box sits at the record's left and top, through its matrix (20, 30) px. + assert_eq!(k.elements[0].transform.m, [1.0, 0.0, 0.0, 1.0, 20.0, 30.0]); + let ElementKind::Shape(rect) = &k.elements[1].kind else { panic!("the bitmap's rectangle") }; + assert!(matches!(rect.fill, Some(Paint::Bitmap { bitmap, repeat: false, .. }) if bitmap == b.id)); + assert_eq!(k.elements[1].transform.m, [2.0, 0.0, 0.0, 2.0, 10.0, 20.0]); + let bounds = rect.path.bounds(); + assert_eq!((bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y), (0.0, 0.0, 2.0, 1.0)); + assert!(matches!(k.elements[2].kind, ElementKind::Symbol { .. })); + assert_eq!(k.elements[2].name, "CC", "a button's name comes from its own settings"); + assert_eq!(report.skipped.get("scripts on instances (left out; frame scripts are kept)"), Some(&1), "{:?}", report.skipped); + assert!(!report.skipped.keys().any(|k| k.starts_with("button settings")), "{:?}", report.skipped); + // The sound frame: its sound, sync, repeats and envelope; its script, kept as written. + let k = &tl.layers[1].keyframes[0]; + let fs = k.sound.as_ref().expect("a frame sound"); + assert_eq!((fs.sound, fs.sync, fs.repeat, fs.looping), (s.id, SoundSync::Stream, 3, false)); + let SoundEffect::Custom(points) = &fs.effect else { panic!("an envelope: {:?}", fs.effect) }; + assert_eq!(points.len(), 1); + assert!((points[0].at - 1.0).abs() < 1e-9 && points[0].left == 1.0 && points[0].right == 0.5, "{points:?}"); + let Some(FrameScript::Source(script)) = &k.script else { panic!("a frame script: {:?}", k.script) }; + assert_eq!((script.text.as_str(), script.language), ("gotoAndPlay(1);\r\n", Language::ActionScript1or2)); + assert_eq!(report.kept.get("frame scripts in ActionScript 1.0 & 2.0"), Some(&1), "{:?}", report.kept); + assert!(!report.skipped.contains_key("sound in and out points (played whole)")); + // The shape tween's hints, start and end, in pixels, `a` first. + let hints = &tl.layers[2].keyframes[0].hints; + assert_eq!(hints.len(), 2); + assert_eq!((hints[0].start, hints[0].end), (anicraft_geom::Vec2::new(10.0, 20.0), anicraft_geom::Vec2::new(-5.0, 3.0))); + assert_eq!((hints[1].start, hints[1].end), (anicraft_geom::Vec2::new(0.0, 0.0), anicraft_geom::Vec2::new(1.0, 2.0))); + // Everything decoded: the report keeps them. + for kind in ["bitmaps", "sounds", "texts", "bitmap instances", "library folders"] { + assert!(report.kept.contains_key(kind), "{kind}: {:?}", report.kept); + } + let left_out: Vec<&String> = report.skipped.keys().filter(|k| k.as_str() != "scripts on instances (left out; frame scripts are kept)").collect(); + assert!(left_out.is_empty(), "{left_out:?}"); +} + +#[test] +fn media_that_does_not_decode_is_reported_by_name_and_its_uses_are_counted() { + // The bitmap's stream holds damaged pixels; the sound's is not its sample count long and + // no sound file either. + let mut bitmap = bitmap_payload(2, 1, &[255, 255, 0, 0, 128, 128, 128, 128]); + let n = bitmap.len(); + bitmap[n - 4] ^= 0xFF; + let bytes = write(&[("Contents", media_contents()), ("P 1 1", media_page()), ("Symbol 9", one_frame_stream(&rectangle_body())), ("Media 1", bitmap), ("M 2 1", vec![1, 2, 3])]); + let (doc, report) = super::doc::import(&bytes).expect("opens"); + assert!(doc.bitmaps.is_empty() && doc.sounds.is_empty()); + let named = |k: &str| report.names.get(k).cloned().unwrap_or_default(); + assert_eq!(named("bitmaps in Animate's own format AniCraft can't decode").len(), 1, "{:?}", report.names); + assert!(named("bitmaps in Animate's own format AniCraft can't decode")[0].starts_with("badge.png: ")); + assert!(named("sounds in formats AniCraft can't decode")[0].starts_with("beep: "), "{:?}", report.names); + assert_eq!(report.skipped.get("instances of missing bitmaps"), Some(&1)); + assert_eq!(report.skipped.get("frame sounds whose sound isn't in the file"), Some(&1)); +} + +#[test] +fn a_document_with_media_cut_short_or_damaged_anywhere_never_panics() { + let page = media_page(); + let contents = media_contents(); + let bitmap = bitmap_payload(2, 1, &[255, 255, 0, 0, 128, 128, 128, 128]); + for cut in 0..page.len() { + let bytes = write(&[("Contents", media_contents()), ("P 1 1", page[..cut].to_vec()), ("Media 1", bitmap.clone())]); + assert!(super::doc::import(&bytes).is_ok(), "cut at {cut}"); + } + for at in 1..page.len() { + let mut bad = page.clone(); + bad[at] ^= 0xA5; + assert!(super::doc::import(&write(&[("Contents", media_contents()), ("P 1 1", bad), ("Media 1", bitmap.clone())])).is_ok(), "flip at {at}"); + } + // `Contents` damaged anywhere: the document opens or is refused, never a panic. + for at in 0..contents.len() { + let mut bad = contents.clone(); + bad[at] ^= 0x5A; + let _ = super::doc::import(&write(&[("Contents", bad), ("P 1 1", page.clone()), ("Media 1", bitmap.clone()), ("M 2 1", vec![0; 8])])); + let _ = super::library::media_items(&contents[..at], |_| true); + let _ = super::library::folders(&contents[..at]); + } +} + +#[test] +fn library_folders_nest_by_their_parents_and_a_loop_stays_at_the_root() { + use super::library::{folder_paths, folders, Folder}; + let found = folders(&media_contents()); + assert_eq!(found, vec![Folder { name: "Art".into(), parent: (0, 0), id: ART }, Folder { name: "Sounds".into(), parent: ART, id: SOUNDS }]); + let paths = folder_paths(&found); + assert_eq!(paths.get(&SOUNDS).map(String::as_str), Some("Art/Sounds")); + // Two folders each other's parent: neither loops forever. + let looped = [Folder { name: "a".into(), parent: (2, 2), id: (1, 1) }, Folder { name: "b".into(), parent: (1, 1), id: (2, 2) }]; + let paths = folder_paths(&looped); + assert_eq!(paths.get(&(1, 1)).map(String::as_str), Some("b/a")); + assert_eq!(super::library::script_version(&media_contents()).as_deref(), Some("2")); +} diff --git a/crates/fla/src/text_tests.rs b/crates/fla/src/text_tests.rs index bea498e0..07292a67 100644 --- a/crates/fla/src/text_tests.rs +++ b/crates/fla/src/text_tests.rs @@ -8,21 +8,21 @@ use anicraft_text::Fonts; /// One run's attributes, as the encoder writes them. #[derive(Clone)] -struct Style { - size: u16, - face: &'static str, - rgba: [u8; 4], - bold: bool, - italic: bool, - kern: bool, - position: u8, - align: u8, - line: i16, - indent: i16, - letter: i16, - target: &'static str, - render: u8, - thickness: f32, +pub(crate) struct Style { + pub(crate) size: u16, + pub(crate) face: &'static str, + pub(crate) rgba: [u8; 4], + pub(crate) bold: bool, + pub(crate) italic: bool, + pub(crate) kern: bool, + pub(crate) position: u8, + pub(crate) align: u8, + pub(crate) line: i16, + pub(crate) indent: i16, + pub(crate) letter: i16, + pub(crate) target: &'static str, + pub(crate) render: u8, + pub(crate) thickness: f32, } impl Default for Style { @@ -75,14 +75,14 @@ fn block(s: &Style) -> Vec { } /// A record's head fields. -struct Head { - flags: u8, - matrix: [i32; 6], - bounds: [i32; 4], - auto: bool, - field: u16, - selectable: bool, - name: String, +pub(crate) struct Head { + pub(crate) flags: u8, + pub(crate) matrix: [i32; 6], + pub(crate) bounds: [i32; 4], + pub(crate) auto: bool, + pub(crate) field: u16, + pub(crate) selectable: bool, + pub(crate) name: String, } impl Default for Head { @@ -92,7 +92,7 @@ impl Default for Head { } /// A whole record: head, runs (units and style, stored as given), trailer. -fn record(h: &Head, runs: &[(Vec, Style)]) -> Vec { +pub(crate) fn record(h: &Head, runs: &[(Vec, Style)]) -> Vec { let mut out = vec![0x04, h.flags, 0, 0]; out.extend(0x8000_0000u32.to_le_bytes()); out.extend(0x8000_0000u32.to_le_bytes()); @@ -122,7 +122,7 @@ fn record(h: &Head, runs: &[(Vec, Style)]) -> Vec { out } -fn units(s: &str) -> Vec { +pub(crate) fn units(s: &str) -> Vec { s.encode_utf16().collect() } diff --git a/crates/fla/tests/corpus.rs b/crates/fla/tests/corpus.rs index 1c0fe0ca..caedb955 100644 --- a/crates/fla/tests/corpus.rs +++ b/crates/fla/tests/corpus.rs @@ -588,3 +588,424 @@ fn the_corpus_stage_matches_the_twins() { } assert!(checked >= 6); } + +// --------------------------------------------------------------------------------------------- +// Texts, bitmaps, sounds, buttons and the library's folders, keyframe by keyframe. + +/// Calls `f` for every keyframe the legacy import and its twin hold alike (same timeline, +/// layer and span: the timeline differential above checks that they all do), with a tag for +/// messages, the document, the legacy keyframe and the twin's `DOMFrame`. +fn for_each_keyframe(dir: &std::path::Path, mut f: impl FnMut(&str, &anicraft_doc::Document, &anicraft_doc::Keyframe, &craft_xml::El)) -> usize { + let mut files = 0; + for (legacy, twin) in TWINS { + let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin)); + if !legacy_path.exists() || !twin_path.exists() { + continue; + } + files += 1; + let data = std::fs::read(&legacy_path).expect("legacy reads"); + let (doc, _) = anicraft_fla::import(&data).unwrap_or_else(|e| panic!("{legacy}: {e}")); + let mut pairs: Vec<(String, &anicraft_doc::Timeline, Vec)> = Vec::new(); + let dom = twin_member(&twin_path, "DOMDocument.xml").expect("DOMDocument.xml"); + for (i, scene) in doc.scenes.iter().enumerate() { + pairs.push((format!("{legacy}:{}#{i}", scene.name), &scene.timeline, dom.clone())); + } + let mut by_stem: std::collections::HashMap> = std::collections::HashMap::new(); + for m in twin_members(&twin_path).into_iter().filter(|m| m.starts_with("LIBRARY/") && m.ends_with(".xml")) { + let stem = m.rsplit('/').next().unwrap_or(&m).trim_end_matches(".xml").to_string(); + by_stem.entry(stem).or_default().push(m); + } + for symbol in &doc.library { + let Some([member]) = by_stem.get(&symbol.name).map(Vec::as_slice) else { continue }; + let Some(xml) = twin_member(&twin_path, member) else { continue }; + pairs.push((format!("{legacy}:{}", symbol.name), &symbol.timeline, xml)); + } + for (tag, tl, xml) in pairs { + let Ok(x) = craft_xfl::document::Document::parse(&xml) else { continue }; + // A scene is its DOMTimeline by position; a symbol has one. + let scene_index = tag.rsplit_once('#').and_then(|(_, i)| i.parse::().ok()); + let mut timelines = x.root().descendants().filter(|e| local(&e.name) == "DOMTimeline"); + let Some(twin_tl) = (match scene_index { + Some(i) => timelines.nth(i), + None => timelines.next(), + }) else { + continue; + }; + let twin_layers: Vec<&craft_xml::El> = kids(twin_tl, "layers").flat_map(|l| kids(l, "DOMLayer")).collect(); + if twin_layers.len() != tl.layers.len() { + continue; + } + for (layer, tw) in tl.layers.iter().zip(twin_layers) { + if tw.attr("layerType") == Some("folder") || tw.attr("name").unwrap_or("") != layer.name { + continue; + } + let frames: Vec<&craft_xml::El> = kids(tw, "frames").flat_map(|f| kids(f, "DOMFrame")).collect(); + if frames.len() != layer.keyframes.len() { + continue; + } + for (k, fr) in layer.keyframes.iter().zip(frames) { + let start: u32 = fr.attr("index").and_then(|v| v.parse().ok()).unwrap_or(0); + if start == k.start { + f(&format!("{tag} / {} @{}", layer.name, k.start), &doc, k, fr); + } + } + } + } + } + files +} + +/// The legacy elements of a keyframe, groups opened, each with its transform on the frame. +fn flat_elements(els: &[std::sync::Arc], parent: anicraft_geom::Affine, out: &mut Vec<(anicraft_geom::Affine, std::sync::Arc)>) { + for e in els { + let m = parent.mul(&e.transform); + if let anicraft_doc::ElementKind::Group { members } = &e.kind { + for l in &members.layers { + for k in &l.keyframes { + flat_elements(&k.elements, m, out); + } + } + } else { + out.push((m, e.clone())); + } + } +} + +/// A twin frame's elements, groups opened (Animate writes a group's members in its parent's +/// space). +fn twin_elements<'a>(el: &'a craft_xml::El, out: &mut Vec<&'a craft_xml::El>) { + for e in el.elements() { + match local(&e.name) { + "DOMGroup" => { + for m in kids(e, "members") { + twin_elements(m, out); + } + } + _ => out.push(e), + } + } +} + +fn twin_frame_elements(fr: &craft_xml::El) -> Vec<&craft_xml::El> { + let mut out = Vec::new(); + for els in kids(fr, "elements") { + twin_elements(els, &mut out); + } + out +} + +fn twin_matrix(e: &craft_xml::El) -> anicraft_geom::Affine { + let m = kids(e, "matrix").flat_map(|m| kids(m, "Matrix")).next(); + let g = |k: &str, d: f32| m.and_then(|m| m.attr(k)).and_then(|v| v.parse::().ok()).unwrap_or(d); + anicraft_geom::Affine { m: [g("a", 1.0), g("b", 0.0), g("c", 0.0), g("d", 1.0), g("tx", 0.0), g("ty", 0.0)] } +} + +fn same_affine(a: &anicraft_geom::Affine, b: &anicraft_geom::Affine) -> bool { + (0..4).all(|i| (a.m[i] - b.m[i]).abs() <= 0.01) && (4..6).all(|i| (a.m[i] - b.m[i]).abs() <= 0.05) +} + +/// Line breaks as one character, the ends trimmed. +fn norm_text(s: &str) -> String { + s.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n").trim().to_string() +} + +#[test] +fn the_corpus_texts_sit_on_the_twins_keyframes() { + let Some(dir) = corpus() else { return }; + let (mut twin_total, mut matched, mut legacy_total) = (0usize, 0usize, 0usize); + let mut mismatches = Vec::new(); + for_each_keyframe(&dir, |tag, _doc, k, fr| { + let mut flat = Vec::new(); + flat_elements(&k.elements, anicraft_geom::Affine::IDENTITY, &mut flat); + // Each text as (dynamic, its text, where its box's top-left (inside the gutter, for + // static text) lands on the frame). + let mut legacy: Vec<(bool, String, anicraft_geom::Vec2)> = flat.iter().filter_map(|(m, e)| match &e.kind { + anicraft_doc::ElementKind::Text(b) => Some((b.field.is_some(), norm_text(&b.text), m.apply(anicraft_geom::Vec2::new(0.0, 0.0)))), + _ => None, + }).collect(); + legacy_total += legacy.len(); + for e in twin_frame_elements(fr) { + let dynamic = match local(&e.name) { + "DOMStaticText" => false, + "DOMDynamicText" | "DOMInputText" => true, + _ => continue, + }; + let text: String = kids(e, "textRuns").flat_map(|r| kids(r, "DOMTextRun")).filter_map(|r| r.child_text("characters").map(|c| c.into_owned())).collect(); + let text = norm_text(&text); + // An empty static text draws nothing: AniCraft leaves it out, as the XFL importer. + if !dynamic && text.is_empty() { + continue; + } + twin_total += 1; + let num = |k: &str| e.attr(k).and_then(|v| v.parse::().ok()).unwrap_or(0.0); + let gutter = if dynamic { 0.0 } else { anicraft_fla::text::GUTTER }; + let at = twin_matrix(e).apply(anicraft_geom::Vec2::new(num("left") + gutter, num("top") + gutter)); + let found = legacy.iter().position(|(d, t, p)| *d == dynamic && *t == text && (p.x - at.x).abs() <= 0.06 && (p.y - at.y).abs() <= 0.06); + match found { + Some(i) => { + legacy.swap_remove(i); + matched += 1; + } + None => mismatches.push(format!("{tag}: twin {} text {:?} at {at:?} not among {:?}", if dynamic { "dynamic" } else { "static" }, text.chars().take(40).collect::(), legacy.iter().map(|(d, t, p)| (*d, t.chars().take(20).collect::(), *p)).collect::>())), + } + } + for (d, t, p) in legacy { + mismatches.push(format!("{tag}: legacy {} text {:?} at {p:?} has no twin", if d { "dynamic" } else { "static" }, t.chars().take(40).collect::())); + } + }); + eprintln!("texts on keyframes: {matched}/{twin_total} twin texts matched ({legacy_total} legacy)"); + for m in mismatches.iter().take(30) { + eprintln!(" {m}"); + } + assert!(mismatches.is_empty(), "{} text placements differ from the twins", mismatches.len()); + assert!(twin_total >= 300, "expected the corpus's texts on keyframes, compared {twin_total}"); + assert_eq!(matched, twin_total); +} + +#[test] +fn the_corpus_bitmaps_and_their_instances_match_the_twins() { + let Some(dir) = corpus() else { return }; + let (mut twin_total, mut matched) = (0usize, 0usize); + let mut mismatches = Vec::new(); + // Every placed bitmap: the twin's library name (leaf) and matrix. + for_each_keyframe(&dir, |tag, doc, k, fr| { + let mut flat = Vec::new(); + flat_elements(&k.elements, anicraft_geom::Affine::IDENTITY, &mut flat); + let mut legacy: Vec<(String, anicraft_geom::Affine)> = flat.iter().filter_map(|(m, e)| match &e.kind { + anicraft_doc::ElementKind::Shape(s) => match s.fill { + Some(anicraft_doc::Paint::Bitmap { bitmap, .. }) => Some((doc.bitmap(bitmap).map_or(String::new(), |b| b.name.clone()), *m)), + _ => None, + }, + _ => None, + }).collect(); + for e in twin_frame_elements(fr).into_iter().filter(|e| local(&e.name) == "DOMBitmapInstance") { + twin_total += 1; + let name = e.attr("libraryItemName").unwrap_or(""); + let name = name.rsplit('/').next().unwrap_or(name).to_string(); + let m = twin_matrix(e); + match legacy.iter().position(|(n, lm)| *n == name && same_affine(lm, &m)) { + Some(i) => { + legacy.swap_remove(i); + matched += 1; + } + None => mismatches.push(format!("{tag}: twin bitmap {name} {m:?} not among {legacy:?}")), + } + } + for l in legacy { + mismatches.push(format!("{tag}: legacy bitmap {l:?} has no twin")); + } + }); + // The library's bitmaps: each twin item by its path, with its pixel size. + let mut items = 0; + for (legacy, twin) in TWINS { + let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin)); + if !legacy_path.exists() || !twin_path.exists() { + continue; + } + let (doc, _) = anicraft_fla::import(&std::fs::read(&legacy_path).expect("reads")).expect("imports"); + let dom = twin_member(&twin_path, "DOMDocument.xml").expect("DOMDocument.xml"); + let dom = craft_xfl::document::Document::parse(&dom).expect("parses"); + for item in dom.root().descendants().filter(|e| local(&e.name) == "DOMBitmapItem") { + items += 1; + let path = item.attr("name").unwrap_or(""); + let size = |k: &str| item.attr(k).and_then(|v| v.parse::().ok()).map_or(0, |t| (t / 20.0).round() as u32); + let found = doc.bitmaps.iter().find(|b| doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Bitmap(b.id))) == path); + match found { + Some(b) if (b.width, b.height) == (size("frameRight"), size("frameBottom")) => {} + other => mismatches.push(format!("{legacy}: twin bitmap item {path} ({}×{}) vs {:?}", size("frameRight"), size("frameBottom"), other.map(|b| (b.name.clone(), b.width, b.height)))), + } + } + } + eprintln!("bitmap instances: {matched}/{twin_total} match the twins; {items} bitmap items compared"); + for m in mismatches.iter().take(30) { + eprintln!(" {m}"); + } + assert!(mismatches.is_empty(), "{} bitmap differences", mismatches.len()); + assert!(twin_total >= 9 && items >= 9, "the corpus's CC badge, once per file"); +} + +#[test] +fn the_corpus_frame_sounds_match_the_twins() { + let Some(dir) = corpus() else { return }; + let (mut twin_total, mut matched, mut legacy_total) = (0usize, 0usize, 0usize); + let mut mismatches = Vec::new(); + for_each_keyframe(&dir, |tag, doc, k, fr| { + let legacy = k.sound.as_ref(); + legacy_total += usize::from(legacy.is_some()); + let Some(name) = fr.attr("soundName").filter(|n| !n.trim().is_empty()) else { + if let Some(s) = legacy { + mismatches.push(format!("{tag}: legacy sound {s:?} has no twin")); + } + return; + }; + twin_total += 1; + let Some(s) = legacy else { + mismatches.push(format!("{tag}: twin sound {name} missing")); + return; + }; + let leaf = name.rsplit('/').next().unwrap_or(name); + let sync = match fr.attr("soundSync").unwrap_or("event") { + "start" => anicraft_doc::SoundSync::Start, + "stop" => anicraft_doc::SoundSync::Stop, + "stream" => anicraft_doc::SoundSync::Stream, + _ => anicraft_doc::SoundSync::Event, + }; + let repeat: u32 = fr.attr("soundLoop").and_then(|v| v.parse().ok()).unwrap_or(1); + // The envelope as the XFL importer reads it: its points, seconds and levels 0..=1. + let points: Vec<(f64, f32, f32)> = kids(fr, "SoundEnvelope").flat_map(|e| kids(e, "SoundEnvelopePoint")).map(|p| { + let n = |k: &str| p.attr(k).and_then(|v| v.parse::().ok()).unwrap_or(0.0); + (n("mark44") / 44_100.0, (n("level0") / 32_768.0) as f32, (n("level1") / 32_768.0) as f32) + }).collect(); + let got_points: Vec<(f64, f32, f32)> = match &s.effect { + anicraft_doc::SoundEffect::Custom(p) => p.iter().map(|p| (p.at, p.left, p.right)).collect(), + _ => Vec::new(), + }; + let same_points = points.len() == got_points.len() && points.iter().zip(&got_points).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6 && (a.2 - b.2).abs() < 1e-6); + let got_name = doc.sound(s.sound).map(|x| x.name.as_str()).unwrap_or(""); + if got_name == leaf && s.sync == sync && s.repeat == repeat && !s.looping && same_points { + matched += 1; + } else { + mismatches.push(format!("{tag}: {got_name:?} {:?} ×{} {got_points:?} vs twin {leaf:?} {sync:?} ×{repeat} {points:?}", s.sync, s.repeat)); + } + }); + // The library's sounds: each twin item by its path, and its length in samples. + let mut items = 0; + for (legacy, twin) in TWINS { + let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin)); + if !legacy_path.exists() || !twin_path.exists() { + continue; + } + let (doc, _) = anicraft_fla::import(&std::fs::read(&legacy_path).expect("reads")).expect("imports"); + let dom = twin_member(&twin_path, "DOMDocument.xml").expect("DOMDocument.xml"); + let dom = craft_xfl::document::Document::parse(&dom).expect("parses"); + for item in dom.root().descendants().filter(|e| local(&e.name) == "DOMSoundItem") { + items += 1; + let path = item.attr("name").unwrap_or(""); + let found = doc.sounds.iter().find(|s| doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Sound(s.id))) == path); + let Some(s) = found else { + mismatches.push(format!("{legacy}: twin sound item {path} missing")); + continue; + }; + let count: u64 = item.attr("sampleCount").and_then(|v| v.parse().ok()).unwrap_or(0); + let format = item.attr("format").unwrap_or(""); + let rate = if format.starts_with("44") { 44_100 } else { 0 }; + let channels = if format.ends_with("Stereo") { 2 } else { 1 }; + if (s.rate, s.channels, s.frames) != (rate, channels, count) { + mismatches.push(format!("{legacy}: sound {path}: {} Hz × {} ch × {} vs twin {format} × {count}", s.rate, s.channels, s.frames)); + } + } + } + eprintln!("frame sounds: {matched}/{twin_total} match the twins ({legacy_total} legacy); {items} sound items compared"); + for m in mismatches.iter().take(30) { + eprintln!(" {m}"); + } + assert!(mismatches.is_empty(), "{} sound differences", mismatches.len()); + assert!(twin_total >= 5 && items >= 4, "the corpus's 5 sound frames and 4 sounds"); +} + +#[test] +fn the_corpus_instance_names_and_buttons_match_the_twins() { + let Some(dir) = corpus() else { return }; + let (mut instances, mut named, mut buttons, mut same) = (0usize, 0usize, 0usize, 0usize); + let mut mismatches = Vec::new(); + for_each_keyframe(&dir, |tag, doc, k, fr| { + let legacy: Vec<(String, String)> = k.elements.iter().filter_map(|e| match &e.kind { + anicraft_doc::ElementKind::Symbol { symbol, .. } => Some((doc.symbol(*symbol).map_or(String::new(), |s| s.name.clone()), e.name.clone())), + _ => None, + }).collect(); + let twin: Vec<(String, String, bool)> = kids(fr, "elements").flat_map(|els| kids(els, "DOMSymbolInstance")).map(|e| { + let n = e.attr("libraryItemName").unwrap_or(""); + (n.rsplit('/').next().unwrap_or(n).to_string(), e.attr("name").unwrap_or("").to_string(), e.attr("symbolType") == Some("button")) + }).collect(); + if legacy.len() != twin.len() { + mismatches.push(format!("{tag}: {} instances vs twin {}", legacy.len(), twin.len())); + return; + } + for ((ls, ln), (ts, tn, button)) in legacy.iter().zip(&twin) { + instances += 1; + named += usize::from(!tn.is_empty()); + buttons += usize::from(*button); + if ls == ts && ln == tn { + same += 1; + } else { + mismatches.push(format!("{tag}: {ls} named {ln:?} vs twin {ts} named {tn:?}{}", if *button { " (button)" } else { "" })); + } + } + }); + // Symbol types: Contents' type byte against the twin's `symbolType`. + let mut kinds = 0; + for (legacy, twin) in TWINS { + let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin)); + if !legacy_path.exists() || !twin_path.exists() { + continue; + } + let (doc, _) = anicraft_fla::import(&std::fs::read(&legacy_path).expect("reads")).expect("imports"); + for m in twin_members(&twin_path).into_iter().filter(|m| m.starts_with("LIBRARY/") && m.ends_with(".xml")) { + let path = m.trim_start_matches("LIBRARY/").trim_end_matches(".xml").to_string(); + let Some(sym) = doc.library.iter().find(|s| doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(s.id))) == path) else { continue }; + let Some(xml) = twin_member(&twin_path, &m) else { continue }; + let Ok(x) = craft_xfl::document::Document::parse(&xml) else { continue }; + let want = match x.root().attr("symbolType") { + Some("graphic") => anicraft_doc::SymbolKind::Graphic, + Some("button") => anicraft_doc::SymbolKind::Button, + _ => anicraft_doc::SymbolKind::MovieClip, + }; + kinds += 1; + if sym.kind != want { + mismatches.push(format!("{legacy}: {path} is {:?}, twin {want:?}", sym.kind)); + } + } + } + eprintln!("instances: {same}/{instances} same symbol and name ({named} named, {buttons} buttons); {kinds} symbol types compared"); + for m in mismatches.iter().take(30) { + eprintln!(" {m}"); + } + assert!(mismatches.is_empty(), "{} instance or symbol differences", mismatches.len()); + assert!(buttons >= 18 && named >= 3, "the corpus's 18 button instances, 3 named CC (got {buttons}, {named})"); + assert!(kinds >= 300, "expected the twins' symbols by path, compared {kinds}"); +} + +#[test] +fn the_corpus_library_folders_match_the_twins() { + let Some(dir) = corpus() else { return }; + let (mut folders, mut items) = (0usize, 0usize); + let mut mismatches = Vec::new(); + for (legacy, twin) in TWINS { + let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin)); + if !legacy_path.exists() || !twin_path.exists() { + continue; + } + let (doc, _) = anicraft_fla::import(&std::fs::read(&legacy_path).expect("reads")).expect("imports"); + let dom = twin_member(&twin_path, "DOMDocument.xml").expect("DOMDocument.xml"); + let dom = craft_xfl::document::Document::parse(&dom).expect("parses"); + let mut want: Vec = dom.root().descendants().filter(|e| local(&e.name) == "DOMFolderItem").filter_map(|e| e.attr("name").map(str::to_string)).collect(); + let mut got: Vec = doc.library_tree.folders.iter().map(|f| { + let chain = doc.folder_chain(f.id); + chain.iter().filter_map(|id| doc.folder(*id).map(|x| x.name.clone())).collect::>().join("/") + }).collect(); + want.sort(); + got.sort(); + folders += want.len(); + if want != got { + mismatches.push(format!("{legacy}: folders {got:?} vs twin {want:?}")); + } + // Every symbol whose twin file has a unique name sits at the twin's path. + let members: Vec = twin_members(&twin_path).into_iter().filter(|m| m.starts_with("LIBRARY/") && m.ends_with(".xml")).collect(); + for sym in &doc.library { + let hits: Vec<&String> = members.iter().filter(|m| m.rsplit('/').next() == Some(format!("{}.xml", sym.name).as_str())).collect(); + let [m] = hits.as_slice() else { continue }; + items += 1; + let want = m.trim_start_matches("LIBRARY/").trim_end_matches(".xml"); + let got = doc.entry_path(anicraft_doc::LibraryEntry::Item(anicraft_doc::LibraryItem::Symbol(sym.id))); + if got != want { + mismatches.push(format!("{legacy}: symbol at {got:?}, twin {want:?}")); + } + } + } + eprintln!("library folders: {folders} twin folders compared, {items} symbols at their twin's path"); + for m in mismatches.iter().take(30) { + eprintln!(" {m}"); + } + assert!(mismatches.is_empty(), "{} library differences", mismatches.len()); + assert!(folders >= 30 && items >= 300); +} diff --git a/docs/adr/0096-legacy-fla-compound-binary-import.md b/docs/adr/0096-legacy-fla-compound-binary-import.md index 678f7b13..a0f9f9f1 100644 --- a/docs/adr/0096-legacy-fla-compound-binary-import.md +++ b/docs/adr/0096-legacy-fla-compound-binary-import.md @@ -1,8 +1,9 @@ # ADR 0096: Legacy Flash import — the compound binary container -Date: 2026-11-16 · Status: accepted — the container (Stage 1), shapes and the timelines -(scenes, layers, keyframes, instances, tweens, library symbols) are implemented; text, media, -scripts and filters continue +Date: 2026-11-16 · Status: accepted — the container (Stage 1), shapes, the timelines +(scenes, layers, keyframes, instances, tweens, library symbols), texts, bitmaps, sounds, button +settings, scripts (kept, not run), shape hints and library folders are implemented; filters, +movie clip component settings and bitmap fills continue ## Context @@ -51,8 +52,10 @@ follow-on work tracked in `openspec/changes/add-legacy-fla-import/`. ## Consequences -- `crates/fla` joins the workspace at L2 (std + `thiserror` + `anicraft-doc`), with a row in - the AGENTS.md map and the LAYERS table. +- `crates/fla` joins the workspace at L2 (std, `thiserror`, `anicraft-doc`, `anicraft-geom`, + `anicraft-text` for laying texts out as the XFL importer does, and the L0 `anicraft-flamedia` + for the media payloads it shares with the XFL importer), with a row in the AGENTS.md map and + the LAYERS table. - Record decoding into `anicraft-doc` documents reuses the XFL importer's seam and its skipped-report pattern; unknown record kinds are counted, never fatal. The engine's open path routes OLE2 bytes to `anicraft_fla::import` before the zip importer sees them. @@ -99,8 +102,42 @@ follow-on work tracked in `openspec/changes/add-legacy-fla-import/`. bit 0) or a group (members as children). `Contents` gives each library item's u32 id and symbol type after its label, and the stage (rectangle in twips, background, 16.16 frame rate) in the document properties. -- **Skipping what isn't decoded.** Texts, bitmaps, a movie clip's or button's extra - settings and anything newer are skipped to where their parent continues — its own end +- **The keyframe's sound block** (after the ease): u16 sound (a `Contents` media id, 0 none), + u16 n and n envelope points (u32 position in samples at 44.1 kHz, u16 left and right level + `0..=32768`), u16 loops, u8 sync, u32 in and out points (`0x3FFFFFFF`: none), u16 zoom. + The frame actions are a 16-byte header and the frame script (a UTF-16 string, line ends as + written); the shape-hint list is a `CObList` of `CMorphHintItem`s (i32 start x, y, end x, + y in twips, u32 key). +- **Buttons and movie clips** carry their own settings after the common instance fields: a + button `0B`, the 16-byte actions header, its handler script (`on (release) { … }`), a byte + (track as menu — a hypothesis, 0 throughout the corpus), its **instance name** and u32 0; a + movie clip `08`, the header, its clip-event script, its name, then component settings + (not decoded). The instance's own name string in the common fields is empty on every + corpus instance. The instance class, not the library item's type, is what the twins write + as an instance's `symbolType`; the symbol's type comes from `Contents`. +- **Texts** (`crates/fla/src/text.rs`): a `CPicText` record is its head (the common base, + kind `0D`), matrix, bounds, field flags, then runs of an attribute block (size, face, + RGBA, bold, italic, kerning, position, alignment, spacing, target, rendering) and UTF-16 + characters; it becomes the text block the XFL importer makes of the twin's + `DOMStaticText` / `DOMDynamicText`, laid out with this computer's fonts. +- **Bitmap instances** (`CPicBitmap`, kind `02`): the matrix, the u16 media id and a byte + (0); placed as the XFL importer places a `DOMBitmapInstance` (the image's rectangle, + filled with it). +- **The library in `Contents`** (`crates/fla/src/library.rs`): every item has an identity + block — u32 6, u32 1, the parent folder's item id, u32 1, its own item id (two u32, the + twin's `itemID`). Folders are `u32 4`, a name, the identity block; a folder's path is its + parents' names. Media items are `CMediaBits` / `CMediaSound` objects: version 6, the data + stream's name, the leaf name, the **u16 media id** (what placements and frame sounds refer + to — not the stream's number), the source path and import time, the identity block, the + common item settings, then a sound's format byte (SWF's bits: `0F` 44.1 kHz 16-bit stereo, + `0E` mono) and sample count. The `Media ` / `M ` streams are byte for byte the + twins' `bin/*.dat` files, so one L0 decoder (`anicraft-flamedia`) serves both importers: + Animate's lossless bitmap (zlib in u16-length chunks, premultiplied A, R, G, B rows) and raw + 16-bit PCM (it comes across as a WAV). The publish settings in `Contents` give + `Vector::ActionScriptVersion` ("2" on every corpus file), the language scripts are kept in. +- **Skipping what isn't decoded.** Filter lists, a movie clip's component settings, text and + bitmap records in a layout not seen (or that don't end where their parent continues), and + anything newer are skipped to where their parent continues — its own end (`00 00` and its base with its kind byte) or the next sibling, confirmed by parsing that sibling — counting class declarations inside the skipped bytes so later class numbers stay right. A keyframe whose artwork doesn't decode keeps its timing (its fields are found @@ -109,17 +146,42 @@ follow-on work tracked in `openspec/changes/add-legacy-fla-import/`. - **Mapping** mirrors the XFL importer: folders hold no frames, zero-length frame records are dropped (the twins don't have them), raw shapes merge (ADR 0042), comments are reported, classic and shape tweens keep their eases (shape tweens are rebuilt by the - engine; the stored morph cache and hints are not used), movie clips and buttons loop. - A moved transformation point becomes the instance's pivot (ADR 0111). + engine; the stored morph cache is not used), movie clips and buttons loop. A moved + transformation point becomes the instance's pivot (ADR 0111). Label kind 1 is a comment; + 0 and 2 are taken for a name and an anchor (Flash's menu order, a hypothesis: every corpus + label is a comment), both a `Keyframe.label`, as XFL's names and anchors are. Shape hints + go on the shape tween's start keyframe (ADR 0023), each with its start and end point, + snapped onto the outlines within 2 px as the XFL importer pairs them (the twins keep them in + `morphHintsList`, which the XFL path doesn't read, so here the legacy file opens with more + than its twin). A frame sound keeps its sound, sync (0 event, 1 start, 2 stop, 3 stream — + only stream is in the corpus, the rest a hypothesis by Flash's menu order), repeats and + envelope (the format has no effect byte: an envelope plays as its points, as the XFL + importer reads one without a preset name); in and out points are reported (played whole), + as there. Frame scripts are kept verbatim as `FrameScript::Source` in the document's + language, never run by the import; handler scripts on buttons and movie clips are reported + ("scripts on instances"), as the XFL importer reports them. A button's name becomes the + element's instance name when actions can use it. Library items go into their folders; + empty folders come across too. - **Verified differentially** against all 9 pairs: 337/337 timelines have the twins' layers, 1628/1628 layers their keyframes (index and duration), 6993/6993 keyframes their tween - kind, 4457/4457 instances their library item, matrix, loop mode and first frame; the - stage matches on all pairs; rendered frames of the movie template and the character rigs - match their twins' apart from text and dotted strokes. -- **What stays open**: text, bitmaps, sounds, frame and button scripts, filters (an - instance with filters loses its blend mode too), dashed/dotted strokes, instance names - on buttons, library folders — each counted in the report's `skipped` per kind. Committed - fixtures stay synthetic; the CC BY-NC-SA corpus runs via `ANICRAFT_FLA_CORPUS`. + kind, 4457/4457 instances their library item, matrix, loop mode, first frame and instance + name (18 buttons, 3 named); 335/335 non-empty texts sit on the twins' keyframes with their + kind, characters and position (and 372/372 text records match field for field); 9/9 bitmap + instances and bitmap items (name, folder, size), 5/5 frame sounds (sound, sync, repeats, + envelope) and 4/4 sound items (folder, rate, channels, length); 39/39 library folders and + 328/328 symbols at their twins' library paths and types; the stage matches on all pairs. + Rendered frames of the movie template and the character rigs match their twins' apart + from dotted strokes, text antialiasing on a few pixels, and the shape tweens whose hints + the twins' XFL path drops. +- **What stays open**, each counted in the report's `skipped` per kind: filters (an instance + with filters loses its blend mode too; the corpus's six filtered instances all hold one + blur in a 52-byte block before the blend — a type byte 1, then what look like distance, + blur x, blur y and angle as f32 and quality and strength as u32 — too few samples to tell + the fields apart), a movie clip's component settings, bitmap fills (kinds `40`–`43`, absent + from the corpus), dashed and dotted strokes, sound in and out points (as in the XFL + importer), a button's track-as-menu byte (no place in the model), sound formats other than + raw 16-bit PCM and bitmaps other than the lossless layout or PNG / JPEG. Committed fixtures + stay synthetic; the CC BY-NC-SA corpus runs via `ANICRAFT_FLA_CORPUS`. ## References diff --git a/docs/roadmap.md b/docs/roadmap.md index c89e49cb..bbd4bdf4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -21,7 +21,7 @@ This integration depends on craft-libs #1962 and still requires hosted parity va | Headless | CLI: info, render, render-seq, **gif**, **apng**, **webp**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. **Live control** (ADR 0104, `docs/control-protocol.md`): `anicraft --control ` and `anicraft-cli mcp --bridge ` run the same tools on the open window, on this computer only, with a per-run token in `control.json`. **Automation roots** (ADR 0124, AGENTS.md rule 18): `mcp` refuses to start without `--automation-read-root` and `--automation-write-root`; an assistant's commands read inside the read roots and write inside the write root only, checked in the engine (`engine::access`: given paths before the command runs, every `vfs` call, ffmpeg, XFL folders and the plug-in registry) on the resolved path (`..`, links, junctions, letter case), with errors that name the root; the bridge carries the roots and the window applies them per call (control protocol 2); `serve` takes them optionally (not yet: roots saved in the app's preferences as a cap on any bridge, a shared craft-libs helper, environment variables, file handles held open against a swapped link). | | Sound | **Audio layers, first slice** (ADR 0020): WAV (own reader), Ogg Vorbis (`lewton`) and MP3 (`nanomp3`) import, bounded and crash-proof; sounds live in the library, stored in `.anicraft` as imported, decoded once in the background. A sound belongs to a keyframe as in Animate (Properties › Sound: name, Sync Event/Start/Stop/Stream, Repeat ×N or Loop); Import to Stage puts one on a new layer spanning its length, Import to Library only adds it, the Library previews, places and deletes sounds. The timeline draws each sound's waveform over its span. Stage playback plays the mix through `cpal` (default feature `sound-output`) and the playhead follows the audio clock; stream sounds resync after a jump and scrubbing plays one-frame snippets. Mixing is pure and sample-exact (`doc::sound::voices` + `audio::mix`, Catmull-Rom resampling between rates). Headless: `sound.place/set/remove/rename/delete`, `file.import_to_library`, **`file.export_audio`** (WAV, 16/24-bit or float, any rate), and Export Video carries the soundtrack (Opus in WebM, AAC in MP4, by the user's ffmpeg). **Second slice** (ADR 0039): each frame sound has an **Effect** (None, Left channel, Right channel, Fade left to right, Fade right to left, Fade in, Fade out, shaped over the time it is heard, or **Custom**: up to 16 volume points per channel in the **Edit Envelope** window, drawn on each channel's waveform; the timeline's waveform follows the envelope). Layers holding sounds get a **Volume** and **Mute** (Properties, and a speaker toggle in the timeline); volumes multiply down through symbols and muted layers are silent in playback and every export. **Sounds inside symbols** play: a graphic's on its own frames mapped to the parent's time (loop mode and first frame apply; streams join mid-way and follow the parent playhead), a movie clip's on a loop from when the instance appeared; in the interactive player and **Test Movie** (which now has sound, the picture keeping time with it) movie clips start theirs as their own timelines reach them. The HTML page carries envelopes, volumes and graphic sounds. Headless: `sound.set {effect, envelope}`, `layer.set_volume`, `layer.toggle_mute`. **Sounds on button frames** (ADR 0057) play in Test Movie and the HTML page as the pointer changes the button's state (Over, Down, and Up and Hit on leaving and release, as the SWF format keeps them; never in the soundtrack); `control.test_movie` lists the sounds it starts. **XFL** brings sounds whose file is in the package (WAV, Ogg, MP3) with the sounds on frames that use them, buttons' included. **Output polish** (ADR 0095): the playhead follows the sound *heard* (the device's latency taken off, frames dropped rather than drifting; under a frame off over an hour in tests), event sounds play to their end across a loop and after the last frame (Enter stops all), a **monitor volume and mute** in the timeline header (Control › Mute Sounds; the listener's, in preferences, never in exports), **Control › Audio Scrubbing** (a slice of at least 1/20 s), a lost or missing device never crashes (silent playback, one notice, a log line, reopened on the next play; a new default device is followed), and the **web build plays sound through Web Audio**. The device sits behind an `Output` trait, so the clock and mixing paths are tested with a fake one. Sounds kept only as Animate's own raw PCM data (`bin/*.dat`, read by `anicraft-flamedia` and checked against the item's `sampleCount`) come across as WAV. **Audio to keyframes and auto lip-sync, first slice** (ADR 0114, #332): `anicraft_audio::analysis` gives a sound's loudness per movie frame (RMS, normalised to the loudest frame, gated by a threshold, smoothed by a centred average) and, for speech, one of five mouth shapes per frame (rest, open, wide, round, closed) from band energies of a short FFT sorted by the vowels' public formant values, with no speech recognition; pure, deterministic and bounded (10 minutes of sound: levels in 19 ms, mouths in 135 ms). **Convert Audio to Keyframes** (`sound.to_keyframes`; Modify › Timeline, Properties › Sound) maps the loudness onto an object's scale, alpha, position or rotation offset, or a graphic symbol's first frame, as keyframes or as a motion tween's property curve; **Auto Lip-Sync** (`sound.lip_sync`; also beside Looping in Properties) keys the frames of a graphic symbol of mouth poses, found by its frame labels as the mouth chart template names them; `sound.analyse` reports both headless. One dialog previews everything live (a graph of loudness, threshold, value and key ticks, or a row per mouth; the keys themselves on the stage and timeline), one undo step. Not yet: driving the camera, armature layers or filter values from sound; classic tweens between the keys; more than five mouth shapes (F/V, L and the other consonants are placed by hand) or a script as input; the sound's effect and layer volume in the measured loudness; compressed or 8-bit sounds in Animate's own data format (unobserved; reported), **Split Audio** and a sound's in and out points (the start and end handles in Edit Envelope; a frame's sound always plays from its beginning, #502), sound effects and in/out points from XFL, sound panning beyond the envelope, audio in Lottie, stream sounds that follow go-tos in the HTML page, lossless compression of stored WAVs, choosing an output device other than the system's default, `stopAllSounds` as a timeline action. **Importing video** (#369, ADR 0116): File › Import › Import Video… reads any video the user's own ffmpeg reads (found as Export Video finds it; a clear message with how to install it when it is missing; no decoder in AniCraft, pictures cross a pipe as PPM with every size checked and both readers fuzzed). **Frames in the document**: bitmaps on a new layer from the playhead, one keyframe per picture at the document's frame rate (frame step 1–60, largest size, start and length), in a Library folder, with the sound track as a stream sound on its own layer; one undo step. **Reference layer**: a locked guide layer right under the active layer shows the video beneath what is drawn, for tracing, in no export; frames are decoded on demand in runs of 16 on their own thread and kept within 256 MB, the layer's opacity fades it, Layer Properties relinks or removes it. The dialog says up front how many pictures of what size and how much memory, and where a long video is cut (2000 pictures, 1 GB decoded); a progress window with Cancel; cancelling or failing leaves the document unchanged. Headless: `file.import_video`, `file.video_info`, `layer.set_video`. Not yet: sound with a reference layer, moving or scaling the reference with the tools, a reference inside a symbol, video with alpha, collecting footage with the document, compressed storage of the imported sound, video in the web build. | | Documents | **Several open at once** (ADR 0112): tabs above the edit bar, the shown document in `App`, the others parked whole (session, view, autosave) and exchanged in O(1) (0.2 µs median); the engine and the CLI/MCP stay one document per session. Cross-document paste remaps Library ids (`engine::transfer`). Not yet: a tab in its own window, another document's Library in the panel, session restore, a shared undo budget. | -| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (WebP container writing delegates to shared `craft-webp`; APNG framing remains app-local; ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). Archives whose end record overstates the directory's size, as Flash CS5 to Animate write most `.fla` files, open (#356; until the shared reader does it, storytold/craft-libs#1986). Binary `.fla` (Flash CS4 and earlier) is not read and says so (#163, #289: a stretch goal in `requirements.md`, no clean-room reader yet). Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Bitmaps kept only in **Animate's own lossless data** (`bin/*.dat`: zlib-compressed premultiplied ARGB) decode too, through `anicraft-flamedia`, which the legacy importer shares; its unobserved variants (other pixel formats, uncompressed, JPEG-backed) are reported, not guessed. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). Shared `craft-xfl` readers now parse filters, shape hints, tween easing, and frame-sound envelopes; AniCraft retains document-model mapping and validation. The XFL schema audit remains in progress, including per-character styles and motion-tween records; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): each frame is evaluated, artwork that persists (same layer and element, or the same look on the same layer across keyframes) becomes one shape layer, and what changes is written as **keyframes with Lottie's Bézier eases** (ADR 0089): holds where values stay, eased keys wherever an ease of the document draws the frames exactly (linear, Classic, Bézier, custom curves, Quad/Cubic/Back/Bounce; a key per cubic piece), checked at every frame, and a hold key per frame only where nothing exact exists (Elastic, Sine…, reported once); moving artwork keeps its outline in its own space under an animated group transform (position, rotation, skew, scale), and shape tweens between outlines of one structure are shape keys; a playback parity test plays the file with a Lottie player written from the spec through the oracle at every frame (sample scenes, a movie of every ease, the XFL corpus); files 57–90 % smaller (demo 46.7 → 10.4 kB); one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. **Hostile documents stay bounded**: keyframes past frame 100,000 are trimmed on load, and one evaluation or bounds query visits at most a million elements, so symbols that double at every level draw in part instead of hanging (not yet: the same allowance in the player's stepping and the other walks over nested symbols; a note to the artist when artwork was left out). A document holding a non-finite number saves to a file that opens again (the number as 0, a ruined element transform as identity). | +| Files | `.anicraft` JSON load/save (v3, with scenes; v1 and v2 files open as one scene), PNG frame and sequence export, **animated GIF export** (parallel render and quantize, exact frame timing, looping), **animated PNG and animated WebP export** (WebP container writing delegates to shared `craft-webp`; APNG framing remains app-local; ADR 0063: full colour and real alpha, transparent or on the stage colour; every frame exactly the renderer's; repeated frames merged into longer delays; later frames only the rectangle that changed (APNG blends opaque changes over, WebP replaces); APNG delays exact fractions of the frame rate, WebP milliseconds that never drift; loop forever, once or N times; File › Export, Publish Settings, the web build's downloads, `anicraft-cli apng`/`webp`; not yet: lossy WebP (no permissive pure-Rust VP8 encoder exists), dispose-to-background frames, palette or RGB APNG for smaller files), **SVG frame export** (from the same evaluated frame as the renderer: stage-space paths, renderer-matched stroke widths, caps, joins and dashes, gradients under `gradientTransform`, colour effects baked in, masks as nested `clipPath`s). **Opens Animate documents** (`.fla`, `.xfl`, XFL folders; ADR 0009; `.fla` archives in every common zip layout, ZIP64 included, and hostile ones refused with a readable error, ADR 0054): stage, first scene, layers, keyframes, labels, classic tweens with ease, shapes (solid/linear/radial fills, strokes), groups, primitives, symbol instances (matrix, alpha, tint, loop, blend mode, all seven filters), library symbols, **shape tweens**, **layer folders** and **mask layers** (masks inside folders too); imported files are untitled so Save never overwrites them; what isn't supported yet is reported after opening. One damaged bitmap, sound or library symbol is left out and reported rather than refusing the whole file (#226), and a document without a stage colour gets Animate's default white (#163). Archives whose end record overstates the directory's size, as Flash CS5 to Animate write most `.fla` files, open (#356; until the shared reader does it, storytold/craft-libs#1986). **Binary `.fla` (Flash 8–CS4)** opens through its own clean-room compound-file reader (ADR 0096; #163, #289): scenes, layers, keyframes, shapes, groups, symbol instances, classic and shape tweens with eases and shape hints, texts, bitmaps, sounds on frames, button names, frame scripts (kept, not run) and library folders, differentially checked against the same files saved by Animate; filters, movie clip component settings and bitmap fills are reported, not read yet. Every scene comes across. **Bitmaps**: library items whose image is in the package as PNG or JPEG (the original in `LIBRARY/`, else the `bin/` data file when it is PNG or JPEG), instances, and bitmap fills with their matrix (twips scale removed; repeating unless clipped); Bitmaps kept only in **Animate's own lossless data** (`bin/*.dat`: zlib-compressed premultiplied ARGB) decode too, through `anicraft-flamedia`, which the legacy importer shares; its unobserved variants (other pixel formats, uncompressed, JPEG-backed) are reported, not guessed. **Text** (ADR 0014): static, dynamic and input text fields become text blocks laid out by `anicraft-text`, with face (by PostScript name, family, or the family the name suggests; `_sans`/`_serif`/`_typewriter`), size, colour, bold/italic, alignment, letter and line spacing, margins, matrix, fixed width (wraps) or auto-size, and several lines; runs in different styles become one block per run of same-style lines, stacked as in Animate; a line mixing styles takes its main style and is counted; missing families fall back and are named in the report; dynamic/input fields come across as static text (reported). **Shape hints** on shape tweens (a tolerant self-authored `shapeHints` reader, ADR 0023). Colour effects in every style (Brightness, Tint, Advanced, Alpha; ADR 0056), movie clip and button instance names, one-segment custom eases (as cubic Béziers); a symbol without `symbolType` is a movie clip; frame comments aren't labels. Stroke caps, joins and miter limit, dashed and dotted strokes (ADR 0046; ragged, stipple and hatched are drawn solid and reported). Reported rather than silently changed: gradient strokes, repeating/reflecting, focal-point, elliptical and linear-RGB gradients, reverse loop modes, extra tween spins. A self-authored corpus with golden renders covers all of it (ADR 0035). Shared `craft-xfl` readers now parse filters, shape hints, tween easing, and frame-sound envelopes; AniCraft retains document-model mapping and validation. The XFL schema audit remains in progress, including per-character styles and motion-tween records; **frame scripts are kept** verbatim (scenes and every symbol, with the language from the publish settings), with symbol linkage classes and the document class, and the report lists them as kept, not run (ADR 0013 tier 1; scripts on instances and linkage on bitmaps and sounds are reported); **Import to Stage (Ctrl+R) for SVG drawings**: editable shapes on a new layer at the playhead, with groups, use and symbols, transforms, viewBox, styles, opacity and gradients; **clip paths and opaque masks** (ADR 0021) become mask layers in a folder named after the file (clips that cut nothing dropped, clips inside clips intersected exactly when all but one are convex polygons, curves kept), and **text** becomes text blocks, one per text chunk (position, anchor, font family list, size, weight, style, letter spacing, fill), with missing fonts named; stroke caps, joins, miter limits and dashes come across (ADR 0046); soft masks, per-character positions and text on a path are reported, as is anything else unsupported. **Sprite sheet export**: movie frames on one PNG grid (parallel render, columns/padding/scale, transparent or stage background) with a "JSON hash" frame map (rectangles, sizes, per-frame durations). **Video export**: WebM (VP9) or MP4 (H.264) by streaming raw frames, in order and rendered in parallel batches, to the user's own ffmpeg (no encoder bundled; ffmpeg from a parameter, `ANICRAFT_FFMPEG` or the PATH; argument lists, never a shell). **Lottie export** (`file.export_lottie`): each frame is evaluated, artwork that persists (same layer and element, or the same look on the same layer across keyframes) becomes one shape layer, and what changes is written as **keyframes with Lottie's Bézier eases** (ADR 0089): holds where values stay, eased keys wherever an ease of the document draws the frames exactly (linear, Classic, Bézier, custom curves, Quad/Cubic/Back/Bounce; a key per cubic piece), checked at every frame, and a hold key per frame only where nothing exact exists (Elastic, Sine…, reported once); moving artwork keeps its outline in its own space under an animated group transform (position, rotation, skew, scale), and shape tweens between outlines of one structure are shape keys; a playback parity test plays the file with a Lottie player written from the spec through the oracle at every frame (sample scenes, a movie of every ease, the XFL corpus); files 57–90 % smaller (demo 46.7 → 10.4 kB); one layer order consistent with every frame (topological); checked against the reference web player (matches the renderer). Reported, not exported: bitmap fills, nested masks (innermost kept), group fades (per shape), stretched radial gradients (circles). **HTML canvas export** (`file.export_html`, ADR 0028): one self-contained web page that plays the movie, buttons and actions included (see Interactivity). **Drops, Open Recent and the start screen** (ADR 0059): files dropped on the window open (documents) or import onto the stage at the drop point on the active layer, or into the Library folder under the pointer, in one undo step (`file.drop`), with a drop highlight; File › Open Recent (10 recent, pinned favourites, missing files greyed with Remove) kept in the preferences; a start screen at launch with New presets (1280 × 720, 1920 × 1080, 1080 × 1080, 1080 × 1920, custom), Open, the sample and recent files with thumbnails captured on save. **Templates, SVG into the Library and drops on the timeline** (ADR 0065): six built-in templates made in code (banners 728 × 90 and 300 × 250, social square 1080 × 1080 at 30 fps, storyboard 16:9 panels, character turnaround, lip-sync mouth chart) with guides on a locked guide layer, on the start screen and File › New from Template; File › Save as Template keeps the document with a picture in the settings folder by category (replacing and deleting confirm); an SVG dropped on or imported to the Library becomes one graphic symbol named after the file, in the folder under the pointer; a sound dropped on a layer's frame goes onto that keyframe, an image or SVG onto that layer in a keyframe made there if needed, one undo step, with a highlight on the cell. Not yet: exact drop positions on the desktop (eframe 0.36 and 0.37 are on winit 0.30, which gives none during a drag; a drop waits for the first pointer move, else lands mid-view), user template descriptions and renaming, several documents at once. **Publish Settings and Publish** (ADR 0060): the formats to publish, with their options and output names, saved in the document; File › Publish (Shift+F12) writes them all in the background with progress, Cancel and one report; presets in Preferences. **Hostile documents stay bounded**: keyframes past frame 100,000 are trimmed on load, and one evaluation or bounds query visits at most a million elements, so symbols that double at every level draw in part instead of hanging (not yet: the same allowance in the player's stepping and the other walks over nested symbols; a note to the artist when artwork was left out). A document holding a non-finite number saves to a file that opens again (the number as 0, a ruined element transform as identity). | | Library | **Library management, first slice** (ADR 0050): nested **folders** (New Folder, rename, drag items and folders in and out, Move to; deleting a folder that holds items asks), **inline rename** (F2 or double-click the name; names unique per folder, case aside), **Duplicate Symbol** (fresh ids, same folder, “Ball copy”), **Swap Symbol** in Properties (keeps transform, colour effect, filters, looping and name), a **use count** column, **Select Unused Items** and **Delete Unused Items** (unused = not reachable from any scene; linkage classes count as used; asks first), deleting used items asks and removes their instances, fills and keyframe sounds, **sort** by name, type, use count or date added, **search** (opens the folders that lead to a match), multiple selection, a **preview** (a symbol's first frame from the oracle, a bitmap as smoothed or not, a sound's waveform with play) and **item properties** (symbol type and linkage class, bitmap **Allow Smoothing**, which the oracle, the GPU stage, SVG and HTML honour). Folders are a side table in the document (older files open flat); XFL import keeps folders and Allow Smoothing. Headless: `library.items/new_folder/rename/move/duplicate/delete/unused/delete_unused/set_smoothing`, `element.swap_symbol`. **Second slice** (ADR 0053): **drag items onto the stage** (symbols and bitmaps land at the pointer on the active layer at the playhead, sounds go onto its keyframe; several at once; one undo step; inside a symbol open for editing too), **Place on Stage** (button, right-click, or Enter) at the centre of the view, **Swap Bitmap** in Properties (a placed bitmap keeps its corner and takes the new size; a bitmap fill keeps its shape), **Trace Bitmap** and **Convert to Bitmap** in Modify (#463: a placed bitmap becomes filled raw shapes that tile, with Animate's four settings; a selection becomes one Library bitmap in its place; bounded at 4096 × 4096 pixels and 20,000 shapes; not yet: a live preview in the dialog, a progress bar for very large traces, tracing a bitmap fill inside another outline, a resolution choice for Convert to Bitmap), a **Convert to Symbol** dialog with name, type and **folder** that offers the last folder and type again, and **"mixed" on every Properties row** for several elements (Scale, Rotation, Alpha, Symbol, Type, Filters, Blending, Looping, First frame, Fill, Bitmap, Stroke, Width, Style; each row compares only the elements it edits; editing a mixed row sets all, and Type sets every selected instance's symbol). Headless: `library.place {items, x, y}` (and `sound`), `element.swap_bitmap`, `kind` and `folder` on `modify.convert_to_symbol`. **9-slice scaling** (ADR 0055): Enable guides for 9-slice scaling on a symbol (Library or Properties). Scaled instances keep their corners, stretch their edges one way and the centre both ways, and strokes keep their width. Rotation and skew apply after; nested symbols, text and bitmaps scale normally. Guides are dragged as dashed lines while editing the symbol in place, or typed in Properties. The CPU, GPU, SVG and Lottie output all show it, and XFL `scaleGrid*` attributes are imported; guides switched off are kept and come back when switched on (ADR 0057). Not yet: 9-slice in HTML canvas export (scaled as a whole and reported), guides in Library previews, snapping guides. Not yet: shared libraries and importing items from another document, linkage on bitmaps and sounds, bitmap compression, dropping files from the desktop, a picture of the item while dragging, Swap Bitmap on a Library item (every use), mixed text style rows, a Colour Effect row with tint. | | Data-driven animation | **Data tables that drive animation, first slice** (ADR 0118, #416, #417, #418): numeric **tables kept in the document** as Library items, imported from **CSV, TSV or JSON** (File › Import › Import Data Table; through craft-csv; named columns, gaps, text-only columns left out and reported, a row per frame or a **key column** for a row per keyed time; 256 tables, 100 000 rows, 1 000 000 cells, files up to 32 MB; hostile input refused or cut to the limits), a **table viewer**, **Import Again** that keeps every binding; **bindings** that let a column drive a symbol instance's **X, Y, Scale X, Scale Y, Rotation, Alpha** or **the frame a graphic shows** over a span of frames, with scale, offset, linear or step interpolation and reversed key ranges, edited live in Properties › Data and evaluated purely in `evaluate` (stage, oracle, GPU stage, Test Movie and every export that draws frames agree); **Bake to Keyframes** (every frame looks as it did); `data.*` commands headless, over the CLI and MCP, and for plug-ins (all but reading a file). Not yet: bindings that follow copy, paste and duplicate; baking inside a motion tween and a Lottie export warning for live bindings; editing cells in the viewer, adding and renaming columns; text columns for captions; binding skew, tint, filter values, shapes, text and group members; expressions; audio amplitude into a table. | | Find & navigation | **Find and Replace, and the Movie Explorer, first slice** (ADR 0058): Edit › Find and Replace (Ctrl+F) finds text (text fields, frame labels, layer and instance names, frame scripts; match case, whole word, regular expressions on a linear-time engine), fonts, colours, symbols, sounds and bitmaps, in this scene with its symbols or the whole document; results as you type; F3 / Shift+F3 go there, opening symbols in place; Replace, and Replace All as one undo step that asks above 100 places. Window › Movie Explorer (Alt+F3), beside the Library: scenes › layers › keyframes › instances (into their symbols), text, sounds, bitmaps and scripts, symbol definitions, Show filters and search, double-click to go there. Headless `find.search`, `find.replace`, `find.goto`, `explorer.tree`. Not yet: action parameters, ActionScript strings apart from code, font size and style, colour tolerance, renaming in the explorer. |