Skip to main content

fm_vector/
lib.rs

1//! A notation program's PDF read from its vectors (docs/pdf-import.md).
2//!
3//! A PDF that MuseScore, Dorico, Sibelius or Finale wrote holds its music as the engraver set it:
4//! every notehead, rest, clef, accidental, flag and dot a glyph of a SMuFL music font at its exact
5//! place, every staff line, stem, barline and beam a drawn line or shape, and the words as text.
6//! Read from there, a notehead's pitch is its place on the staff and a note's length its head,
7//! flags or beams and dots: nothing is guessed from a picture, and nothing needs a model or a
8//! server, so it runs in the browser.
9//!
10//! [`read_pdf`] finds the systems (staves a line joins), the parts (staves the barlines join are a
11//! piano's; a staff with words under it a voice), and reads system after system into `.fmn`
12//! (docs/transcribing.md), compiling each after the ones before it with [`fm_transcribe`]: what
13//! comes out always opens. It takes notes and chords in up to two voices a staff (rests a program
14//! hid are filled in), rests, dots, ties, slurs, accidentals (cautionary ones too), key, time and
15//! clef changes (inside a system too), a pickup, dynamics, fermatas, the common articulations and
16//! ornaments, tuplets, grace and cue notes, tremolos, fingering, glissandos, cross-staff notes, the
17//! barlines (double, final, repeats), endings, the segno and coda, To Coda, Fine, D.S. and D.C.,
18//! printed beams that differ from the beat, and the words of each voice, hyphens and held
19//! syllables included; and over and under the staves (`marks.rs`) hairpins, words, a tempo and
20//! its metronome mark, rehearsal marks, chord symbols, the pedal and ottava lines. The music
21//! fonts before SMuFL (Sibelius's, Finale's, capella's, Doremi) are read as SMuFL (`legacy.rs`),
22//! as are LilyPond's, by its glyphs' names (`lilypond.rs`), and MuseScore's old one (`mscore.rs`).
23//! A staff's bar it cannot time (two voices that do not add up however its rests are given out),
24//! or whose notes do not stand where the other staves' say they start (`columns.rs`), is left as
25//! a bar's rest and listed, saying where and why; a scan, or a PDF in a music font it does not
26//! know, is refused.
27
28mod audit;
29mod between;
30mod choir;
31mod columns;
32mod cues;
33mod dashes;
34mod dotways;
35mod doubt;
36mod frac;
37mod judge;
38mod jumps;
39mod key;
40mod layout;
41mod legacy;
42mod lilypond;
43mod longbars;
44mod lyrics;
45mod marks;
46mod mscore;
47#[doc(hidden)]
48pub mod names;
49mod options;
50mod page;
51mod passing;
52mod pictures;
53mod read;
54mod repeats;
55mod review;
56mod shapes;
57mod shown;
58mod smufl;
59mod spacing;
60mod staff;
61mod stems;
62mod svg;
63mod ties;
64mod times;
65mod tuplets;
66mod unison;
67mod words;
68mod write;
69
70pub use audit::{audit_pdf, Audit, BarAudit, SystemAudit};
71#[doc(hidden)]
72pub use page::Picture;
73#[doc(hidden)]
74pub use pictures::{shape as picture_shape, Shape as PictureShape};
75pub use read::{Place, Reading, Refusal, Unread};
76pub use review::{
77    bar_text_json, read_pdf_review, reading_json, BarPlace, BarText, Choice, NoteMark, Question,
78    Review,
79};
80pub use svg::page_svg;
81
82/// A page's staff space, its staves' lines and the images it draws (`pictures_of`).
83#[doc(hidden)]
84pub type PicturePage = (f64, Vec<[f64; 5]>, Vec<Picture>);
85
86/// The images each page of a PDF draws, as their ink, with the page's staff space (its staves'
87/// median; 0 for a page with none) and its staves' lines, for the `pictures` example.
88#[doc(hidden)]
89pub fn pictures_of(bytes: &[u8]) -> Result<Vec<PicturePage>, String> {
90    Ok(page::read_pages(bytes)?
91        .into_iter()
92        .map(|p| {
93            let staves = p.staves();
94            let mut sps: Vec<f64> = staves.iter().map(|s| s.sp()).collect();
95            sps.sort_by(f64::total_cmp);
96            let sp = sps.get(sps.len() / 2).copied().unwrap_or(0.0);
97            (sp, staves.iter().map(|s| s.lines).collect(), p.pictures)
98        })
99        .collect())
100}
101
102/// Read a PDF's bytes into a score, or say why it cannot be read. A staff's bar it cannot read
103/// is left as a bar's rest and listed in [`Reading::unread`], while those are no more than an
104/// eighth of the staves' bars; past that the PDF is refused for the first of them.
105/// ```no_run
106/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
107/// let reading = fm_vector::read_pdf(&std::fs::read("score.pdf")?)?;
108/// std::fs::write("score.musicxml", reading.musicxml)?;
109/// # Ok(())
110/// # }
111/// ```
112pub fn read_pdf(bytes: &[u8]) -> Result<Reading, Refusal> {
113    read_pdf_leaving(bytes, 0.125)
114}
115
116/// [`read_pdf`], leaving up to `max_unread` of the staves' bars unread (0: none; 1: any number).
117pub fn read_pdf_leaving(bytes: &[u8], max_unread: f64) -> Result<Reading, Refusal> {
118    let pages = page::read_pages(bytes).map_err(|why| Refusal { system: None, why })?;
119    read::read(&pages, max_unread)
120}
121
122/// Whether a PDF looks like a notation program's own: music-font glyphs on its pages, as text.
123/// Cheap next to [`read_pdf`]; a scan has none.
124pub fn is_engraved(bytes: &[u8]) -> bool {
125    page::read_pages(bytes)
126        .map(|pages| {
127            pages.iter().any(|p| {
128                p.glyphs
129                    .iter()
130                    .filter(|g| smufl::head(g.code).is_some())
131                    .count()
132                    > 10
133            })
134        })
135        .unwrap_or(false)
136}
137
138/// The layout found, in words: each system's page and staves, and the parts (for looking into a
139/// refusal).
140pub fn describe_layout(bytes: &[u8]) -> Result<String, String> {
141    let pages = page::read_pages(bytes)?;
142    let systems = layout::systems(&pages);
143    let mut out = String::new();
144    for (i, s) in systems.iter().enumerate() {
145        let tops: Vec<String> = s
146            .staves
147            .iter()
148            .map(|st| format!("{:.0}", st.top()))
149            .collect();
150        out.push_str(&format!(
151            "system {} page {}: staves at {}\n",
152            i + 1,
153            s.page + 1,
154            tops.join(" ")
155        ));
156    }
157    for p in layout::parts(&pages, &systems) {
158        out.push_str(&format!("part {} {:?} {:?}\n", p.id, p.name, p.kind));
159    }
160    for (pi, p) in pages.iter().enumerate() {
161        let braces = p
162            .glyphs
163            .iter()
164            .filter(|g| (0xE000..=0xE003).contains(&g.code))
165            .count();
166        out.push_str(&format!(
167            "page {}: {} music glyphs, {} braces/brackets as glyphs, {} vertical lines\n",
168            pi + 1,
169            p.glyphs.len(),
170            braces,
171            p.vlines.len()
172        ));
173    }
174    Ok(out)
175}
176
177/// Everything drawn over one system (1-based), for looking into a refusal: the music glyphs, the
178/// words, and the short lines, shapes and curves, by place.
179#[doc(hidden)]
180pub fn dump_system(bytes: &[u8], system: usize) -> Result<String, String> {
181    let pages = page::read_pages(bytes)?;
182    let systems = layout::systems(&pages);
183    let s = systems
184        .get(system.wrapping_sub(1))
185        .ok_or("no such system")?;
186    let pg = &pages[s.page];
187    let sp = s.staves[0].sp();
188    let (lo, hi) = (
189        s.staves[0].top() - 12.0 * sp,
190        s.staves.last().unwrap().bottom() + 8.0 * sp,
191    );
192    let inside = |y: f64| lo <= y && y <= hi;
193    let mut out = format!(
194        "page {} sp {sp:.2} head size {:.1} staves {:?}\n",
195        s.page + 1,
196        pg.size,
197        s.staves.iter().map(|t| t.top().round()).collect::<Vec<_>>()
198    );
199    for g in pg.glyphs.iter().filter(|g| inside(g.y)) {
200        out.push_str(&format!(
201            "glyph {:04X} x {:.1}-{:.1} y {:.1} size {:.1}\n",
202            g.code, g.x0, g.x1, g.y, g.size
203        ));
204    }
205    for w in words::words_of(pg).iter().filter(|w| inside(w.base)) {
206        out.push_str(&format!(
207            "word {:?} x {:.1}-{:.1} base {:.1} size {:.1}\n",
208            w.text, w.x0, w.x1, w.base, w.size
209        ));
210    }
211    for l in pg
212        .hlines
213        .iter()
214        .filter(|l| inside(l.y) && l.x1 - l.x0 < 0.07 * pg.width)
215    {
216        out.push_str(&format!(
217            "hline x {:.1}-{:.1} y {:.1} w {:.2}\n",
218            l.x0, l.x1, l.y, l.w
219        ));
220    }
221    for l in pg.dashed.iter().filter(|l| inside(l.y)) {
222        out.push_str(&format!(
223            "dashed x {:.1}-{:.1} y {:.1} w {:.2}\n",
224            l.x0, l.x1, l.y, l.w
225        ));
226    }
227    for v in pg.vlines.iter().filter(|v| inside(v.y0)) {
228        out.push_str(&format!(
229            "vline x {:.1} y {:.1}-{:.1} w {:.2}\n",
230            v.x, v.y0, v.y1, v.w
231        ));
232    }
233    for p in pg.polys.iter().filter(|p| p.iter().any(|q| inside(q.1))) {
234        let xs = p.iter().map(|q| q.0);
235        let ys = p.iter().map(|q| q.1);
236        out.push_str(&format!(
237            "poly {} pts x {:.1}-{:.1} y {:.1}-{:.1}\n",
238            p.len(),
239            xs.clone().fold(f64::MAX, f64::min),
240            xs.fold(f64::MIN, f64::max),
241            ys.clone().fold(f64::MAX, f64::min),
242            ys.fold(f64::MIN, f64::max)
243        ));
244    }
245    for c in pg.curves.iter().filter(|c| inside(c.y0)) {
246        out.push_str(&format!(
247            "curve x {:.1}-{:.1} y {:.1}-{:.1}\n",
248            c.x0, c.x1, c.y0, c.y1
249        ));
250    }
251    for l in pg.diagonals.iter().filter(|l| inside(l.1)) {
252        out.push_str(&format!(
253            "diag ({:.1},{:.1})-({:.1},{:.1}) w {:.2}\n",
254            l.0, l.1, l.2, l.3, l.4
255        ));
256    }
257    Ok(out)
258}