use std::{ rc::Rc, sync::{Arc, Mutex}, time::{Duration, Instant}, }; use crate::lang::w; use common::call::CreateMessage; use common::constant::VOICE_SAMPLE_RATE; use gpui_kit::{ App, Context, Div, Entity, InteractiveElement, IntoElement, MouseButton, ParentElement, Styled, Task, Window, assets::IconName, component::{Icon, WindowExt, notification::Notification}, div, prelude::FluentBuilder as _, px, }; use rtrb::{Consumer, RingBuffer}; use super::{ Tooltip as _, Yumush, chat::VoiceState, clickable, media_view::time_text, notify_error, parts, style::{self, Tokens, radius, size, space}, text, widget::ok_or_notify, }; use crate::{ media::voice_note::{self, BARS}, voice::{ Playback, audio::{self, Audio}, }, }; const TICK: Duration = Duration::from_millis(100); const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize; const MAX_SECONDS: usize = 300; const MAX_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * MAX_SECONDS; const SLOT_WIDTH: f32 = 5.; const BAR_WIDTH: f32 = 3.; const BAR_MIN: f32 = 2.; const BAR_MAX: f32 = 24.; #[derive(Default)] pub enum VoiceNote { #[default] Idle, Recording { started: Instant, _audio: Audio, consumer: Consumer, samples: Vec, levels: Vec, _tick: Task<()>, }, } fn drain(consumer: &mut Consumer, samples: &mut Vec) { while samples.len() < MAX_SAMPLES && let Ok(sample) = consumer.pop() { samples.push(sample); } } pub fn bars( levels: &[f32], progress: f32, t: Tokens, scrub: bool, on_pick: impl Fn(usize, &mut Window, &mut App) + 'static, ) -> Div { let on_pick = Rc::new(on_pick); let offset = BARS - levels.len().min(BARS); div() .flex_1() .h(px(BAR_MAX)) .flex() .items_center() .children((0..BARS).map(|index| { let level = index .checked_sub(offset) .and_then(|slot| levels.get(slot)) .copied() .unwrap_or(0.); let color = if (index as f32) < progress * BARS as f32 { t.paper() } else { t.dim() }; let (down, drag) = (on_pick.clone(), on_pick.clone()); div() .w(px(SLOT_WIDTH)) .h_full() .flex() .items_center() .justify_center() .on_mouse_down(MouseButton::Left, move |_, window, cx| { down(index, window, cx) }) .when(scrub, |slot| { slot.on_mouse_move(move |event, window, cx| { if event.pressed_button == Some(MouseButton::Left) { drag(index, window, cx); } }) }) .child( div() .w(px(BAR_WIDTH)) .h(px((BAR_MAX * level).max(BAR_MIN))) .rounded_full() .bg(color), ) })) } pub fn recording_row( started: Instant, levels: &[f32], entity: &Entity, t: Tokens, ) -> impl IntoElement { let cancel = entity.clone(); let send = entity.clone(); div() .min_h(px(size::ROW)) .pl(px(space::XS)) .pr(px(space::XS)) .py(px(space::XS)) .flex() .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) .bg(t.raise()) .child( clickable("cancel_voice_note", t, move |_, cx| { cancel.update(cx, |yumush, cx| yumush.cancel_voice_note(cx)) }) .tip(w().voice_note.cancel) .size(px(size::CONTROL_SM)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .text_color(t.dim()) .child(Icon::new(IconName::X).size(px(size::ICON))), ) .child( div() .flex_1() .flex() .items_center() .gap(px(space::SM)) .text_size(text(style::text::LABEL)) .text_color(t.paper()) .child(super::parts::small_icon(IconName::Mic)) .child(time_text( started .elapsed() .min(Duration::from_secs(MAX_SECONDS as u64)), )) .child(bars(levels, 1., t, false, |_, _, _| {})), ) .child( parts::pill("send_voice_note", t, move |window, cx| { send.update(cx, |yumush, cx| yumush.send_voice_note(window, cx)) }) .tip(w().voice_note.send) .size(px(size::CONTROL_SM)) .justify_center() .child(parts::small_icon(IconName::ArrowUp)), ) } pub fn mic_button(entity: &Entity, t: Tokens) -> impl IntoElement { let entity = entity.clone(); clickable("voice_note_button", t, move |window, cx| { entity.update(cx, |yumush, cx| yumush.start_voice_note(window, cx)) }) .tip(w().voice_note.voice_message) .size(px(size::CONTROL_SM)) .flex() .items_center() .justify_center() .rounded(px(radius::MD)) .text_color(t.dim()) .child(Icon::new(IconName::Mic).size(px(size::ICON))) } impl Yumush { fn start_voice_note(&mut self, window: &mut Window, cx: &mut Context) { if !matches!(self.chat.session.voice_state, VoiceState::Off) { window.push_notification(Notification::error(w().voice_note.leave_call_first), cx); return; } let (producer, consumer) = RingBuffer::new(RING_SAMPLES); let capture = Arc::new(Mutex::new(producer)); let (_, silent) = RingBuffer::new(1); let playback: Playback = Arc::new(Mutex::new(silent)); let audio = audio::start(Some(capture), playback, self.settings.voice.choice.clone()); let tick = cx.spawn(async move |this, cx| { loop { cx.background_executor().timer(TICK).await; if this .update(cx, |yumush, cx| yumush.tick_voice_note(cx)) .is_err() { break; } } }); self.chat.session.media.voice_note = VoiceNote::Recording { started: Instant::now(), _audio: audio, consumer, samples: Vec::new(), levels: Vec::new(), _tick: tick, }; cx.notify(); } fn tick_voice_note(&mut self, cx: &mut Context) { if !matches!(self.chat.session.voice_state, VoiceState::Off) { self.chat.session.media.voice_note = VoiceNote::Idle; } if let VoiceNote::Recording { consumer, samples, levels, .. } = &mut self.chat.session.media.voice_note { let start = samples.len(); drain(consumer, samples); levels.push(voice_note::level(&samples[start..])); if levels.len() > BARS { levels.remove(0); } } cx.notify(); } fn cancel_voice_note(&mut self, cx: &mut Context) { self.chat.session.media.voice_note = VoiceNote::Idle; cx.notify(); } fn send_voice_note(&mut self, window: &mut Window, cx: &mut Context) { let VoiceNote::Recording { mut consumer, mut samples, .. } = std::mem::take(&mut self.chat.session.media.voice_note) else { return; }; drain(&mut consumer, &mut samples); let Some(community_id) = self.chat.session.selected_community_id else { return; }; let network = self.network.clone(); cx.notify(); let order = self.send_order.clone(); cx.spawn_in(window, async move |this, cx| { let Some(path) = cx .background_executor() .spawn(async move { voice_note::save(&samples) }) .await else { return; }; let Ok(upload) = this.update(cx, |yumush, cx| { yumush.upload(community_id, path.clone(), cx) }) else { return; }; let uploaded = upload.await; let _ = std::fs::remove_file(&path); let attachment = match uploaded { Ok(attachment) => attachment, Err(error) => return notify_error(&this, cx, error), }; let _turn = order.lock().await; ok_or_notify( network .call(CreateMessage { community_id, body: String::new(), attachments: vec![attachment.id], reply_to: None, }) .await, &this, cx, ); }) .detach(); } }