fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
//! A notation program's PDF read from its vectors (docs/pdf-import.md).
//!
//! A PDF that MuseScore, Dorico, Sibelius or Finale wrote holds its music as the engraver set it:
//! every notehead, rest, clef, accidental, flag and dot a glyph of a SMuFL music font at its exact
//! place, every staff line, stem, barline and beam a drawn line or shape, and the words as text.
//! Read from there, a notehead's pitch is its place on the staff and a note's length its head,
//! flags or beams and dots: nothing is guessed from a picture, and nothing needs a model or a
//! server, so it runs in the browser.
//!
//! [`read_pdf`] finds the systems (staves a line joins), the parts (staves the barlines join are a
//! piano's; a staff with words under it a voice), and reads system after system into `.fmn`
//! (docs/transcribing.md), compiling each after the ones before it with [`fm_transcribe`]: what
//! comes out always opens. It takes notes and chords in up to two voices a staff (rests a program
//! hid are filled in), rests, dots, ties, slurs, accidentals (cautionary ones too), key, time and
//! clef changes (inside a system too), a pickup, dynamics, fermatas, the common articulations and
//! ornaments, tuplets, grace and cue notes, tremolos, fingering, glissandos, cross-staff notes, the
//! barlines (double, final, repeats), endings, the segno and coda, To Coda, Fine, D.S. and D.C.,
//! printed beams that differ from the beat, and the words of each voice, hyphens and held
//! syllables included; and over and under the staves (`marks.rs`) hairpins, words, a tempo and
//! its metronome mark, rehearsal marks, chord symbols, the pedal and ottava lines. The music
//! fonts before SMuFL (Sibelius's, Finale's, capella's, Doremi) are read as SMuFL (`legacy.rs`),
//! as are LilyPond's, by its glyphs' names (`lilypond.rs`), and MuseScore's old one (`mscore.rs`).
//! A staff's bar it cannot time (two voices that do not add up however its rests are given out),
//! or whose notes do not stand where the other staves' say they start (`columns.rs`), is left as
//! a bar's rest and listed, saying where and why; a scan, or a PDF in a music font it does not
//! know, is refused.

mod audit;
mod between;
mod choir;
mod columns;
mod cues;
mod dashes;
mod dotways;
mod doubt;
mod frac;
mod judge;
mod jumps;
mod key;
mod layout;
mod legacy;
mod lilypond;
mod longbars;
mod lyrics;
mod marks;
mod mscore;
#[doc(hidden)]
pub mod names;
mod options;
mod page;
mod passing;
mod pictures;
mod read;
mod repeats;
mod review;
mod shapes;
mod shown;
mod smufl;
mod spacing;
mod staff;
mod stems;
mod svg;
mod ties;
mod times;
mod tuplets;
mod unison;
mod words;
mod write;

pub use audit::{audit_pdf, Audit, BarAudit, SystemAudit};
#[doc(hidden)]
pub use page::Picture;
#[doc(hidden)]
pub use pictures::{shape as picture_shape, Shape as PictureShape};
pub use read::{Place, Reading, Refusal, Unread};
pub use review::{
    bar_text_json, read_pdf_review, reading_json, BarPlace, BarText, Choice, NoteMark, Question,
    Review,
};
pub use svg::page_svg;

/// A page's staff space, its staves' lines and the images it draws (`pictures_of`).
#[doc(hidden)]
pub type PicturePage = (f64, Vec<[f64; 5]>, Vec<Picture>);

/// The images each page of a PDF draws, as their ink, with the page's staff space (its staves'
/// median; 0 for a page with none) and its staves' lines, for the `pictures` example.
#[doc(hidden)]
pub fn pictures_of(bytes: &[u8]) -> Result<Vec<PicturePage>, String> {
    Ok(page::read_pages(bytes)?
        .into_iter()
        .map(|p| {
            let staves = p.staves();
            let mut sps: Vec<f64> = staves.iter().map(|s| s.sp()).collect();
            sps.sort_by(f64::total_cmp);
            let sp = sps.get(sps.len() / 2).copied().unwrap_or(0.0);
            (sp, staves.iter().map(|s| s.lines).collect(), p.pictures)
        })
        .collect())
}

/// Read a PDF's bytes into a score, or say why it cannot be read. A staff's bar it cannot read
/// is left as a bar's rest and listed in [`Reading::unread`], while those are no more than an
/// eighth of the staves' bars; past that the PDF is refused for the first of them.
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let reading = fm_vector::read_pdf(&std::fs::read("score.pdf")?)?;
/// std::fs::write("score.musicxml", reading.musicxml)?;
/// # Ok(())
/// # }
/// ```
pub fn read_pdf(bytes: &[u8]) -> Result<Reading, Refusal> {
    read_pdf_leaving(bytes, 0.125)
}

/// [`read_pdf`], leaving up to `max_unread` of the staves' bars unread (0: none; 1: any number).
pub fn read_pdf_leaving(bytes: &[u8], max_unread: f64) -> Result<Reading, Refusal> {
    let pages = page::read_pages(bytes).map_err(|why| Refusal { system: None, why })?;
    read::read(&pages, max_unread)
}

/// Whether a PDF looks like a notation program's own: music-font glyphs on its pages, as text.
/// Cheap next to [`read_pdf`]; a scan has none.
pub fn is_engraved(bytes: &[u8]) -> bool {
    page::read_pages(bytes)
        .map(|pages| {
            pages.iter().any(|p| {
                p.glyphs
                    .iter()
                    .filter(|g| smufl::head(g.code).is_some())
                    .count()
                    > 10
            })
        })
        .unwrap_or(false)
}

/// The layout found, in words: each system's page and staves, and the parts (for looking into a
/// refusal).
pub fn describe_layout(bytes: &[u8]) -> Result<String, String> {
    let pages = page::read_pages(bytes)?;
    let systems = layout::systems(&pages);
    let mut out = String::new();
    for (i, s) in systems.iter().enumerate() {
        let tops: Vec<String> = s
            .staves
            .iter()
            .map(|st| format!("{:.0}", st.top()))
            .collect();
        out.push_str(&format!(
            "system {} page {}: staves at {}\n",
            i + 1,
            s.page + 1,
            tops.join(" ")
        ));
    }
    for p in layout::parts(&pages, &systems) {
        out.push_str(&format!("part {} {:?} {:?}\n", p.id, p.name, p.kind));
    }
    for (pi, p) in pages.iter().enumerate() {
        let braces = p
            .glyphs
            .iter()
            .filter(|g| (0xE000..=0xE003).contains(&g.code))
            .count();
        out.push_str(&format!(
            "page {}: {} music glyphs, {} braces/brackets as glyphs, {} vertical lines\n",
            pi + 1,
            p.glyphs.len(),
            braces,
            p.vlines.len()
        ));
    }
    Ok(out)
}

/// Everything drawn over one system (1-based), for looking into a refusal: the music glyphs, the
/// words, and the short lines, shapes and curves, by place.
#[doc(hidden)]
pub fn dump_system(bytes: &[u8], system: usize) -> Result<String, String> {
    let pages = page::read_pages(bytes)?;
    let systems = layout::systems(&pages);
    let s = systems
        .get(system.wrapping_sub(1))
        .ok_or("no such system")?;
    let pg = &pages[s.page];
    let sp = s.staves[0].sp();
    let (lo, hi) = (
        s.staves[0].top() - 12.0 * sp,
        s.staves.last().unwrap().bottom() + 8.0 * sp,
    );
    let inside = |y: f64| lo <= y && y <= hi;
    let mut out = format!(
        "page {} sp {sp:.2} head size {:.1} staves {:?}\n",
        s.page + 1,
        pg.size,
        s.staves.iter().map(|t| t.top().round()).collect::<Vec<_>>()
    );
    for g in pg.glyphs.iter().filter(|g| inside(g.y)) {
        out.push_str(&format!(
            "glyph {:04X} x {:.1}-{:.1} y {:.1} size {:.1}\n",
            g.code, g.x0, g.x1, g.y, g.size
        ));
    }
    for w in words::words_of(pg).iter().filter(|w| inside(w.base)) {
        out.push_str(&format!(
            "word {:?} x {:.1}-{:.1} base {:.1} size {:.1}\n",
            w.text, w.x0, w.x1, w.base, w.size
        ));
    }
    for l in pg
        .hlines
        .iter()
        .filter(|l| inside(l.y) && l.x1 - l.x0 < 0.07 * pg.width)
    {
        out.push_str(&format!(
            "hline x {:.1}-{:.1} y {:.1} w {:.2}\n",
            l.x0, l.x1, l.y, l.w
        ));
    }
    for l in pg.dashed.iter().filter(|l| inside(l.y)) {
        out.push_str(&format!(
            "dashed x {:.1}-{:.1} y {:.1} w {:.2}\n",
            l.x0, l.x1, l.y, l.w
        ));
    }
    for v in pg.vlines.iter().filter(|v| inside(v.y0)) {
        out.push_str(&format!(
            "vline x {:.1} y {:.1}-{:.1} w {:.2}\n",
            v.x, v.y0, v.y1, v.w
        ));
    }
    for p in pg.polys.iter().filter(|p| p.iter().any(|q| inside(q.1))) {
        let xs = p.iter().map(|q| q.0);
        let ys = p.iter().map(|q| q.1);
        out.push_str(&format!(
            "poly {} pts x {:.1}-{:.1} y {:.1}-{:.1}\n",
            p.len(),
            xs.clone().fold(f64::MAX, f64::min),
            xs.fold(f64::MIN, f64::max),
            ys.clone().fold(f64::MAX, f64::min),
            ys.fold(f64::MIN, f64::max)
        ));
    }
    for c in pg.curves.iter().filter(|c| inside(c.y0)) {
        out.push_str(&format!(
            "curve x {:.1}-{:.1} y {:.1}-{:.1}\n",
            c.x0, c.x1, c.y0, c.y1
        ));
    }
    for l in pg.diagonals.iter().filter(|l| inside(l.1)) {
        out.push_str(&format!(
            "diag ({:.1},{:.1})-({:.1},{:.1}) w {:.2}\n",
            l.0, l.1, l.2, l.3, l.4
        ));
    }
    Ok(out)
}