canvas-renderer 0.1.4

Custom minimal renderer for Saorsa Canvas built on wgpu. Provides GPU rendering with WebGL2/2D fallbacks.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Video texture management for streaming video content.
//!
//! This module provides types and utilities for managing video frame textures
//! that can be uploaded to the GPU for rendering. It supports:
//!
//! - Per-frame RGBA data upload
//! - Caching of video textures by stream ID
//! - Graceful handling of missing video streams

use std::collections::HashMap;

use thiserror::Error;

/// Errors that can occur during video texture operations.
#[derive(Debug, Error)]
pub enum VideoTextureError {
    /// The video frame data has invalid dimensions or size.
    #[error("Invalid video frame data: expected {expected} bytes, got {actual}")]
    InvalidFrameData {
        /// Expected byte count.
        expected: usize,
        /// Actual byte count.
        actual: usize,
    },

    /// The requested stream was not found.
    #[error("Video stream not found: {0}")]
    StreamNotFound(String),

    /// GPU texture creation failed.
    #[error("Failed to create video texture: {0}")]
    TextureCreation(String),

    /// Frame dimensions would cause integer overflow.
    #[error("Frame dimensions {width}x{height} would overflow")]
    DimensionOverflow {
        /// Width in pixels.
        width: u32,
        /// Height in pixels.
        height: u32,
    },
}

/// Result type for video texture operations.
pub type VideoTextureResult<T> = Result<T, VideoTextureError>;

/// Raw video frame data in RGBA format.
///
/// This struct holds a single frame of video data that can be uploaded
/// to a GPU texture. The data is expected to be in RGBA format with
/// 4 bytes per pixel.
///
/// # Note on Public Fields
///
/// Fields are public for zero-copy access to pixel data. Use the constructor
/// [`VideoFrameData::new`] or [`VideoFrameData::placeholder`] to create
/// validated instances. Direct modification of fields after construction
/// may violate the `width*height*4 == data.len()` invariant.
#[derive(Debug, Clone)]
pub struct VideoFrameData {
    /// Width of the frame in pixels.
    pub width: u32,
    /// Height of the frame in pixels.
    pub height: u32,
    /// RGBA pixel data (4 bytes per pixel, row-major order).
    pub data: Vec<u8>,
}

impl VideoFrameData {
    /// Calculate the expected byte size for a frame, with overflow checking.
    ///
    /// # Errors
    ///
    /// Returns an error if the dimensions would cause integer overflow.
    fn checked_frame_size(width: u32, height: u32) -> VideoTextureResult<usize> {
        (width as usize)
            .checked_mul(height as usize)
            .and_then(|pixels| pixels.checked_mul(4))
            .ok_or(VideoTextureError::DimensionOverflow { width, height })
    }

    /// Create a new video frame from RGBA data.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The dimensions would cause integer overflow
    /// - The data length doesn't match width * height * 4
    pub fn new(width: u32, height: u32, data: Vec<u8>) -> VideoTextureResult<Self> {
        let expected = Self::checked_frame_size(width, height)?;
        if data.len() != expected {
            return Err(VideoTextureError::InvalidFrameData {
                expected,
                actual: data.len(),
            });
        }

        Ok(Self {
            width,
            height,
            data,
        })
    }

    /// Create a placeholder frame with a solid color.
    ///
    /// Used when a video stream is not yet available.
    ///
    /// # Errors
    ///
    /// Returns an error if the dimensions would cause integer overflow.
    pub fn placeholder(width: u32, height: u32) -> VideoTextureResult<Self> {
        let byte_size = Self::checked_frame_size(width, height)?;
        let pixel_count = byte_size / 4;
        let mut data = Vec::with_capacity(byte_size);

        // Create a dark gray placeholder (similar to video player background)
        for _ in 0..pixel_count {
            data.extend_from_slice(&[32, 32, 32, 255]); // Dark gray
        }

        Ok(Self {
            width,
            height,
            data,
        })
    }

    /// Check if the frame dimensions are valid (non-zero).
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.width > 0 && self.height > 0 && !self.data.is_empty()
    }

    /// Get the frame width in pixels.
    #[must_use]
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Get the frame height in pixels.
    #[must_use]
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Get a reference to the RGBA pixel data.
    #[must_use]
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

/// Cached video texture entry metadata.
///
/// This struct tracks metadata about a video texture (dimensions and update time).
/// Fields are public for simple read access in the render loop.
#[derive(Debug)]
pub struct VideoTextureEntry {
    /// Width of the cached texture.
    pub width: u32,
    /// Height of the cached texture.
    pub height: u32,
    /// Last update timestamp (frame number or time).
    pub last_updated: u64,
}

impl VideoTextureEntry {
    /// Get the texture width in pixels.
    #[must_use]
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Get the texture height in pixels.
    #[must_use]
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Get the last update frame number.
    #[must_use]
    pub fn last_updated(&self) -> u64 {
        self.last_updated
    }
}

/// Manages video textures for multiple streams.
///
/// This manager tracks active video streams and their associated GPU textures.
/// It provides methods to update textures with new frame data and retrieve
/// cached textures for rendering.
///
/// # Example
///
/// ```
/// use canvas_renderer::video::{VideoTextureManager, VideoFrameData};
///
/// let mut manager = VideoTextureManager::new();
///
/// // Update a video stream with new frame data
/// let frame = VideoFrameData::placeholder(640, 480).expect("valid dimensions");
/// manager.update_texture("stream-1", &frame);
///
/// // Check if texture exists
/// if manager.has_texture("stream-1") {
///     // Render the video element
/// }
/// ```
#[derive(Debug, Default)]
pub struct VideoTextureManager {
    /// Texture metadata by stream ID.
    entries: HashMap<String, VideoTextureEntry>,
    /// Frame counter for tracking updates.
    frame_counter: u64,
}

impl VideoTextureManager {
    /// Create a new video texture manager.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: HashMap::new(),
            frame_counter: 0,
        }
    }

    /// Update or create a video texture for a stream.
    ///
    /// This method records the texture metadata. The actual GPU texture
    /// upload is handled by the wgpu backend using the frame data.
    pub fn update_texture(&mut self, stream_id: &str, frame: &VideoFrameData) {
        self.frame_counter += 1;

        self.entries.insert(
            stream_id.to_string(),
            VideoTextureEntry {
                width: frame.width,
                height: frame.height,
                last_updated: self.frame_counter,
            },
        );
    }

    /// Get texture metadata for a stream.
    #[must_use]
    pub fn get_texture(&self, stream_id: &str) -> Option<&VideoTextureEntry> {
        self.entries.get(stream_id)
    }

    /// Check if a texture exists for a stream.
    #[must_use]
    pub fn has_texture(&self, stream_id: &str) -> bool {
        self.entries.contains_key(stream_id)
    }

    /// Remove a video texture from the cache.
    ///
    /// Call this when a video stream ends or the element is removed.
    pub fn remove_texture(&mut self, stream_id: &str) -> bool {
        self.entries.remove(stream_id).is_some()
    }

    /// Clear all video textures.
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// Get the number of cached video textures.
    #[must_use]
    pub fn texture_count(&self) -> usize {
        self.entries.len()
    }

    /// Get an iterator over all stream IDs.
    pub fn stream_ids(&self) -> impl Iterator<Item = &str> {
        self.entries.keys().map(String::as_str)
    }

    /// Get the current frame counter.
    #[must_use]
    pub fn frame_counter(&self) -> u64 {
        self.frame_counter
    }
}

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

    #[test]
    fn test_video_frame_data_new() {
        // Valid frame
        let data = vec![0u8; 4 * 4 * 4]; // 4x4 RGBA
        let frame = VideoFrameData::new(4, 4, data);
        assert!(frame.is_ok());

        let frame = frame.expect("Frame should be valid");
        assert_eq!(frame.width, 4);
        assert_eq!(frame.height, 4);
        assert!(frame.is_valid());
    }

    #[test]
    fn test_video_frame_data_invalid() {
        // Wrong size
        let data = vec![0u8; 10]; // Not 4x4x4
        let frame = VideoFrameData::new(4, 4, data);
        assert!(frame.is_err());

        match frame {
            Err(VideoTextureError::InvalidFrameData { expected, actual }) => {
                assert_eq!(expected, 64);
                assert_eq!(actual, 10);
            }
            _ => panic!("Expected InvalidFrameData error"),
        }
    }

    #[test]
    fn test_video_frame_placeholder() {
        let frame = VideoFrameData::placeholder(640, 480).expect("Should create placeholder");
        assert_eq!(frame.width, 640);
        assert_eq!(frame.height, 480);
        assert_eq!(frame.data.len(), 640 * 480 * 4);
        assert!(frame.is_valid());

        // Check that it's dark gray
        assert_eq!(&frame.data[0..4], &[32, 32, 32, 255]);
    }

    #[test]
    fn test_video_frame_dimension_overflow() {
        // Test that extremely large dimensions are rejected
        let result = VideoFrameData::new(u32::MAX, u32::MAX, vec![]);
        assert!(result.is_err());

        match result {
            Err(VideoTextureError::DimensionOverflow { width, height }) => {
                assert_eq!(width, u32::MAX);
                assert_eq!(height, u32::MAX);
            }
            _ => panic!("Expected DimensionOverflow error"),
        }

        // Placeholder should also reject overflow dimensions
        let result = VideoFrameData::placeholder(u32::MAX, u32::MAX);
        assert!(matches!(
            result,
            Err(VideoTextureError::DimensionOverflow { .. })
        ));
    }

    #[test]
    fn test_video_texture_manager() {
        let mut manager = VideoTextureManager::new();

        // Initially empty
        assert_eq!(manager.texture_count(), 0);
        assert!(!manager.has_texture("stream-1"));

        // Add a texture
        let frame = VideoFrameData::placeholder(320, 240).expect("Should create placeholder");
        manager.update_texture("stream-1", &frame);

        assert_eq!(manager.texture_count(), 1);
        assert!(manager.has_texture("stream-1"));

        // Get texture metadata
        let entry = manager.get_texture("stream-1");
        assert!(entry.is_some());
        let entry = entry.expect("Entry should exist");
        assert_eq!(entry.width, 320);
        assert_eq!(entry.height, 240);
        assert_eq!(entry.last_updated, 1);

        // Update the same stream
        let frame2 = VideoFrameData::placeholder(640, 480).expect("Should create placeholder");
        manager.update_texture("stream-1", &frame2);

        let entry = manager.get_texture("stream-1").expect("Entry should exist");
        assert_eq!(entry.width, 640);
        assert_eq!(entry.height, 480);
        assert_eq!(entry.last_updated, 2);

        // Add another stream
        manager.update_texture("stream-2", &frame);
        assert_eq!(manager.texture_count(), 2);

        // Remove a texture
        assert!(manager.remove_texture("stream-1"));
        assert_eq!(manager.texture_count(), 1);
        assert!(!manager.has_texture("stream-1"));
        assert!(manager.has_texture("stream-2"));

        // Remove non-existent
        assert!(!manager.remove_texture("stream-1"));

        // Clear all
        manager.clear();
        assert_eq!(manager.texture_count(), 0);
    }

    #[test]
    fn test_video_texture_manager_stream_ids() {
        let mut manager = VideoTextureManager::new();

        let frame = VideoFrameData::placeholder(100, 100).expect("Should create placeholder");
        manager.update_texture("a", &frame);
        manager.update_texture("b", &frame);
        manager.update_texture("c", &frame);

        let mut ids: Vec<_> = manager.stream_ids().collect();
        ids.sort_unstable();
        assert_eq!(ids, vec!["a", "b", "c"]);
    }

    #[test]
    fn test_video_frame_data_getters() {
        let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
        let frame = VideoFrameData::new(2, 2, data.clone()).expect("Should create frame");

        assert_eq!(frame.width(), 2);
        assert_eq!(frame.height(), 2);
        assert_eq!(frame.data(), data.as_slice());
    }

    #[test]
    fn test_video_texture_entry_getters() {
        let mut manager = VideoTextureManager::new();
        let frame = VideoFrameData::placeholder(800, 600).expect("Should create placeholder");
        manager.update_texture("test-stream", &frame);

        let entry = manager
            .get_texture("test-stream")
            .expect("Entry should exist");
        assert_eq!(entry.width(), 800);
        assert_eq!(entry.height(), 600);
        assert_eq!(entry.last_updated(), 1);
    }

    #[test]
    fn test_video_frame_zero_dimensions() {
        // Zero width should produce empty data and be invalid
        let result = VideoFrameData::new(0, 100, vec![]);
        assert!(result.is_ok()); // Constructor succeeds but...

        let frame = result.expect("Should create frame");
        assert!(!frame.is_valid()); // ...frame is not valid

        // Zero height same
        let frame2 = VideoFrameData::new(100, 0, vec![]).expect("Should create frame");
        assert!(!frame2.is_valid());
    }

    #[test]
    fn test_video_texture_manager_frame_counter() {
        let mut manager = VideoTextureManager::new();
        assert_eq!(manager.frame_counter(), 0);

        let frame = VideoFrameData::placeholder(100, 100).expect("Should create placeholder");

        manager.update_texture("stream-1", &frame);
        assert_eq!(manager.frame_counter(), 1);

        manager.update_texture("stream-1", &frame);
        assert_eq!(manager.frame_counter(), 2);

        manager.update_texture("stream-2", &frame);
        assert_eq!(manager.frame_counter(), 3);
    }

    #[test]
    fn test_video_frame_missing_stream_behavior() {
        let manager = VideoTextureManager::new();

        // Accessing non-existent stream should return None, not panic
        assert!(manager.get_texture("nonexistent").is_none());
        assert!(!manager.has_texture("nonexistent"));
    }
}