ftts-cli 0.1.7

franken_tts CLI: pure-Rust Qwen3-TTS voice synthesis (`ftts say`), no Python, no GPU
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! `ftts card`: export a voice as a voice card, import a voice card back.
//!
//! A voice card is the interchange picture the iOS app shares: the full 1,024-float
//! x-vector written as `ftts-voicecard`'s self-locating mosaic, plus a lossless
//! private PNG chunk as the byte-exact fast path. Cards made here import on a phone
//! and cards made on a phone import here, through either layer — the mosaic encoder
//! is bit-identical across the two implementations by test.
//!
//! Layout mirrors the app's card (1024×1180: title band, mosaic, name band); the
//! fonts differ (bundled IBM Plex here, the system font there), which is fine — text
//! is for humans, the mosaic and chunk are the data.

use std::path::{Path, PathBuf};

use fmd_font::Font;
use ftts_video::raster::{FontStack, Surface};

use crate::FttsError;
use crate::synth::SPEAKER_VECTOR_BYTES;

/// Card pixel dimensions: the mosaic square plus title and name bands.
const CARD_WIDTH: usize = ftts_voicecard::CARD_SIZE;
const CARD_HEIGHT: usize = ftts_voicecard::CARD_SIZE + 156;
/// The mosaic's y offset: the title band above it.
const MOSAIC_TOP: usize = 72;

/// The lab's palette, matching the app's `Theme.swift`.
const BACKGROUND: [u8; 3] = [2, 10, 6];
const EMERALD: [u8; 3] = [52, 211, 153];
const TEXT_PRIMARY: [u8; 3] = [226, 232, 240];
const TEXT_SECONDARY: [u8; 3] = [148, 163, 184];

/// Render the full card PNG (mosaic, text bands, lossless chunk) for a voice.
///
/// # Errors
///
/// When the vector has the wrong width or the bundled fonts fail to parse.
pub fn render_card_png(name: &str, vector: &[f32]) -> Result<Vec<u8>, FttsError> {
    if vector.len() != ftts_voicecard::VECTOR_WIDTH {
        return Err(FttsError::Input(format!(
            "a voice card carries exactly {} floats, got {}",
            ftts_voicecard::VECTOR_WIDTH,
            vector.len()
        )));
    }
    let mosaic = ftts_voicecard::render_mosaic_pixels(name, vector);

    let mut rgb = vec![0_u8; CARD_WIDTH * CARD_HEIGHT * 3];
    for pixel in rgb.chunks_mut(3) {
        pixel.copy_from_slice(&BACKGROUND);
    }
    for row in 0..ftts_voicecard::CARD_SIZE {
        let source = row * ftts_voicecard::CARD_SIZE * 3;
        let target = (MOSAIC_TOP + row) * CARD_WIDTH * 3;
        rgb[target..target + ftts_voicecard::CARD_SIZE * 3]
            .copy_from_slice(&mosaic[source..source + ftts_voicecard::CARD_SIZE * 3]);
    }

    // Text bands via the video renderer's font stack (drawn onto an RGBA surface,
    // then alpha-blended onto the card).
    let plex_bold = Font::parse(fmd_font::bundled::PLEX_BOLD.to_vec())
        .map_err(|error| FttsError::Generic(format!("bundled font failed to parse: {error:?}")))?;
    let plex_regular = Font::parse(fmd_font::bundled::PLEX_REGULAR.to_vec())
        .map_err(|error| FttsError::Generic(format!("bundled font failed to parse: {error:?}")))?;
    let bold = FontStack {
        faces: vec![&plex_bold],
    };
    let regular = FontStack {
        faces: vec![&plex_regular],
    };
    let mut text_layer = Surface::new(CARD_WIDTH, CARD_HEIGHT);

    let title = "F R A N K E N T T S · V O I C E  C A R D";
    let title_width = bold.measure(title, 26.0);
    bold.draw(
        &mut text_layer,
        title,
        (CARD_WIDTH as f64 - title_width) / 2.0,
        48.0,
        26.0,
        EMERALD,
        1.0,
    );
    let name_width = bold.measure(name, 42.0);
    bold.draw(
        &mut text_layer,
        name,
        (CARD_WIDTH as f64 - name_width) / 2.0,
        (MOSAIC_TOP + ftts_voicecard::CARD_SIZE + 44) as f64,
        42.0,
        TEXT_PRIMARY,
        1.0,
    );
    let tagline = "the green mosaic is the voice · add it from a photo in FrankenTTS";
    let tagline_width = regular.measure(tagline, 20.0);
    regular.draw(
        &mut text_layer,
        tagline,
        (CARD_WIDTH as f64 - tagline_width) / 2.0,
        (MOSAIC_TOP + ftts_voicecard::CARD_SIZE + 76) as f64,
        20.0,
        TEXT_SECONDARY,
        1.0,
    );
    for (pixel, over) in rgb.chunks_mut(3).zip(text_layer.rgba.chunks(4)) {
        if over[3] == 0 {
            continue;
        }
        let alpha = f32::from(over[3]) / 255.0;
        for c in 0..3 {
            let base = f32::from(pixel[c]);
            pixel[c] = (f32::from(over[c]) * alpha + base * (1.0 - alpha))
                .round()
                .clamp(0.0, 255.0) as u8;
        }
    }

    let png = encode_png(&rgb, CARD_WIDTH, CARD_HEIGHT)?;
    ftts_voicecard::embed_chunk(name, vector, &png)
        .ok_or_else(|| FttsError::Generic("card PNG lost its structure".to_owned()))
}

/// Decode a voice from card image bytes: lossless chunk first, then the mosaic.
/// Accepts PNG and JPEG, the formats phones share.
///
/// # Errors
///
/// When the file is neither, or carries no intact voice.
pub fn decode_card(bytes: &[u8]) -> Result<(String, Vec<f32>), FttsError> {
    if let Some(found) = ftts_voicecard::decode_chunk(bytes) {
        return Ok(found);
    }
    let (rgb, width, height) = decode_image_rgb(bytes)?;
    if let Some(found) = ftts_voicecard::decode(&rgb, width, height) {
        return Ok(found);
    }
    // Rotation retry: the phone bakes EXIF orientation into pixels before decoding,
    // but zune-jpeg does not apply the EXIF flag, so a card that traveled through a
    // rotation-tagging pipeline arrives sideways here. Three quarter-turns cover
    // every axis-aligned case; each retry costs one decode pass, failure path only.
    let mut turned = rgb;
    let (mut turned_width, mut turned_height) = (width, height);
    for _ in 0..3 {
        (turned, turned_width, turned_height) =
            rotate_quarter_turn(&turned, turned_width, turned_height);
        if let Some(found) = ftts_voicecard::decode(&turned, turned_width, turned_height) {
            return Ok(found);
        }
    }
    Err(FttsError::Input(
        "no voice found in that picture; voice cards must arrive uncropped (screenshots \
         and messaging-app recompression are fine)"
            .to_owned(),
    ))
}

/// Rotate an RGB24 image 90° clockwise.
fn rotate_quarter_turn(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, usize, usize) {
    let mut out = vec![0_u8; rgb.len()];
    for y in 0..height {
        for x in 0..width {
            let source = (y * width + x) * 3;
            let target = (x * height + (height - 1 - y)) * 3;
            out[target..target + 3].copy_from_slice(&rgb[source..source + 3]);
        }
    }
    (out, height, width)
}

/// Read a `.spk` speaker vector file.
///
/// # Errors
///
/// When the file is missing, the wrong size, or carries non-finite values.
pub fn read_spk(path: &Path) -> Result<Vec<f32>, FttsError> {
    let bytes = std::fs::read(path).map_err(|error| {
        FttsError::Input(format!(
            "cannot read voice file {}: {error}",
            path.display()
        ))
    })?;
    if bytes.len() != SPEAKER_VECTOR_BYTES {
        return Err(FttsError::Input(format!(
            "{} is {} bytes; a speaker vector is exactly {SPEAKER_VECTOR_BYTES}",
            path.display(),
            bytes.len()
        )));
    }
    let vector: Vec<f32> = bytes
        .as_chunks::<4>()
        .0
        .iter()
        .map(|chunk| f32::from_le_bytes(*chunk))
        .collect();
    if vector.iter().any(|value| !value.is_finite()) {
        return Err(FttsError::Input(format!(
            "{} carries non-finite values; it is not a usable speaker vector",
            path.display()
        )));
    }
    Ok(vector)
}

/// Write an imported vector as a `.spk` file.
///
/// # Errors
///
/// When the file cannot be written.
pub fn write_spk(path: &Path, vector: &[f32]) -> Result<(), FttsError> {
    let mut bytes = Vec::with_capacity(vector.len() * 4);
    for value in vector {
        bytes.extend_from_slice(&value.to_le_bytes());
    }
    std::fs::write(path, bytes)
        .map_err(|error| FttsError::Generic(format!("cannot write {}: {error}", path.display())))
}

/// A filesystem-safe name for default output paths.
#[must_use]
pub fn safe_file_stem(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|ch| if ch.is_alphanumeric() { ch } else { '-' })
        .collect();
    let trimmed = cleaned.trim_matches('-');
    if trimmed.is_empty() {
        "voice".to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// Default output path for an imported voice, next to the card.
#[must_use]
pub fn default_import_path(card: &Path, name: &str) -> PathBuf {
    card.with_file_name(format!("{}.spk", safe_file_stem(name)))
}

// ------------------------------------------------------------------------ image I/O

fn encode_png(rgb: &[u8], width: usize, height: usize) -> Result<Vec<u8>, FttsError> {
    let mut out = Vec::new();
    {
        let mut encoder = png::Encoder::new(&mut out, width as u32, height as u32);
        encoder.set_color(png::ColorType::Rgb);
        encoder.set_depth(png::BitDepth::Eight);
        let mut writer = encoder
            .write_header()
            .map_err(|error| FttsError::Generic(format!("PNG header: {error}")))?;
        writer
            .write_image_data(rgb)
            .map_err(|error| FttsError::Generic(format!("PNG data: {error}")))?;
    }
    Ok(out)
}

fn decode_image_rgb(bytes: &[u8]) -> Result<(Vec<u8>, usize, usize), FttsError> {
    const PNG_SIGNATURE: [u8; 8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
    if bytes.len() >= 8 && bytes[..8] == PNG_SIGNATURE {
        return decode_png_rgb(bytes);
    }
    if bytes.len() >= 3 && bytes[..3] == [0xFF, 0xD8, 0xFF] {
        return decode_jpeg_rgb(bytes);
    }
    Err(FttsError::Input(
        "that file is neither PNG nor JPEG; share the card picture itself".to_owned(),
    ))
}

/// Bound the work BEFORE pixel buffers are allocated: the mosaic is unreadable below
/// ~2 px/cell anyway, and an arbitrary 100-megapixel input would otherwise cost
/// hundreds of MB. The phone applies the same kind of cap (24 MP, downscaling);
/// here refusal with a named reason beats a silent giant allocation.
fn refuse_oversized(width: usize, height: usize) -> Result<(), FttsError> {
    if width.saturating_mul(height) > 40_000_000 {
        return Err(FttsError::Input(format!(
            "{width}x{height} is larger than any voice card; export or screenshot the \
             card itself rather than a scan"
        )));
    }
    Ok(())
}

fn decode_png_rgb(bytes: &[u8]) -> Result<(Vec<u8>, usize, usize), FttsError> {
    let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
    let mut reader = decoder
        .read_info()
        .map_err(|error| FttsError::Input(format!("unreadable PNG: {error}")))?;
    let header = reader.info();
    refuse_oversized(header.width as usize, header.height as usize)?;
    let mut buffer = vec![0_u8; reader.output_buffer_size().unwrap_or_default()];
    let info = reader
        .next_frame(&mut buffer)
        .map_err(|error| FttsError::Input(format!("unreadable PNG: {error}")))?;
    buffer.truncate(info.buffer_size());
    let width = info.width as usize;
    let height = info.height as usize;
    // Depth first: the channel unpacking below assumes one byte per sample, and
    // 16-bit input must be refused before it can be misread as two 8-bit samples.
    if info.bit_depth != png::BitDepth::Eight {
        return Err(FttsError::Input(
            "only 8-bit images are supported; re-save the card as a normal screenshot".to_owned(),
        ));
    }
    let rgb = match info.color_type {
        png::ColorType::Rgb => buffer,
        png::ColorType::Rgba => buffer
            .as_chunks::<4>()
            .0
            .iter()
            .flat_map(|px| [px[0], px[1], px[2]])
            .collect(),
        png::ColorType::Grayscale => buffer.iter().flat_map(|&g| [g, g, g]).collect(),
        png::ColorType::GrayscaleAlpha => buffer
            .as_chunks::<2>()
            .0
            .iter()
            .flat_map(|px| [px[0], px[0], px[0]])
            .collect(),
        png::ColorType::Indexed => {
            return Err(FttsError::Input(
                "indexed-color PNG; re-export the card as a normal screenshot".to_owned(),
            ));
        }
    };
    Ok((rgb, width, height))
}

fn decode_jpeg_rgb(bytes: &[u8]) -> Result<(Vec<u8>, usize, usize), FttsError> {
    use zune_jpeg::JpegDecoder;
    use zune_jpeg::zune_core::colorspace::ColorSpace;
    use zune_jpeg::zune_core::options::DecoderOptions;

    let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGB);
    let mut decoder = JpegDecoder::new_with_options(
        zune_jpeg::zune_core::bytestream::ZCursor::new(bytes),
        options,
    );
    decoder
        .decode_headers()
        .map_err(|error| FttsError::Input(format!("unreadable JPEG: {error}")))?;
    let (width, height) = decoder
        .dimensions()
        .ok_or_else(|| FttsError::Input("JPEG carries no dimensions".to_owned()))?;
    refuse_oversized(width, height)?;
    let rgb = decoder
        .decode()
        .map_err(|error| FttsError::Input(format!("unreadable JPEG: {error}")))?;
    Ok((rgb, width, height))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_vector() -> Vec<f32> {
        let mut state: u64 = 0xBEEF_CAFE_1234_5678;
        (0..ftts_voicecard::VECTOR_WIDTH)
            .map(|_| {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                ((state >> 40) as f64 / f64::from(1 << 24) - 0.5) as f32 * 2.0
            })
            .collect()
    }

    #[test]
    fn a_rendered_card_imports_through_both_layers() {
        let vector = test_vector();
        let png = render_card_png("Round Trip", &vector).expect("render");

        // Chunk fast path on the raw bytes.
        let (name, decoded) = decode_card(&png).expect("chunk import");
        assert_eq!(name, "Round Trip");
        assert_eq!(decoded, vector);

        // Pixel path: strip the private chunk by re-encoding the decoded image,
        // which is what a screenshot or a messaging app effectively does.
        let (rgb, width, height) = decode_image_rgb(&png).expect("decode image");
        let stripped = encode_png(&rgb, width, height).expect("re-encode");
        let (name, decoded) = decode_card(&stripped).expect("pixel import");
        assert_eq!(name, "Round Trip");
        assert_eq!(decoded, vector);
    }

    #[test]
    fn a_sideways_card_still_imports() {
        // zune-jpeg ignores the EXIF orientation flag, so a card that traveled
        // through a rotation-tagging pipeline arrives with its pixels turned;
        // the retry must recover all three quarter-turn cases.
        let vector = test_vector();
        let png = render_card_png("Turned", &vector).expect("render");
        let (rgb, width, height) = decode_image_rgb(&png).expect("decode");
        let mut turned = rgb;
        let (mut turned_width, mut turned_height) = (width, height);
        for turn in 1..=3 {
            (turned, turned_width, turned_height) =
                rotate_quarter_turn(&turned, turned_width, turned_height);
            let stripped = encode_png(&turned, turned_width, turned_height).expect("re-encode");
            let (name, decoded) = decode_card(&stripped)
                .unwrap_or_else(|error| panic!("turn {turn} failed: {error}"));
            assert_eq!(name, "Turned");
            assert_eq!(decoded, vector);
        }
    }

    #[test]
    fn an_oversized_image_is_refused_before_decoding() {
        // A 41-megapixel PNG header must be refused by dimensions alone; encoding
        // a real one would be slow, so build a tiny header-only lie via the
        // encoder path with small data — instead, verify the guard directly.
        assert!(refuse_oversized(6_500, 6_500).is_err());
        assert!(refuse_oversized(1_024, 1_180).is_ok());
    }

    #[test]
    fn an_unrelated_image_is_refused_by_name() {
        let flat = vec![128_u8; 300 * 200 * 3];
        let png = encode_png(&flat, 300, 200).expect("encode");
        let error = decode_card(&png).expect_err("no voice in a flat image");
        assert!(error.to_string().contains("no voice found"));
    }
}