//! A voice message's player, the core's half (the voice player, 23 Nov 2026, //! `assets/design/chat/voice-player.html`). //! //! ```text //! chat.settings { voiceSpeed?: 1 | 1.5 | 2 } → { …, voiceSpeed } //! chat.waveforms { limit? } → { items: [{ message, index, path }] } //! chat.waveform { items: [{ message, index, waveform }] } → { set } //! ``` //! //! **The speed** is one for every voice message, kept with the person's Comms //! settings and synced: the `face_settings` row keyed [`SETTINGS_ROW`] (a key //! naming no table is a screen of the shell's own, its face kept as said and //! its other columns that screen's settings), column `speed`. A new note, //! another chat, the next launch and the person's other phone all start at the //! last speed chosen. It changes only when the player's pill is tapped. //! //! **The bars** are the core's (`bubble::bars`, 36 heights from the message's //! waveform). The waveform comes with the message: the sender's phone sends //! the recorder's peaks with `chat.act send`. A voice message with none (sent //! by an older phone, or imported) gets its waveform from the first phone that //! holds its file, as old pictures get their previews (`chat_ahead`): //! `chat.waveforms` lists the voice files held here with none, the phone reads //! each file's peaks (at most 64, 0..1) and hands them to `chat.waveform`, //! which writes them into the message's own row once, so every phone of the //! person draws its bars from then on. use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use cotton_core::chat::payload; use super::chat_files::{self, Attached}; use super::cotton_chat::{meta_value, one, read, rows, write, ws, MESSAGES}; use crate::methods::MethodError; use crate::shell::client::ClientController; /// The `face_settings` row Comms keeps its voice speed in. pub const SETTINGS_ROW: &str = "comms"; /// The face the row wears: Comms' look. const FACE: &str = "warm"; /// The speeds the pill goes through, in order, wrapping round. pub const SPEEDS: [f64; 3] = [1.0, 1.5, 2.0]; /// The face choices table and its key column, where this copy keeps one. fn table(client: &ClientController) -> Option<(String, String)> { let mut found = None; client .read_rows("chat.settings", &mut |ctx| { let listed = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?; found = super::catalogue::FaceChoiceTable::of(&listed.definitions).map(|choices| (choices.table, choices.row_key)); Ok(Value::Null) }) .ok()?; found } /// The voice speed as kept: 1 when none is, or when the row holds one this build does not offer. pub(crate) fn speed(client: &ClientController) -> f64 { let Some((table, _)) = table(client) else { return 1.0 }; let row = crate::phone::records::call(client, "records.get", &json!({ "table": table, "id": SETTINGS_ROW })).ok(); row.and_then(|r| r["data"]["speed"].as_f64()).filter(|s| SPEEDS.contains(s)).unwrap_or(1.0) } /// `voiceSpeed` written on the row, synced to the person's other phones. pub(crate) fn set_speed(client: &ClientController, asked: &Value) -> Result { let speed = asked.as_f64().filter(|s| SPEEDS.contains(s)).ok_or_else(|| MethodError::new("invalid_request", "voiceSpeed is 1, 1.5 or 2"))?; if speed == self::speed(client) { return Ok(speed); } let (table, key) = table(client).ok_or_else(|| MethodError::new("unwritable", "this database keeps no settings for Comms"))?; let mut data = Map::new(); data.insert(key, json!(SETTINGS_ROW)); data.insert("face".into(), json!(FACE)); data.insert("speed".into(), json!(speed)); crate::phone::records::call(client, "records.create", &json!({ "table": table, "data": Value::Object(data) }))?; Ok(speed) } const VOICE_ROW: &str = "id, thread_id, media, meta, origin, channel, direction, send_state, sent_at, created_at"; const HAS_FILES: &str = "trashed_at IS NULL AND deleted_at IS NULL AND hidden_at IS NULL AND (meta LIKE '%\"voice\"%' OR (media IS NOT NULL AND media NOT IN ('', '[]')))"; /// Attachments one message carries at most, imports and Cotton files counted. const ATTACHED_MAX: usize = 64; /// Whether attachment `index` of `row` is a voice message with no waveform, and where its file is on this phone. fn wanting(client: &ClientController, row: &Value, index: usize) -> Option { match chat_files::attached(row, index)? { Attached::Imported(media) => { let voice = cotton_core::messages::preview::media_kind_of(&media) == cotton_core::constants::MessageMediaKind::Voice; (voice && media.waveform.as_ref().is_none_or(Vec::is_empty)).then(|| held(client, &media.key)).flatten() } Attached::Cotton(at, picture) => { if picture.kind.as_deref() != Some("voice") || !picture.waveform.is_empty() { return None; } meta_value(&row["meta"])["cotton"]["pictures"][at]["kept"].as_str().and_then(|key| held(client, key)) } Attached::Pending(..) => None, } } /// Whether `key`'s bytes are on this phone now. fn held(client: &ClientController, key: &str) -> Option { let key = key.to_string(); client .with_file(|replica| { let key = super::media::object_key_of(replica.driver, &replica.identity.id().to_string(), key); Ok(super::media::local_path_of(replica.driver, &key)) }) .ok() .flatten() } /// `chat.waveforms`: voice messages whose file is on this phone and that have no waveform yet, newest first. pub(crate) fn waveforms(client: &ClientController, request: &Value) -> Result { let limit = request.get("limit").and_then(Value::as_u64).map_or(20, |n| n.clamp(1, 200) as usize); let found = read(client, "chat.waveforms", |ctx| Ok(Value::Array(rows(ctx, &format!("SELECT {VOICE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND {HAS_FILES} ORDER BY sent_at DESC LIMIT 4000"), &[ws(ctx)])?.into_iter().map(Value::Object).collect())))?; let mut items = Vec::new(); 'rows: for row in found.as_array().into_iter().flatten() { for index in 0..ATTACHED_MAX { if items.len() >= limit { break 'rows; } if chat_files::attached(row, index).is_none() { break; } if let Some(path) = wanting(client, row, index) { items.push(json!({ "message": row["id"], "index": index, "path": path.to_string_lossy() })); } } } Ok(json!({ "items": items })) } /// A waveform as the phone hands it: at most [`payload::WAVEFORM_MAX`] samples in 0..1; anything else is none. fn samples_of(value: &Value) -> Option> { let all = value.as_array()?; let samples: Vec = all.iter().filter_map(Value::as_f64).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0)).collect(); (!samples.is_empty() && samples.len() == all.len() && samples.len() <= payload::WAVEFORM_MAX).then_some(samples) } /// `chat.waveform`: each waveform written into its message's row, once (never over one already there). pub(crate) fn set_waveforms(client: &ClientController, request: &Value) -> Result { let items: Vec<(String, usize, Vec)> = request .get("items") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(|item| Some((item["message"].as_str()?.to_string(), item["index"].as_u64()? as usize, samples_of(&item["waveform"])?))) .take(200) .collect(); write(client, "chat.waveform", move |ctx| { let mut set = 0; for (id, index, samples) in &items { let Some(row) = one(ctx, &format!("SELECT {VOICE_ROW} FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])? else { continue }; let row = Value::Object(row); let mut patch = Map::new(); match chat_files::attached(&row, *index) { Some(Attached::Imported(media)) if media.waveform.as_ref().is_none_or(Vec::is_empty) && cotton_core::messages::preview::media_kind_of(&media) == cotton_core::constants::MessageMediaKind::Voice => { let mut entries: Vec = match &row["media"] { Value::String(t) => serde_json::from_str(t).unwrap_or_default(), Value::Array(a) => a.clone(), _ => continue, }; // The index counts the import's own entries, never the Cotton files kept beside them. let Some(entry) = entries.iter_mut().filter(|e| e["cottonKept"] != json!(true)).nth(*index) else { continue }; entry["waveform"] = json!(samples); patch.insert("media".into(), json!(entries)); } Some(Attached::Cotton(at, picture)) if picture.kind.as_deref() == Some("voice") && picture.waveform.is_empty() => { // Kept as a Cotton file keeps it: 0..255, as the sealed message carries it. let mut meta = meta_value(&row["meta"]); meta["cotton"]["pictures"][at]["waveform"] = json!(samples.iter().map(|v| (v * 255.0).round() as u8).collect::>()); patch.insert("meta".into(), meta); } _ => continue, } cotton_tools::mcp::handlers::common::update_row(ctx, MESSAGES, id, patch).map_err(|f| f.to_string())?; set += 1; } Ok(json!({ "set": set })) }) }