//! Calls: video and voice with a contact, peer to peer and end-to-end //! encrypted through the p2p service, with Pinnacle's own codecs; and an //! ordinary phone call through the `phone` service when the contact //! cannot be reached that way, or to a number typed in. //! //! Signalling is a payload of kind CALL (ring, ringing, answer, hang up, //! busy; a ring followed by `call::VOICE` is a call without video); //! media a payload of kind MEDIA: a byte for video (1) or audio (2), then //! the codec's packet. On QEMU there is no camera or microphone: a moving //! test picture and a tone stand in for them; a device's come with its //! drivers. In a call the microphone can be muted and the camera turned //! off: nothing of it is sent then, and the other side shows the caller's //! mark where the video stops coming. //! //! The fallback: a call rings the contact peer to peer first. Their p2p //! service answers a ring with RINGING at once; when none comes within //! [`FALLBACK_MS`], or the p2p service says the DHT does not find them, //! the ring is taken back and the contact's phone number is dialled. A //! person with a number and no Pinnacle is called by phone straight away. //! A phone call's sound goes through the modem, not this app. //! //! Every call is kept in the app's folder ([`RECENTS`]): who, which way, //! how (video, voice, phone), when, and whether it was answered and for //! how long. A call missed is a notification too. A ring that comes during //! another call is answered BUSY and kept as missed. //! //! Started with argument 1, the app answers the ring the p2p service //! holds; with 2, the phone call ringing in at the phone service. #![no_std] #![no_main] extern crate alloc; use alloc::string::String; use alloc::vec::Vec; use pinnacle_gfx::{Canvas, Color, Rect}; use pinnacle_locale::{Date, t, tf}; use pinnacle_media::{adpcm, video}; use pinnacle_modem::number; use pinnacle_rt::Channel; use pinnacle_rt::audio::{Player, Recorder}; use pinnacle_rt::fs; use pinnacle_rt::locale::Zone; use pinnacle_ui::layout::calls::video_scale; use pinnacle_ui::p2p::{self, Client, Key}; use pinnacle_ui::phone::{self, Ended, Said}; use pinnacle_ui::{App, Event, theme}; use pinnacle_view::{IntoView, SCALE, Screen, Signal, View, el, signal}; const W: usize = 240; const H: usize = 320; const QUALITY: u8 = 8; const FRAME_MS: u64 = 100; const KEY_EVERY: u32 = 20; const VIDEO: u8 = 1; const AUDIO: u8 = 2; /// Tones at 16 kHz, as cos and sin of their angle per sample: the stand-in /// microphone's 442 Hz, and the ringtone's 660 Hz. const STAND_IN: (f32, f32) = (0.985, 0.173); const RING: (f32, f32) = (0.966_601, 0.256_292); /// The ringtone: a burst this long, this often. const RING_BURST: usize = 4800; const RING_EVERY_MS: u64 = 1500; /// How long a ring peer to peer waits to be heard before the contact's /// number is called instead. A device that is up answers within a round /// trip; one the DHT has an old address for is found anew within the /// p2p service's lookup (4 s) and a retry. const FALLBACK_MS: u64 = 8000; /// How long how a call ended stays on the screen. const ENDED_MS: u64 = 2500; /// No video from the other side for this long: their camera is off, and /// their mark is shown instead of the last frame. const STALE_MS: u64 = 1000; /// The calls kept, a line each, newest first: the time (seconds since /// 1970, 0 when the device did not know it), `1` outgoing or `0`, how it /// went (`a`nswered, `m`issed, `d`eclined, `n`o answer), seconds talked, /// `o`nline or by `p`hone, `1` voice only or `0`, the contact's key in /// hex or `-`, the number or `-`, and the name; separated by tabs. const RECENTS: &str = "app:recents"; /// How many calls are kept, and how many the first page lists. const RECENTS_KEPT: usize = 100; const RECENTS_SHOWN: usize = 12; /// Someone to call: their Pinnacle (if they have one) and their numbers. #[derive(Clone)] struct Person { name: String, key: Option, phones: Vec, } impl Person { /// Someone known only by the number that calls. fn stranger(number: &str) -> Person { Person { name: if number.is_empty() { t("Unknown number").into() } else { number.into() }, key: None, phones: alloc::vec![number.into()], } } } /// How a call goes. #[derive(Clone, Copy, PartialEq, Eq)] enum Via { /// Peer to peer, video and voice. Online, /// An ordinary phone call through the modem. Phone, } /// How a call went, as the recents keep it. #[derive(Clone, Copy, PartialEq, Eq)] enum Outcome { Answered, /// Rang in and was not answered. Missed, /// Rang in and was declined here. Declined, /// Went out and was not answered: declined there, busy, unreachable, /// or taken back here. NoAnswer, } impl Outcome { fn letter(self) -> char { match self { Outcome::Answered => 'a', Outcome::Missed => 'm', Outcome::Declined => 'd', Outcome::NoAnswer => 'n', } } fn from_letter(c: &str) -> Option { Some(match c { "a" => Outcome::Answered, "m" => Outcome::Missed, "d" => Outcome::Declined, "n" => Outcome::NoAnswer, _ => return None, }) } } /// A call that was, as [`RECENTS`] keeps it. #[derive(Clone)] struct Recent { at: u64, name: String, key: Option, number: String, outgoing: bool, via: Via, voice: bool, outcome: Outcome, secs: u64, } fn hex(key: &Key) -> String { key.iter().map(|b| alloc::format!("{b:02x}")).collect() } fn unhex(s: &str) -> Option { let mut key = [0u8; 32]; if s.len() != 64 { return None; } for (i, b) in key.iter_mut().enumerate() { *b = u8::from_str_radix(s.get(i * 2..i * 2 + 2)?, 16).ok()?; } Some(key) } impl Recent { fn line(&self) -> String { let clean = |s: &str| -> String { s.replace(['\t', '\n'], " ") }; alloc::format!( "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", self.at, u8::from(self.outgoing), self.outcome.letter(), self.secs, if self.via == Via::Phone { 'p' } else { 'o' }, u8::from(self.voice), self.key.as_ref().map_or_else(|| "-".into(), hex), if self.number.is_empty() { "-".into() } else { clean(&self.number) }, clean(&self.name), ) } fn parse(line: &str) -> Option { let mut f = line.split('\t'); Some(Recent { at: f.next()?.parse().ok()?, outgoing: f.next()? == "1", outcome: Outcome::from_letter(f.next()?)?, secs: f.next()?.parse().ok()?, via: if f.next()? == "p" { Via::Phone } else { Via::Online }, voice: f.next()? == "1", key: unhex(f.next()?), number: match f.next()? { "-" => String::new(), n => n.into(), }, name: f.next()?.into(), }) } } /// The calls kept, newest first. fn read_recents() -> Vec { fs::read_string(RECENTS) .map(|s| s.lines().filter_map(Recent::parse).collect()) .unwrap_or_default() } /// What is kept of the calls, and the display server's channel a missed /// call is told through. struct Log { recents: Vec, display: Option, /// Calls missed since the recent calls were last shown. unseen: usize, } impl Log { /// Keeps the call that ended with `person`; a missed one is told as a /// notification too. fn keep(&mut self, person: &Person, outgoing: bool, via: Via, voice: bool, outcome: Outcome, secs: u64) { let recent = Recent { at: pinnacle_rt::clock(), name: person.name.clone(), key: person.key, number: person.phones.first().cloned().unwrap_or_default(), outgoing, via, voice, outcome, secs, }; if outcome == Outcome::Missed { self.unseen += 1; pinnacle_rt::println!("calls: missed a call from {}", person.name); if self.display.is_none() { self.display = pinnacle_rt::connect("display"); } if let Some(display) = &self.display { pinnacle_ui::notify(display, "calls", t("Missed call"), &person.name); } } self.recents.insert(0, recent); self.recents.truncate(RECENTS_KEPT); self.save(); } fn save(&self) { let text: String = self.recents.iter().map(Recent::line).collect(); if !fs::write(RECENTS, text.as_bytes()) { pinnacle_rt::println!("calls: could not keep the recent calls"); } } } enum State { Idle, Ringing { person: Person, outgoing: bool, via: Via, voice: bool, /// When the ring went out peer to peer, and whether it was heard. since: u64, heard: bool, }, InCall { person: Person, outgoing: bool, via: Via, voice: bool, since: u64, }, /// How the last call ended, shown until `until`. Ended { text: &'static str, until: u64, }, } /// Ends the call `state` holds, keeping it as `outcome` (one answered with /// how long it lasted), and says `text` for a moment, or nothing when it /// is empty. fn end(state: &mut State, log: &mut Log, outcome: Outcome, text: &'static str) { match state { State::Ringing { person, outgoing, via, voice, .. } => log.keep(person, *outgoing, *via, *voice, outcome, 0), State::InCall { person, outgoing, via, voice, since, } => { let secs = (pinnacle_rt::time() - *since) / 1000; pinnacle_rt::println!("calls: the call with {} ended after {secs} s", person.name); log.keep(person, *outgoing, *via, *voice, Outcome::Answered, secs); } _ => {} } *state = if text.is_empty() { State::Idle } else { State::Ended { text, until: pinnacle_rt::time() + ENDED_MS, } }; } /// What the phone service says of a call that ended, in the person's /// language. fn ended_text(ended: Ended) -> &'static str { match ended { Ended::HungUp => t("Call ended"), Ended::Busy => t("Busy"), Ended::NoAnswer => t("No answer"), Ended::Missed => t("Missed call"), Ended::Failed => t("The call did not go through"), } } /// The stand-in camera: a gradient with a ball moving across it and the /// caller's initial, drawn with gfx. fn camera(t: u64, initial: &str, pixels: &mut [u32]) { let mut canvas = Canvas::new(pixels, W as u32, H as u32); for y in 0..H as i32 { let shade = (40 + y * 80 / H as i32) as u8; canvas.fill_rect( Rect::new(0, y, W as i32, 1), Color::rgb(shade / 2, shade, shade + 40), ); } let x = (t / 20 % 400) as i32; let x = if x > 200 { 400 - x } else { x } + 20; canvas.fill_circle(x, 120, 28, Color::rgb(0xe6, 0xb4, 0x2e)); canvas.text_centered( theme::huge(), Rect::new(0, 170, W as i32, 120), initial, theme::TEXT, ); } /// `n` samples of a tone, turning `phase` by `step` (cos, sin) a sample. fn tone(phase: &mut (f32, f32), step: (f32, f32), n: usize) -> Vec { (0..n) .map(|_| { let (c, s) = *phase; *phase = (c * step.0 - s * step.1, c * step.1 + s * step.0); c as i16 }) .collect() } /// Everyone in the address book that can be called: by their Pinnacle, /// their number, or both. fn people_of(client: &Client, pending: &mut Vec<(Key, Vec)>) -> Vec { client .book(pending) .into_iter() .filter(|e| e.key.is_some() || !e.phones.is_empty()) .map(|e| Person { name: e.name, key: e.key, phones: e.phones, }) .collect() } /// The person a number belongs to, or a stranger with it. fn by_number(people: &[Person], n: &str) -> Person { people .iter() .find(|p| p.phones.iter().any(|q| number::same(q, n))) .cloned() .unwrap_or_else(|| Person::stranger(n)) } /// Whom a recent call was with, as the address book has them now. fn person_of(people: &[Person], r: &Recent) -> Person { if let Some(p) = r.key.and_then(|k| people.iter().find(|p| p.key == Some(k))) { return p.clone(); } if !r.number.is_empty() { return by_number(people, &r.number); } Person { name: r.name.clone(), key: r.key, phones: Vec::new(), } } /// Whether a ring's payload asks for a call without video. fn voice_only(payload: &[u8]) -> bool { payload.get(2) == Some(&p2p::call::VOICE) } /// How it says where its named controls are (`Screen::announce`), for /// `cargo xtask` to tap them. const ANNOUNCE: &str = "calls: button "; /// What a tap asked for. #[derive(Clone, Copy, PartialEq)] enum Tap { /// A person, with video or voice only. Call(usize, bool), /// A recent call, made again. Again(usize), /// The number typed in. Dial, ClearRecents, /// The recent calls' tab (true) or the people's. Tab(bool), Answer, Decline, End, Mute, Camera, } /// Takes what a signal holds, leaving it empty. fn take(s: &Signal>) -> Option { let v = s.get_untracked(); if v.is_some() { s.set(None); } v } fn css_color(c: Color) -> String { alloc::format!("#{:06x}", c.0 & 0xff_ffff) } /// "05:07": minutes and seconds. fn duration(secs: u64) -> String { alloc::format!("{:02}:{:02}", secs / 60, secs % 60) } /// When a recent call was, from today's point of view: the time today, /// "Yesterday" and the time, or the date and the time. fn when(at: u64, zone: &Zone) -> String { if at == 0 { return String::new(); } let (then, _) = zone.civil(at as i64); let day = |d: &pinnacle_rt::locale::DateTime| { Date { year: d.year, month: d.month, day: d.day, } .days() }; let time = pinnacle_locale::time(then.hour, then.minute); let today = pinnacle_rt::locale::now_in(zone).map(|(now, _)| day(&now)); match today.map(|today| today - day(&then)) { Some(0) => time, Some(1) => alloc::format!("{} {time}", t("Yesterday")), _ => alloc::format!( "{} {time}", pinnacle_locale::date_short(Date { year: then.year, month: then.month, day: then.day, }) ), } } /// What the line over a call says: who or how, for how long, and what is /// off here. fn clock_line(state: &State, muted: bool, camera_on: bool) -> String { let State::InCall { person, via, voice, since, .. } = state else { return String::new(); }; let time = duration((pinnacle_rt::time() - since) / 1000); let mut line = match (via, voice) { (Via::Phone, _) => tf("Phone call · {}", &[&time]), (Via::Online, true) => tf("Voice call · {}", &[&time]), (Via::Online, false) => alloc::format!("{} · {time}", person.name), }; if muted { line.push_str(" · "); line.push_str(t("Muted")); } if !camera_on && *via == Via::Online && !voice { line.push_str(" · "); line.push_str(t("Camera off")); } line } /// A round button, named for `cargo xtask`, `size` pixels across. fn round( label: &'static str, name: &'static str, color: &str, size: u32, tap: Tap, tapped: &Signal>, ) -> View { let tapped = tapped.clone(); el("button") .attr("type", "button") .attr("data-name", name) .attr( "style", alloc::format!( "width: {size}px; aspect-ratio: 1; border-radius: 50%; border: 0; padding: 0; \ display: flex; align-items: center; justify-content: center; \ background: {color}; color: var(--m-text); font-size: 15px" ), ) .on("click", move |_| tapped.set(Some(tap))) .child(label) .into_view() } /// A round switch in a call (the microphone, the camera): light while what /// it names is off. fn switch( label: &'static str, name: &'static str, off: bool, tap: Tap, tapped: &Signal>, ) -> View { let tapped = tapped.clone(); let (background, color) = if off { ("#eceeec", "#080b10") } else { ("var(--m-surface)", "var(--m-text)") }; el("button") .attr("type", "button") .attr("data-name", name) .attr("aria-pressed", if off { "true" } else { "false" }) .attr( "style", alloc::format!( "width: 88px; aspect-ratio: 1; border-radius: 50%; border: 0; padding: 0; \ display: flex; align-items: center; justify-content: center; \ background: {background}; color: {color}; font-size: 14px" ), ) .on("click", move |_| tapped.set(Some(tap))) .child(label) .into_view() } /// A small button in a list row, named for `cargo xtask`. fn small( label: &'static str, name: String, background: &str, tap: Tap, tapped: &Signal>, ) -> View { let tapped = tapped.clone(); el("button") .class("m-button") .attr("type", "button") .attr("data-name", name) .attr( "style", alloc::format!("background: {background}; color: #fff; min-width: 80px"), ) .on("click", move |_| tapped.set(Some(tap))) .child(label) .into_view() } /// Who a call is with: the name, what is happening, and their mark. fn who(person: &Person, what: View) -> View { let initial: String = person.name.chars().take(1).collect(); el("div") .attr( "style", "flex: 1; display: flex; flex-direction: column; align-items: center; \ justify-content: center; gap: 12px", ) .child( el("div") .attr("style", "font-size: 30px; color: var(--m-text-strong)") .child(person.name.clone()), ) .child(el("div").attr("style", "color: var(--m-text-dim)").child(what)) .child( el("div") .attr( "style", alloc::format!( "width: 135px; aspect-ratio: 1; border-radius: 50%; margin-top: 24px; \ display: flex; align-items: center; justify-content: center; \ font-size: 72px; color: var(--m-text); background: {}", css_color(theme::color_for(&person.name)) ), ) .child(initial), ) .into_view() } /// A row of a list: what it says, and its buttons. fn row(about: View, buttons: Vec) -> View { el("div") .attr( "style", "display: flex; align-items: center; gap: 12px; padding: 14px 18px; \ background: var(--m-surface); border-radius: var(--m-radius-lg)", ) .child(about) .child( el("div") .attr("style", "flex: none; display: flex; gap: 8px") .child(buttons), ) .into_view() } /// A name, and a smaller line under it. fn about(name: &str, line: String, color: &str) -> View { let mut about = el("div") .attr( "style", "flex: 1; min-width: 0; display: flex; flex-direction: column", ) .child( el("span") .attr("style", alloc::format!("font-size: 21px; color: {color}")) .child(String::from(name)), ); if !line.is_empty() { about = about.child( el("span") .attr("style", "font-size: 12px; color: var(--m-text-dim)") .child(line), ); } about.into_view() } /// A control over a list, at its right. fn over_list(control: View) -> View { el("div") .attr( "style", "display: flex; justify-content: flex-end; margin: 8px 0 0", ) .child(control) .into_view() } /// What the call page shows besides the call: the people, the recent /// calls, the zone their times are in, and whether a number can be typed. struct Lists<'a> { people: &'a [Person], recents: &'a [Recent], zone: &'a Zone, can_dial: bool, dialled: &'a Signal, /// Whether the recent calls are shown rather than the people, and how /// many calls were missed since they last were. recent_tab: bool, unseen: usize, } /// The two tabs over the first page: the people, and the recent calls /// with how many were missed since they were last looked at. fn tabs(lists: &Lists, tapped: &Signal>) -> View { let tab = |label: String, name: &'static str, on: bool, recent: bool| { let tapped = tapped.clone(); let (background, color) = if on { ("var(--m-surface)", "var(--m-text-strong)") } else { ("transparent", "var(--m-text-dim)") }; el("button") .attr("type", "button") .attr("data-name", name) .attr("aria-pressed", if on { "true" } else { "false" }) .attr( "style", alloc::format!( "flex: 1; display: flex; justify-content: center; border: 0; padding: 10px 0; \ border-radius: var(--m-radius-lg); \ background: {background}; color: {color}; font-size: 15px" ), ) .on("click", move |_| tapped.set(Some(Tap::Tab(recent)))) .child(label) .into_view() }; let recent = if lists.unseen > 0 { alloc::format!("{} ({})", t("Recent"), lists.unseen) } else { t("Recent").into() }; el("div") .attr( "style", "display: flex; gap: 4px; padding: 4px; margin: 0 0 4px; \ border: 1px solid var(--m-surface); border-radius: var(--m-radius-lg)", ) .child(tab(t("People").into(), "tab-people", !lists.recent_tab, false)) .child(tab(recent, "tab-recent", lists.recent_tab, true)) .into_view() } /// The first page: a number to dial and everyone to call, or the recent /// calls. fn lists(line: &str, lists: &Lists, tapped: &Signal>) -> View { let mut list = el("div").attr( "style", "display: flex; flex-direction: column; gap: 12px; max-width: 720px; width: 100%; \ margin: 0 auto", ); list = list.child(tabs(lists, tapped)); if lists.recent_tab { list = list.child(recents(lists, tapped)); } else { list = list.child(people(lists, tapped)); } el("main") .attr( "style", "min-height: 100vh; padding: 24px 16px; background: #080b10", ) .child( el("div") .attr("style", "max-width: 720px; margin: 0 auto") .child( el("h1") .attr("style", "font-size: 30px; margin: 16px 0 0") .child(t("Calls")), ) .child( el("p") .attr( "style", "margin: 0 0 16px; font-size: 12px; color: var(--m-text-dim)", ) .child(String::from(line)), ), ) .child(list) .into_view() } /// The people tab: a number to type where the device has a phone, and /// everyone to call, by video or voice where they have a Pinnacle. fn people(lists: &Lists, tapped: &Signal>) -> View { let green = "var(--m-success)"; let mut list = el("div").attr("style", "display: flex; flex-direction: column; gap: 12px"); if lists.can_dial { let (shown, set) = (lists.dialled.clone(), lists.dialled.clone()); list = list.child(row( el("div") .class("m-input") .attr("style", "flex: 1; min-width: 0") .child( el("input") .class("m-input__native") .attr("type", "tel") .attr("placeholder", t("Number")) .attr("data-name", "number") .prop("value", move || shown.get_untracked()) .on("input", move |e| set.set(e.value.clone().unwrap_or_default())), ) .into_view(), alloc::vec![small(t("Call"), "dial".into(), green, Tap::Dial, tapped)], )); } if lists.people.is_empty() { list = list.child( el("p") .attr("style", "color: var(--m-text-dim)") .child(t("No one to call yet: add people in Contacts")), ); } for (i, p) in lists.people.iter().enumerate() { let line = match (&p.key, p.phones.first()) { (None, Some(n)) => n.clone(), _ => String::new(), }; let buttons = if p.key.is_some() { alloc::vec![ small( t("Voice"), alloc::format!("voice-{i}"), green, Tap::Call(i, true), tapped ), small( t("Video"), alloc::format!("call-{i}"), green, Tap::Call(i, false), tapped ), ] } else { alloc::vec![small( t("Call"), alloc::format!("call-{i}"), green, Tap::Call(i, false), tapped )] }; list = list.child(row(about(&p.name, line, "var(--m-text)"), buttons)); } list.into_view() } /// The recent tab: the calls, newest first, each to make again. fn recents(lists: &Lists, tapped: &Signal>) -> View { let red = "#e05a4f"; let green = "var(--m-success)"; let mut list = el("div").attr("style", "display: flex; flex-direction: column; gap: 12px"); if lists.recents.is_empty() { list = list.child( el("p") .attr("style", "color: var(--m-text-dim)") .child(t("No calls yet")), ); } else { list = list.child(over_list( el("button") .class("m-button") .attr("type", "button") .attr("data-name", "clear-recents") .on("click", { let tapped = tapped.clone(); move |_| tapped.set(Some(Tap::ClearRecents)) }) .child(t("Clear")) .into_view(), )); for (i, r) in lists.recents.iter().take(RECENTS_SHOWN).enumerate() { let how = match (r.outgoing, r.outcome) { (_, Outcome::Answered) => { alloc::format!("{} {}", if r.outgoing { "↗" } else { "↙" }, duration(r.secs)) } (false, Outcome::Missed) => alloc::format!("↙ {}", t("Missed")), (false, _) => alloc::format!("↙ {}", t("Declined")), (true, _) => alloc::format!("↗ {}", t("Not answered")), }; let kind = match (r.via, r.voice) { (Via::Phone, _) => t("Phone"), (Via::Online, true) => t("Voice"), (Via::Online, false) => t("Video"), }; let line = alloc::format!("{how} · {kind} · {}", when(r.at, lists.zone)); let color = if r.outcome == Outcome::Missed { red } else { "var(--m-text)" }; list = list.child(row( about(&r.name, line, color), alloc::vec![small( t("Call"), alloc::format!("again-{i}"), green, Tap::Again(i), tapped )], )); } } list.into_view() } /// The page for the state the app is in: whom to call, a ring, a call. #[allow(clippy::too_many_arguments)] fn page( state: &State, lists_of: &Lists, muted: bool, camera_on: bool, clock: &Signal, frame: &Signal, scale: i32, tapped: &Signal>, ) -> View { let main = el("main").attr( "style", "height: 100vh; display: flex; flex-direction: column; background: #080b10; \ padding: 24px 16px", ); let buttons = |row: View, gap: u32| { el("div") .attr( "style", alloc::format!( "flex: none; display: flex; justify-content: center; align-items: center; \ gap: {gap}px; padding: 24px 0 36px" ), ) .child(row) }; let red = "#e05a4f"; let green = "var(--m-success)"; // In a call peer to peer: the microphone, the camera in a video call, // and the end. let controls = |video: bool| { let mut row = alloc::vec![switch(t("Mute"), "mute", muted, Tap::Mute, tapped)]; if video { row.push(switch(t("Camera"), "camera", !camera_on, Tap::Camera, tapped)); } row.push(round(t("End"), "end", red, 88, Tap::End, tapped)); buttons(row.into_view(), 28) }; match state { State::Idle | State::Ended { .. } => { let line: &str = match state { State::Ended { text, .. } => text, _ => t("Peer to peer; by phone when someone is not online"), }; lists(line, lists_of, tapped) } State::Ringing { person, outgoing, via, voice, .. } => { let what = match (outgoing, via, voice) { (true, Via::Online, _) => t("Calling…"), (true, Via::Phone, _) => t("Not online: calling by phone…"), (false, Via::Online, false) => t("Incoming video call"), (false, Via::Online, true) => t("Incoming voice call"), (false, Via::Phone, _) => t("Incoming phone call"), }; let row = if *outgoing { round(t("End"), "end", red, 120, Tap::End, tapped) } else { alloc::vec![ round(t("Decline"), "decline", red, 120, Tap::Decline, tapped), round(t("Answer"), "answer", green, 120, Tap::Answer, tapped), ] .into_view() }; main.child(who(person, what.into_view())) .child(buttons(row, 60)) .into_view() } State::InCall { person, via: Via::Phone, .. } => main .child(who(person, clock.clone().into_view())) .child(buttons(round(t("End"), "end", red, 120, Tap::End, tapped), 60)) .into_view(), State::InCall { person, voice: true, .. } => main .child(who(person, clock.clone().into_view())) .child(controls(false)) .into_view(), State::InCall { .. } => { // The other side as large as fits (twice its size on a tall // screen), and us small beside it. let px = |v: i32| alloc::format!("{}px", v as f32 / SCALE); let video = |name: &'static str, w: i32, h: i32| { let frame = frame.clone(); el("canvas") .attr("data-name", name) .attr("data-revision", move || alloc::format!("{}", frame.get())) .attr( "style", alloc::format!("display: block; flex: none; width: {}; height: {}", px(w), px(h)), ) }; let (w, h) = (W as i32, H as i32); main.child( el("div") .attr("style", "flex: none; text-align: center; padding: 8px 0 16px") .child(clock.clone()), ) .child( el("div") .attr( "style", "flex: 1; min-height: 0; display: flex; justify-content: center; \ align-items: flex-start; gap: 12px", ) .child(video("remote", w * scale, h * scale)) .child(video("local", w / 2, h / 2)), ) .child(controls(true)) .into_view() } } } /// What the call's two pictures show: the other side's mark when their /// video stopped coming, and whether our camera is on. struct Pictures<'a> { decoder: &'a video::Decoder, local: &'a [u32], /// The other side's initial and colour, while no video comes. remote_off: Option<(String, Color)>, camera_on: bool, } /// Draws what changed, the call's video from the frames: the other side's /// last decoded one (or their mark when none comes), and ours at half size /// (or that the camera is off). fn draw(screen: &mut Screen, app: &mut App, pictures: &Pictures, all: bool) -> Option { let mut canvas = app.canvas(); screen.draw_with(&mut canvas, all, &mut |name, canvas, r| match name { "remote" => { if let Some((initial, color)) = &pictures.remote_off { canvas.fill_rect(r, theme::SURFACE); let radius = r.width.min(r.height) / 4; canvas.fill_circle(r.x + r.width / 2, r.y + r.height / 2, radius, *color); canvas.text_centered( theme::huge(), Rect::new(r.x, r.y + r.height / 2 - radius, r.width, radius * 2), initial, theme::TEXT, ); return; } let s = (r.width / W as i32).max(1) as usize; let mut remote = alloc::vec![0u32; W * s * H * s]; pictures.decoder.frame.to_rgb(&mut remote, W * s, 0, 0, s); canvas.blit(&remote, (W * s) as i32, (H * s) as i32, r.x, r.y); } "local" => { if !pictures.camera_on { canvas.fill_rect(r, theme::SURFACE); canvas.text_centered(theme::small(), r, t("Camera off"), theme::TEXT_DIM); return; } let mut small = alloc::vec![0u32; W / 2 * H / 2]; for y in 0..H / 2 { for x in 0..W / 2 { small[y * W / 2 + x] = pictures.local[y * 2 * W + x * 2]; } } canvas.blit(&small, (W / 2) as i32, (H / 2) as i32, r.x, r.y); } _ => {} }) } #[unsafe(no_mangle)] fn main(argument: u64) -> u64 { let mut app = App::new("Calls"); let mut screen = Screen::new(app.width, app.height); let tapped: Signal> = signal(None); // What the call's line says, and the frame shown, moved on per frame. let clock = signal(String::new()); let frame = signal(0u32); // The number typed on the first page. let dialled = signal(String::new()); let Some(client) = Client::connect(10_000) else { return 1; }; // Ordinary calls, where the device has a modem. let phone = phone::Client::connect(); let mut pending = Vec::new(); let mut people = people_of(&client, &mut pending); let me = client.card(&mut pending); let my_name: String = me .get(64..96) .map(|n| String::from_utf8_lossy(n).trim_end_matches('\0').into()) .unwrap_or_default(); let initial: String = my_name.chars().take(1).collect(); let mut log = Log { recents: read_recents(), display: None, unseen: 0, }; // Whether the first page shows the recent calls rather than the people. let mut recent_tab = false; let mut zone = pinnacle_rt::locale::zone(); let mut state = State::Idle; // In a call: whether the microphone is muted and the camera on. let mut muted = false; let mut camera_on = true; // When the ringtone's next burst is due, while a call rings in. let mut next_ring = 0u64; // Tell the service this is the Calls app, which gets a waiting ring. client.channel().send(&[p2p::RING_PENDING], Vec::new()); if argument == 1 { // Answer what rang: the service sends it again on connecting. if let Some((from, payload)) = pending.iter().find(|(_, p)| p.first() == Some(&p2p::CALL)) && let Some(person) = people.iter().find(|p| p.key == Some(*from)) { state = State::Ringing { person: person.clone(), outgoing: false, via: Via::Online, voice: voice_only(payload), since: pinnacle_rt::time(), heard: true, }; next_ring = pinnacle_rt::time(); } } // With 2, the phone service's state (asked on connecting) brings the // call that rings in. let mut encoder = video::Encoder::new(W, H, QUALITY); let mut decoder = video::Decoder::new(W, H, QUALITY); let mut audio = adpcm::State::default(); // The speaker and the microphone, where the device has them. A // microphone that gives digital silence (QEMU's) is stood in for by the // tone, so a call is heard at the other end. let mut speaker = Player::open(16_000, 1); let recorder = Recorder::open(16_000, 1); let mut mic: Vec = Vec::new(); let mut local = alloc::vec![0u32; W * H]; let mut frames = 0u32; // When the other side's last frame came. let mut last_video = 0u64; let mut phase = (8000.0f32, 0.0f32); let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE]; let mut next_frame = pinnacle_rt::time(); let mut redraw = true; // A frame of the call to show, or its clock moved on: drawn without // building the page again. let mut tick = false; // The ring peer to peer was not heard: take it back and call the // number, or say they cannot be reached. let fall_back = |state: &mut State, log: &mut Log, client: &Client, phone: Option<&phone::Client>| { let State::Ringing { person, .. } = state else { return; }; if let Some(key) = &person.key { client.send(key, &[p2p::CALL, p2p::call::HANG_UP]); } match (phone, person.phones.first()) { (Some(phone), Some(n)) => { pinnacle_rt::println!("calls: {} not reachable online; calling {n}", person.name); phone.dial(n); let person = person.clone(); *state = State::Ringing { person, outgoing: true, via: Via::Phone, voice: true, since: pinnacle_rt::time(), heard: true, }; } _ => { pinnacle_rt::println!("calls: {} not reachable", person.name); end(state, log, Outcome::NoAnswer, t("Not reachable")); } } }; loop { let (width, height) = (app.width as i32, app.height as i32); let remote_off = match &state { State::InCall { person, via: Via::Online, voice: false, .. } if pinnacle_rt::time() >= last_video + STALE_MS => Some(( person.name.chars().take(1).collect(), theme::color_for(&person.name), )), _ => None, }; let pictures = Pictures { decoder: &decoder, local: &local, remote_off, camera_on, }; if redraw { // A new state: its page. clock.set(clock_line(&state, muted, camera_on)); screen.resize(app.width, app.height); screen.clear(); let scale = video_scale(width, height, (W as i32, H as i32)); let lists_of = Lists { people: &people, recents: &log.recents, zone: &zone, can_dial: phone.is_some(), dialled: &dialled, recent_tab, unseen: log.unseen, }; screen.mount(page( &state, &lists_of, muted, camera_on, &clock, &frame, scale, &tapped, )); draw(&mut screen, &mut app, &pictures, true); app.present_all(); screen.announce(ANNOUNCE); redraw = false; } else if core::mem::take(&mut tick) { // A frame of the call, or its clock: only those are drawn again. clock.set(clock_line(&state, muted, camera_on)); frame.set(frame.get_untracked().wrapping_add(1)); if let Some(area) = draw(&mut screen, &mut app, &pictures, false) { app.present(area); } } let deadline = match &state { State::InCall { via: Via::Online, .. } => Some(next_frame), // A phone call's clock, once a second. State::InCall { via: Via::Phone, .. } => Some(pinnacle_rt::time() + 1000), State::Ringing { outgoing: false, .. } if speaker.is_some() => Some(next_ring), State::Ringing { outgoing: true, via: Via::Online, since, heard: false, .. } => Some(since + FALLBACK_MS), State::Ended { until, .. } => Some(*until), _ => None, }; // The p2p service, the phone service, then the microphone and the // speaker when there are any. let mut others: Vec<&Channel> = alloc::vec![client.channel()]; let phone_index = phone.as_ref().map(|p| { others.push(p.channel()); others.len() - 1 }); let mic_index = recorder.as_ref().map(|r| { others.push(r.channel()); others.len() - 1 }); let speaker_index = speaker.as_ref().map(|p| { others.push(p.channel()); others.len() - 1 }); match app.wait(&others, &mut buffer, deadline) { Event::Timeout => match &state { State::InCall { person, via: Via::Online, voice, .. } => { let Some(key) = person.key else { continue }; let now = pinnacle_rt::time(); next_frame = now + FRAME_MS; if !voice && camera_on { camera(now, &initial, &mut local); let key_frame = frames.is_multiple_of(KEY_EVERY); frames += 1; for packet in encoder.encode(&video::Frame::from_rgb(W, H, &local), key_frame) { let mut payload = alloc::vec![p2p::MEDIA, VIDEO]; payload.extend(packet); client.send(&key, &payload); } } // Without a microphone, 100 ms of the stand-in: five frames. if recorder.is_none() && !muted { for _ in 0..5 { let samples = tone(&mut phase, STAND_IN, adpcm::FRAME); let mut payload = alloc::vec![p2p::MEDIA, AUDIO]; payload.extend(adpcm::encode(&mut audio, &samples)); client.send(&key, &payload); } } tick = true; } State::InCall { .. } => tick = true, State::Ringing { outgoing: false, .. } => { // A burst of the ringtone, then quiet until the next. if let Some(speaker) = &mut speaker { let mut ring = (6000.0f32, 0.0f32); speaker.write(&tone(&mut ring, RING, RING_BURST)); } next_ring = pinnacle_rt::time() + RING_EVERY_MS; } State::Ringing { outgoing: true, via: Via::Online, heard: false, since, .. } if pinnacle_rt::time() >= since + FALLBACK_MS => { fall_back(&mut state, &mut log, &client, phone.as_ref()); redraw = true; } State::Ended { until, .. } if pinnacle_rt::time() >= *until => { state = State::Idle; redraw = true; } _ => {} }, Event::Channel { index, len, .. } if Some(index) == phone_index => { match phone::parse(&buffer[..len]) { // The call ringing in, as the state tells it (started // with 2) or as it starts. Some(Said::State { call: phone::Call::Ringing, number, .. }) | Some(Said::Incoming { number }) => { if matches!(state, State::Idle | State::Ended { .. }) { state = State::Ringing { person: by_number(&people, &number), outgoing: false, via: Via::Phone, voice: true, since: pinnacle_rt::time(), heard: true, }; next_ring = pinnacle_rt::time(); redraw = true; } else if matches!(state, State::InCall { via: Via::Online, .. }) { // In a call peer to peer: the phone call is // refused, and kept as missed. if let Some(phone) = &phone { phone.hang_up(); } log.keep( &by_number(&people, &number), false, Via::Phone, true, Outcome::Missed, 0, ); } } Some(Said::Connected) => { if let State::Ringing { person, outgoing, via: Via::Phone, .. } = &state { pinnacle_rt::println!("calls: on the phone with {}", person.name); state = State::InCall { person: person.clone(), outgoing: *outgoing, via: Via::Phone, voice: true, since: pinnacle_rt::time(), }; redraw = true; } } Some(Said::Ended(ended)) => { let outcome = match state { State::Ringing { via: Via::Phone, outgoing: false, .. } => Some(Outcome::Missed), State::Ringing { via: Via::Phone, .. } => Some(Outcome::NoAnswer), State::InCall { via: Via::Phone, .. } => Some(Outcome::Answered), _ => None, }; if let Some(outcome) = outcome { pinnacle_rt::println!("calls: the phone call ended: {}", ended.text()); end(&mut state, &mut log, outcome, ended_text(ended)); redraw = true; } } _ => {} } } Event::Channel { index, len, .. } if Some(index) == mic_index => { // The microphone's period: sent on in the codec's frames, the // stand-in tone where it gave digital silence; nothing while // muted. if let State::InCall { person, via: Via::Online, .. } = &state && let Some(key) = person.key && !muted { mic.extend(Recorder::samples(&buffer[..len])); while mic.len() >= adpcm::FRAME { let mut frame: Vec = mic.drain(..adpcm::FRAME).collect(); if frame.iter().all(|&s| s == 0) { frame = tone(&mut phase, STAND_IN, adpcm::FRAME); } let mut payload = alloc::vec![p2p::MEDIA, AUDIO]; payload.extend(adpcm::encode(&mut audio, &frame)); client.send(&key, &payload); } } else { mic.clear(); } } Event::Channel { index, len, .. } if Some(index) == speaker_index => { if let Some(speaker) = &mut speaker { speaker.report(&buffer[..len]); } } Event::Channel { len, .. } => { if buffer.first() == Some(&p2p::UNREACHABLE) && len >= 33 { let key: Key = buffer[1..33].try_into().unwrap(); if let State::Ringing { person, outgoing: true, via: Via::Online, heard: false, .. } = &state && person.key == Some(key) { fall_back(&mut state, &mut log, &client, phone.as_ref()); redraw = true; } continue; } let Some((from, payload)) = p2p::parse_received(&buffer[..len]) else { continue; }; let online_with = |state: &State| match state { State::Ringing { person, via: Via::Online, .. } | State::InCall { person, via: Via::Online, .. } => person.key == Some(from), _ => false, }; match (payload.first().copied(), payload.get(1).copied()) { (Some(p2p::MEDIA), Some(VIDEO)) => { if decoder.decode(&payload[2..]) { last_video = pinnacle_rt::time(); } } (Some(p2p::MEDIA), Some(AUDIO)) => { let samples = adpcm::decode(&payload[2..]); if let Some(speaker) = &mut speaker { speaker.write(&samples); } } (Some(p2p::CALL), Some(p2p::call::RING)) => { let Some(person) = people.iter().find(|p| p.key == Some(from)) else { continue; }; if matches!(state, State::Idle | State::Ended { .. }) { state = State::Ringing { person: person.clone(), outgoing: false, via: Via::Online, voice: voice_only(payload), since: pinnacle_rt::time(), heard: true, }; next_ring = pinnacle_rt::time(); redraw = true; } else if !online_with(&state) { // In another call: busy, and kept as missed. pinnacle_rt::println!("calls: busy for {}", person.name); client.send(&from, &[p2p::CALL, p2p::call::BUSY]); let person = person.clone(); log.keep( &person, false, Via::Online, voice_only(payload), Outcome::Missed, 0, ); } } (Some(p2p::CALL), Some(p2p::call::RINGING)) => { if let State::Ringing { person, outgoing: true, via: Via::Online, heard, .. } = &mut state && person.key == Some(from) { pinnacle_rt::println!("calls: {} hears it ring", person.name); *heard = true; } } (Some(p2p::CALL), Some(p2p::call::ANSWER)) => { if let State::Ringing { person, outgoing: true, via: Via::Online, voice, .. } = &state && person.key == Some(from) { pinnacle_rt::println!("calls: {} answered", person.name); state = State::InCall { person: person.clone(), outgoing: true, via: Via::Online, voice: *voice, since: pinnacle_rt::time(), }; frames = 0; last_video = pinnacle_rt::time(); redraw = true; } } (Some(p2p::CALL), Some(p2p::call::HANG_UP)) if online_with(&state) => { let (outcome, text) = match state { State::Ringing { outgoing: false, .. } => (Outcome::Missed, t("Missed call")), State::Ringing { .. } => (Outcome::NoAnswer, t("Declined")), _ => (Outcome::Answered, t("Call ended")), }; end(&mut state, &mut log, outcome, text); redraw = true; } (Some(p2p::CALL), Some(p2p::call::BUSY)) => { if let State::Ringing { person, outgoing: true, via: Via::Online, .. } = &state && person.key == Some(from) { pinnacle_rt::println!("calls: {} is busy", person.name); end(&mut state, &mut log, Outcome::NoAnswer, t("Busy")); redraw = true; } } _ => {} } } Event::Input(e) => { screen.input(&e); let idle = matches!(state, State::Idle | State::Ended { .. }); // Whom to call, and how: a person, a recent call again, or // the number typed. let call = match take(&tapped) { Some(Tap::Call(i, voice)) if idle && i < people.len() => { Some((people[i].clone(), voice, false)) } Some(Tap::Again(i)) if idle && i < log.recents.len() => { let r = &log.recents[i]; Some(( person_of(&people, r), r.voice, r.via == Via::Phone || r.key.is_none(), )) } Some(Tap::Dial) if idle => { let n: String = dialled.get_untracked().trim().into(); (!n.is_empty()).then(|| (by_number(&people, &n), true, true)) } Some(Tap::Tab(recent)) if idle => { recent_tab = recent; if recent { log.unseen = 0; } pinnacle_rt::println!("calls: {}", if recent { "recent calls" } else { "people" }); redraw = true; None } Some(Tap::ClearRecents) if idle => { pinnacle_rt::println!("calls: recent calls cleared"); log.recents.clear(); log.save(); redraw = true; None } Some(Tap::Mute) if matches!(state, State::InCall { .. }) => { muted = !muted; pinnacle_rt::println!("calls: {}", if muted { "muted" } else { "unmuted" }); redraw = true; None } Some(Tap::Camera) if matches!(state, State::InCall { .. }) => { camera_on = !camera_on; // The picture starts again from a whole frame. frames = 0; pinnacle_rt::println!("calls: camera {}", if camera_on { "on" } else { "off" }); redraw = true; None } Some(Tap::Answer) => { if let State::Ringing { person, outgoing: false, via, voice, .. } = &state { if *via == Via::Phone { // In the call once the phone service says so. if let Some(phone) = &phone { phone.answer(); } } else { if let Some(key) = &person.key { client.send(key, &[p2p::CALL, p2p::call::ANSWER]); } pinnacle_rt::println!("calls: answered {}", person.name); state = State::InCall { person: person.clone(), outgoing: false, via: Via::Online, voice: *voice, since: pinnacle_rt::time(), }; frames = 0; last_video = pinnacle_rt::time(); next_frame = pinnacle_rt::time(); redraw = true; } } None } Some(tap @ (Tap::Decline | Tap::End)) => { if let State::Ringing { person, via, .. } | State::InCall { person, via, .. } = &state { match (via, &person.key, &phone) { (Via::Phone, _, Some(phone)) => phone.hang_up(), (Via::Online, Some(key), _) => { client.send(key, &[p2p::CALL, p2p::call::HANG_UP]); } _ => {} } let outcome = match (&state, tap) { (State::Ringing { outgoing: false, .. }, _) => Outcome::Declined, (State::Ringing { .. }, _) => Outcome::NoAnswer, _ => Outcome::Answered, }; end(&mut state, &mut log, outcome, ""); redraw = true; } None } _ => None, }; if let Some((person, voice, by_phone)) = call { muted = false; camera_on = true; let now = pinnacle_rt::time(); match (&person.key, by_phone) { (Some(key), false) => { let ring: &[u8] = if voice { &[p2p::CALL, p2p::call::RING, p2p::call::VOICE] } else { &[p2p::CALL, p2p::call::RING] }; client.send(key, ring); pinnacle_rt::println!( "calls: calling {}{}", person.name, if voice { ", voice only" } else { "" } ); state = State::Ringing { person, outgoing: true, via: Via::Online, voice, since: now, heard: false, }; } _ => { // No Pinnacle, or a number: by phone, straight // away. pinnacle_rt::println!("calls: calling {}", person.name); let person = Person { key: None, ..person }; state = State::Ringing { person, outgoing: true, via: Via::Online, voice: true, since: now, heard: false, }; fall_back(&mut state, &mut log, &client, phone.as_ref()); } } redraw = true; } // A press shows on what it pressed. if !redraw && let Some(area) = draw(&mut screen, &mut app, &pictures, false) { app.present(area); } } Event::Resized => redraw = true, Event::Preferences => { screen.restyle(); redraw = true; } Event::Shown(true) => { // A number written in Contacts meanwhile counts, and a zone // chosen in Settings. Of what arrives while asking, only a // ring matters when idle. let mut arrived = Vec::new(); people = people_of(&client, &mut arrived); zone = pinnacle_rt::locale::zone(); pinnacle_rt::println!("calls: in front, {} to call", people.len()); let ring = arrived .iter() .find(|(_, p)| p.get(..2) == Some(&[p2p::CALL, p2p::call::RING])); if let (State::Idle | State::Ended { .. }, Some((from, payload))) = (&state, ring) && let Some(person) = people.iter().find(|p| p.key == Some(*from)) { state = State::Ringing { person: person.clone(), outgoing: false, via: Via::Online, voice: voice_only(payload), since: pinnacle_rt::time(), heard: true, }; next_ring = pinnacle_rt::time(); } redraw = true; } Event::Closed => return 0, _ => {} } if let State::InCall { via: Via::Online, .. } = state && next_frame <= pinnacle_rt::time() { next_frame = pinnacle_rt::time(); } } }