mod.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_trait::async_trait;
  19. use parking_lot::Mutex as SyncMutex;
  20. use rand::{rngs::OsRng, Rng};
  21. use std::sync::{mpsc, Arc};
  22. use tracing::instrument;
  23. use crate::{
  24. gfx::{
  25. anim::Frame, gfxtag, DrawCall, DrawInstruction, DrawMesh, ManagedSeqAnimPtr,
  26. ManagedTexturePtr, Rectangle, RenderApi,
  27. },
  28. mesh::{MeshBuilder, MeshInfo, COLOR_WHITE},
  29. prop::{BatchGuardPtr, PropertyAtomicGuard, PropertyRect, PropertyStr, PropertyUint32, Role},
  30. scene::{Pimpl, SceneNodeWeak},
  31. ExecutorPtr,
  32. };
  33. use super::{DrawUpdate, OnModify, UIObject};
  34. mod ivf;
  35. mod threads;
  36. use threads::{spawn_decoder_thread, spawn_loader_demuxer_thread};
  37. macro_rules! t { ($($arg:tt)*) => { trace!(target: "ui:video", $($arg)*); } }
  38. pub type VideoPtr = Arc<Video>;
  39. #[derive(Clone)]
  40. pub struct Av1VideoData {
  41. textures: Vec<Option<ManagedTexturePtr>>,
  42. anim: ManagedSeqAnimPtr,
  43. textures_pub: async_broadcast::Sender<(usize, ManagedTexturePtr)>,
  44. textures_sub: async_broadcast::Receiver<(usize, ManagedTexturePtr)>,
  45. }
  46. impl Av1VideoData {
  47. fn new(len: usize, render_api: &RenderApi) -> Self {
  48. let (textures_pub, textures_sub) = async_broadcast::broadcast(len);
  49. let anim = render_api.new_anim(len, false, gfxtag!("video"));
  50. Self { textures: vec![None; len], anim, textures_pub, textures_sub }
  51. }
  52. }
  53. pub struct Video {
  54. node: SceneNodeWeak,
  55. render_api: RenderApi,
  56. tasks: SyncMutex<Vec<smol::Task<()>>>,
  57. load_tasks: SyncMutex<Vec<smol::Task<()>>>,
  58. ex: ExecutorPtr,
  59. dc_key: u64,
  60. vid_data: Arc<SyncMutex<Option<Av1VideoData>>>,
  61. _load_handle: SyncMutex<Option<std::thread::JoinHandle<()>>>,
  62. _decoder_handle: SyncMutex<Option<std::thread::JoinHandle<()>>>,
  63. rect: PropertyRect,
  64. uv: PropertyRect,
  65. z_index: PropertyUint32,
  66. priority: PropertyUint32,
  67. path: PropertyStr,
  68. parent_rect: SyncMutex<Option<Rectangle>>,
  69. }
  70. impl Video {
  71. pub async fn new(node: SceneNodeWeak, render_api: RenderApi, ex: ExecutorPtr) -> Pimpl {
  72. t!("Video::new()");
  73. let node_ref = &node.upgrade().unwrap();
  74. let rect = PropertyRect::wrap(node_ref, Role::Internal, "rect").unwrap();
  75. let uv = PropertyRect::wrap(node_ref, Role::Internal, "uv").unwrap();
  76. let z_index = PropertyUint32::wrap(node_ref, Role::Internal, "z_index", 0).unwrap();
  77. let priority = PropertyUint32::wrap(node_ref, Role::Internal, "priority", 0).unwrap();
  78. let path = PropertyStr::wrap(node_ref, Role::Internal, "path", 0).unwrap();
  79. let self_ = Arc::new(Self {
  80. node,
  81. render_api,
  82. tasks: SyncMutex::new(vec![]),
  83. load_tasks: SyncMutex::new(vec![]),
  84. ex,
  85. dc_key: OsRng.gen(),
  86. vid_data: Arc::new(SyncMutex::new(None)),
  87. _load_handle: SyncMutex::new(None),
  88. _decoder_handle: SyncMutex::new(None),
  89. rect,
  90. uv,
  91. z_index,
  92. priority,
  93. path,
  94. parent_rect: SyncMutex::new(None),
  95. });
  96. Pimpl::Video(self_)
  97. }
  98. async fn reload(self: Arc<Self>, batch: BatchGuardPtr) {
  99. self.load_video();
  100. self.redraw(batch).await;
  101. }
  102. fn load_video(&self) {
  103. let path = self.path.get();
  104. // Thread 1 -> thread 2 channel: raw AV1 encoded frames
  105. let (frame_tx, frame_rx) = mpsc::channel();
  106. // Thread 1 (loader + demuxer):
  107. // loads chunks, demuxes IVF -> AV1 frames, initializes vid_data
  108. let loader_handle = spawn_loader_demuxer_thread(
  109. path,
  110. frame_tx,
  111. self.vid_data.clone(),
  112. self.render_api.clone(),
  113. );
  114. // Thread 2 (decoder):
  115. // blocks on frame_rx, decodes AV1 -> RGB, creates textures directly
  116. let decoder_handle =
  117. spawn_decoder_thread(frame_rx, self.vid_data.clone(), self.render_api.clone());
  118. *self._load_handle.lock() = Some(loader_handle);
  119. *self._decoder_handle.lock() = Some(decoder_handle);
  120. }
  121. #[instrument(target = "ui::video")]
  122. async fn redraw(self: Arc<Self>, batch: BatchGuardPtr) {
  123. let Some(parent_rect) = self.parent_rect.lock().clone() else { return };
  124. let atom = &mut batch.spawn();
  125. let Some(draw_update) = self.get_draw_calls(atom, parent_rect).await else {
  126. error!(target: "ui:video", "Video failed to draw");
  127. return
  128. };
  129. self.render_api.replace_draw_calls(batch.id, draw_update.draw_calls);
  130. }
  131. fn regen_mesh(&self) -> MeshInfo {
  132. let rect = self.rect.get();
  133. let uv = self.uv.get();
  134. let mesh_rect = Rectangle::from([0., 0., rect.w, rect.h]);
  135. let mut mesh = MeshBuilder::new(gfxtag!("img"));
  136. mesh.draw_box(&mesh_rect, COLOR_WHITE, &uv);
  137. mesh.alloc(&self.render_api)
  138. }
  139. async fn get_draw_calls(
  140. &self,
  141. atom: &mut PropertyAtomicGuard,
  142. parent_rect: Rectangle,
  143. ) -> Option<DrawUpdate> {
  144. self.rect.eval(atom, &parent_rect).ok()?;
  145. let rect = self.rect.get();
  146. self.uv.eval(atom, &rect).ok()?;
  147. let mesh = self.regen_mesh();
  148. let (vid_data, tsubs) = {
  149. let vid_data_lock = self.vid_data.lock();
  150. let Some(vid_data) = vid_data_lock.as_ref() else {
  151. // Video not loaded yet, skip draw
  152. return None;
  153. };
  154. let tsubs = vec![vid_data.textures_sub.clone(); vid_data.textures.len()];
  155. // Clone the data before the lock is released
  156. let vid_data_clone = Av1VideoData {
  157. textures: vid_data.textures.clone(),
  158. anim: vid_data.anim.clone(),
  159. textures_pub: vid_data.textures_pub.clone(),
  160. textures_sub: vid_data.textures_sub.clone(),
  161. };
  162. (vid_data_clone, tsubs)
  163. };
  164. assert_eq!(vid_data.textures.len(), tsubs.len());
  165. let mut load_tasks = self.load_tasks.lock();
  166. load_tasks.clear();
  167. let mut loaded_n_frames = 0;
  168. let total_frames = vid_data.textures.len();
  169. for (texture_idx, (mut texture, mut tsub)) in
  170. vid_data.textures.into_iter().zip(tsubs.into_iter()).enumerate()
  171. {
  172. let vertex_buffer = mesh.vertex_buffer.clone();
  173. let index_buffer = mesh.index_buffer.clone();
  174. let Some(texture) = texture.take() else {
  175. let anim = vid_data.anim.clone();
  176. let task = self.ex.spawn(async move {
  177. while let Ok((frame_idx, texture)) = tsub.recv().await {
  178. if frame_idx != texture_idx {
  179. continue
  180. }
  181. let mesh = DrawMesh {
  182. vertex_buffer,
  183. index_buffer,
  184. texture: Some(texture),
  185. num_elements: mesh.num_elements,
  186. };
  187. let dc = DrawCall {
  188. instrs: vec![DrawInstruction::Draw(mesh)],
  189. dcs: vec![],
  190. z_index: 0,
  191. debug_str: "video",
  192. };
  193. anim.update(frame_idx, Frame::new(40, dc));
  194. break
  195. }
  196. });
  197. load_tasks.push(task);
  198. continue
  199. };
  200. let mesh = DrawMesh {
  201. vertex_buffer,
  202. index_buffer,
  203. texture: Some(texture),
  204. num_elements: mesh.num_elements,
  205. };
  206. let dc = DrawCall {
  207. instrs: vec![DrawInstruction::Draw(mesh)],
  208. dcs: vec![],
  209. z_index: 0,
  210. debug_str: "video",
  211. };
  212. vid_data.anim.update(texture_idx, Frame::new(40, dc));
  213. loaded_n_frames += 1;
  214. }
  215. debug!(target: "ui::video", "Loaded {loaded_n_frames} / {total_frames} frames");
  216. Some(DrawUpdate {
  217. key: self.dc_key,
  218. draw_calls: vec![(
  219. self.dc_key,
  220. DrawCall::new(
  221. vec![
  222. DrawInstruction::Move(rect.pos()),
  223. DrawInstruction::Animation(vid_data.anim.id),
  224. ],
  225. vec![],
  226. self.z_index.get(),
  227. "vid",
  228. ),
  229. )],
  230. })
  231. }
  232. }
  233. #[async_trait]
  234. impl UIObject for Video {
  235. fn priority(&self) -> u32 {
  236. self.priority.get()
  237. }
  238. fn init(&self) {
  239. self.load_video();
  240. }
  241. async fn start(self: Arc<Self>, ex: ExecutorPtr) {
  242. let me = Arc::downgrade(&self);
  243. let mut on_modify = OnModify::new(ex, self.node.clone(), me.clone());
  244. on_modify.when_change(self.rect.prop(), Self::redraw);
  245. on_modify.when_change(self.uv.prop(), Self::redraw);
  246. on_modify.when_change(self.z_index.prop(), Self::redraw);
  247. on_modify.when_change(self.path.prop(), Self::reload);
  248. *self.tasks.lock() = on_modify.tasks;
  249. }
  250. fn stop(&self) {
  251. self.tasks.lock().clear();
  252. *self.parent_rect.lock() = None;
  253. *self.vid_data.lock() = None;
  254. // Threads terminate naturally when channels close
  255. }
  256. #[instrument(target = "ui::video")]
  257. async fn draw(
  258. &self,
  259. parent_rect: Rectangle,
  260. atom: &mut PropertyAtomicGuard,
  261. ) -> Option<DrawUpdate> {
  262. *self.parent_rect.lock() = Some(parent_rect);
  263. self.get_draw_calls(atom, parent_rect).await
  264. }
  265. }
  266. impl Drop for Video {
  267. fn drop(&mut self) {
  268. let atom = self.render_api.make_guard(gfxtag!("Video::drop"));
  269. self.render_api.replace_draw_calls(atom.batch_id, vec![(self.dc_key, Default::default())]);
  270. }
  271. }
  272. impl std::fmt::Debug for Video {
  273. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  274. write!(f, "{:?}", self.node.upgrade().unwrap())
  275. }
  276. }