Skip to main content

euv_core/media/codec/
impl.rs

1use super::*;
2
3/// Magic-byte detection, MIME classification, and pure-Rust decoders for all cross-platform media formats.
4impl MediaCodecRegistry {
5    /// Checks whether `haystack` starts with `prefix` using zero-allocation ASCII case folding.
6    ///
7    /// # Arguments
8    ///
9    /// - `&[u8]` - Source byte slice.
10    /// - `&[u8]` - Expected ASCII prefix bytes.
11    ///
12    /// # Returns
13    ///
14    /// - `bool` - `true` when `haystack` begins with `prefix` ignoring ASCII case.
15    #[inline(always)]
16    #[must_use]
17    fn starts_with_ignore_ascii_case(haystack: &[u8], prefix: &[u8]) -> bool {
18        haystack.len() >= prefix.len() && haystack[..prefix.len()].eq_ignore_ascii_case(prefix)
19    }
20
21    /// Checks whether `haystack` ends with `suffix` using zero-allocation ASCII case folding.
22    ///
23    /// # Arguments
24    ///
25    /// - `&[u8]` - Source byte slice.
26    /// - `&[u8]` - Expected ASCII suffix bytes.
27    ///
28    /// # Returns
29    ///
30    /// - `bool` - `true` when `haystack` ends with `suffix` ignoring ASCII case.
31    #[inline(always)]
32    #[must_use]
33    fn ends_with_ignore_ascii_case(haystack: &[u8], suffix: &[u8]) -> bool {
34        haystack.len() >= suffix.len()
35            && haystack[(haystack.len() - suffix.len())..].eq_ignore_ascii_case(suffix)
36    }
37
38    /// Checks whether `haystack` contains `needle` using zero-allocation ASCII case folding.
39    ///
40    /// # Arguments
41    ///
42    /// - `&[u8]` - Source byte slice.
43    /// - `&[u8]` - Expected ASCII substring bytes.
44    ///
45    /// # Returns
46    ///
47    /// - `bool` - `true` when `needle` occurs anywhere inside `haystack` ignoring ASCII case.
48    #[inline]
49    #[must_use]
50    fn contains_ignore_ascii_case(haystack: &[u8], needle: &[u8]) -> bool {
51        if needle.is_empty() {
52            return true;
53        }
54        if haystack.len() < needle.len() {
55            return false;
56        }
57        haystack
58            .windows(needle.len())
59            .any(|win: &[u8]| win.eq_ignore_ascii_case(needle))
60    }
61
62    /// Sniffs `MediaKind` from raw payload magic bytes first, falling back to `uri` extension without heap allocations.
63    ///
64    /// # Arguments
65    ///
66    /// - `&str` - Source URI or filename.
67    /// - `&[u8]` - Optional leading raw bytes.
68    ///
69    /// # Returns
70    ///
71    /// - `MediaKind` - Detected high-level media type.
72    #[must_use]
73    pub fn detect_media_kind(uri: &str, bytes: &[u8]) -> MediaKind {
74        if bytes.starts_with(MAGIC_PDF) {
75            return MediaKind::Pdf;
76        }
77        if bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A) {
78            return MediaKind::AnimatedGif;
79        }
80        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WAVE {
81            return MediaKind::Audio;
82        }
83        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WEBP {
84            return MediaKind::Image;
85        }
86        let is_png_or_jpg: bool =
87            bytes.starts_with(MAGIC_PNG) || bytes.starts_with(&[0xFF, 0xD8, 0xFF]);
88        if is_png_or_jpg || bytes.starts_with(MAGIC_BMP) {
89            return MediaKind::Image;
90        }
91        if bytes.starts_with(MAGIC_ID3)
92            || (bytes.len() >= 2 && bytes[0] == 0xFF && (bytes[1] & 0xE0) == 0xE0)
93        {
94            return MediaKind::Audio;
95        }
96        if bytes.len() >= 8 && &bytes[4..8] == MAGIC_FTYP {
97            return MediaKind::Video;
98        }
99        if let Ok(text) = from_utf8(bytes) {
100            let trimmed: &[u8] = text.trim_start().as_bytes();
101            let head: &[u8] = &trimmed[..trimmed.len().min(32)];
102            if Self::starts_with_ignore_ascii_case(head, TAG_SVG_OPEN.as_bytes())
103                || Self::contains_ignore_ascii_case(head, TAG_SVG_SPACE)
104            {
105                return MediaKind::Svg;
106            }
107            let is_doc_or_html: bool = Self::starts_with_ignore_ascii_case(head, TAG_DOCTYPE_HTML)
108                || Self::starts_with_ignore_ascii_case(head, TAG_HTML_OPEN);
109            let is_art_or_div: bool = Self::starts_with_ignore_ascii_case(head, TAG_ARTICLE_OPEN)
110                || Self::starts_with_ignore_ascii_case(head, TAG_DIV_OPEN);
111            if is_doc_or_html || is_art_or_div {
112                return MediaKind::Html;
113            }
114        }
115        let uri_b: &[u8] = uri.as_bytes();
116        if Self::ends_with_ignore_ascii_case(uri_b, EXT_GIF.as_bytes()) {
117            return MediaKind::AnimatedGif;
118        }
119        if Self::ends_with_ignore_ascii_case(uri_b, EXT_LIVE_BYTES)
120            || Self::ends_with_ignore_ascii_case(uri_b, EXT_LIVP_BYTES)
121        {
122            return MediaKind::LivePhoto;
123        }
124        let vid_a: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_MP4_BYTES)
125            || Self::ends_with_ignore_ascii_case(uri_b, EXT_MOV_BYTES);
126        let vid_b: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_WEBM_BYTES)
127            || Self::ends_with_ignore_ascii_case(uri_b, EXT_MKV_BYTES);
128        if vid_a || vid_b {
129            return MediaKind::Video;
130        }
131        let aud_a: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_WAV_BYTES)
132            || Self::ends_with_ignore_ascii_case(uri_b, EXT_MP3_BYTES);
133        let aud_b: bool = Self::ends_with_ignore_ascii_case(uri_b, EXT_AAC_BYTES)
134            || Self::ends_with_ignore_ascii_case(uri_b, EXT_OGG_BYTES);
135        let aud_ab: bool = aud_a || aud_b;
136        if aud_ab || Self::ends_with_ignore_ascii_case(uri_b, EXT_FLAC_BYTES) {
137            return MediaKind::Audio;
138        }
139        if Self::ends_with_ignore_ascii_case(uri_b, EXT_PDF_BYTES) {
140            return MediaKind::Pdf;
141        }
142        if Self::ends_with_ignore_ascii_case(uri_b, EXT_HTML_BYTES)
143            || Self::ends_with_ignore_ascii_case(uri_b, EXT_HTM_BYTES)
144        {
145            return MediaKind::Html;
146        }
147        if Self::ends_with_ignore_ascii_case(uri_b, EXT_SVG.as_bytes()) {
148            return MediaKind::Svg;
149        }
150        MediaKind::Image
151    }
152
153    /// Detects the encoded `ImageFormat` from leading magic bytes or filename extension without heap allocations.
154    ///
155    /// # Arguments
156    ///
157    /// - `&str` - Source URI or filename.
158    /// - `&[u8]` - Optional leading bytes.
159    ///
160    /// # Returns
161    ///
162    /// - `ImageFormat` - Resolved image format.
163    #[must_use]
164    pub fn detect_image_format(uri: &str, bytes: &[u8]) -> ImageFormat {
165        if bytes.starts_with(MAGIC_PNG) {
166            return ImageFormat::Png;
167        }
168        if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
169            return ImageFormat::Jpeg;
170        }
171        if bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A) {
172            return ImageFormat::Gif;
173        }
174        if bytes.starts_with(MAGIC_BMP) {
175            return ImageFormat::Bmp;
176        }
177        if bytes.len() >= 12 && &bytes[0..4] == MAGIC_RIFF && &bytes[8..12] == MAGIC_WEBP {
178            return ImageFormat::WebP;
179        }
180        let uri_b: &[u8] = uri.as_bytes();
181        if Self::ends_with_ignore_ascii_case(uri_b, EXT_JPG_BYTES)
182            || Self::ends_with_ignore_ascii_case(uri_b, EXT_JPEG_BYTES)
183        {
184            ImageFormat::Jpeg
185        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_WEBP_BYTES) {
186            ImageFormat::WebP
187        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_GIF.as_bytes()) {
188            ImageFormat::Gif
189        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_BMP_BYTES) {
190            ImageFormat::Bmp
191        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_SVG.as_bytes()) {
192            ImageFormat::Svg
193        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_HEIC_BYTES)
194            || Self::ends_with_ignore_ascii_case(uri_b, EXT_HEIF_BYTES)
195        {
196            ImageFormat::Heic
197        } else if Self::ends_with_ignore_ascii_case(uri_b, EXT_AVIF_BYTES) {
198            ImageFormat::Avif
199        } else {
200            ImageFormat::Png
201        }
202    }
203
204    /// Decodes an uncompressed 24-bit or 32-bit Windows BMP byte slice into an `ImageAsset`.
205    ///
206    /// # Arguments
207    ///
208    /// - `&[u8]` - Raw `.bmp` file bytes.
209    /// - `&str` - Accessibility alt text.
210    ///
211    /// # Returns
212    ///
213    /// - `Result<ImageAsset, String>` - Decoded `ImageAsset` or format error message.
214    pub fn decode_bmp(bytes: &[u8], alt_text: &str) -> Result<ImageAsset, String> {
215        if bytes.len() < 54 || &bytes[0..2] != MAGIC_BMP {
216            return Err("invalid BMP header".to_string());
217        }
218        let data_offset: usize =
219            u32::from_le_bytes([bytes[10], bytes[11], bytes[12], bytes[13]]) as usize;
220        let width_i: i32 = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]);
221        let height_i: i32 = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]);
222        let bpp: u16 = u16::from_le_bytes([bytes[28], bytes[29]]);
223        let compression: u32 = u32::from_le_bytes([bytes[30], bytes[31], bytes[32], bytes[33]]);
224        let bad_dims: bool = width_i <= 0 || height_i == 0;
225        let bad_fmt: bool = compression != 0 || (bpp != 24 && bpp != 32);
226        if bad_dims || bad_fmt {
227            return Err(
228                "unsupported BMP pixel layout (expected uncompressed 24/32bpp)".to_string(),
229            );
230        }
231        let width: u32 = width_i as u32;
232        let height: u32 = height_i.unsigned_abs();
233        let w_usize: usize = width as usize;
234        let h_usize: usize = height as usize;
235        let top_down: bool = height_i < 0;
236        let bytes_per_pixel: usize = (bpp / 8) as usize;
237        let row_stride: usize = (w_usize * bytes_per_pixel + 3) & !3;
238        let needed: usize = data_offset.saturating_add(row_stride.saturating_mul(h_usize));
239        if bytes.len() < needed {
240            return Err("truncated BMP pixel payload".to_string());
241        }
242        let total_bytes: usize = w_usize * h_usize * 4;
243        let mut rgba: Vec<u8> = Vec::with_capacity(total_bytes);
244        let dst_ptr: *mut u8 = rgba.as_mut_ptr();
245        let dst_row_bytes: usize = w_usize * 4;
246        if bytes_per_pixel == 4 {
247            let src_row_bytes: usize = w_usize * 4;
248            for pos_y in 0..h_usize {
249                let src_y: usize = if top_down { pos_y } else { h_usize - 1 - pos_y };
250                let src_off: usize = data_offset + src_y * row_stride;
251                let src_slice: &[u8] = &bytes[src_off..(src_off + src_row_bytes)];
252                let dst_row_off: usize = pos_y * dst_row_bytes;
253                for (pos_x, px) in src_slice.as_chunks::<4>().0.iter().enumerate() {
254                    // SAFETY: `dst_row_off + x * 4 + 4 <= total_bytes <= rgba.capacity()`, `[u8; 4]` align is 1.
255                    unsafe {
256                        dst_ptr
257                            .add(dst_row_off + pos_x * 4)
258                            .cast::<[u8; 4]>()
259                            .write([px[2], px[1], px[0], px[3]]);
260                    }
261                }
262            }
263        } else {
264            let src_row_bytes: usize = w_usize * 3;
265            for coord_y in 0..h_usize {
266                let src_y: usize = if top_down {
267                    coord_y
268                } else {
269                    h_usize - 1 - coord_y
270                };
271                let src_off: usize = data_offset + src_y * row_stride;
272                let src_slice: &[u8] = &bytes[src_off..(src_off + src_row_bytes)];
273                let dst_row_off: usize = coord_y * dst_row_bytes;
274                for (coord_x, px) in src_slice.as_chunks::<3>().0.iter().enumerate() {
275                    // SAFETY: `dst_row_off + x * 4 + 4 <= total_bytes <= rgba.capacity()`, `[u8; 4]` align is 1.
276                    unsafe {
277                        dst_ptr
278                            .add(dst_row_off + coord_x * 4)
279                            .cast::<[u8; 4]>()
280                            .write([px[2], px[1], px[0], 255]);
281                    }
282                }
283            }
284        }
285        // SAFETY: Both branches unconditionally initialize all `h_usize * w_usize * 4 == total_bytes` bytes.
286        unsafe {
287            rgba.set_len(total_bytes);
288        }
289        let meta: MediaMetadata = MediaMetadata {
290            title: alt_text.to_string(),
291            width,
292            height,
293            duration_secs: 0.0,
294            page_count: 1,
295            frame_count: 1,
296            sample_rate_hz: 0,
297            channels: 0,
298            format_label: "BMP".to_string(),
299        };
300        Ok(ImageAsset {
301            format: ImageFormat::Bmp,
302            buffer: ImageBuffer::new(width, height, rgba),
303            alt_text: alt_text.to_string(),
304            metadata: meta,
305        })
306    }
307
308    /// Decodes a real PNG byte stream into an `ImageAsset` using the pure-Rust PNG codec.
309    ///
310    /// # Arguments
311    ///
312    /// - `&[u8]` - Raw `.png` file bytes.
313    /// - `&str` - Accessibility alt text.
314    ///
315    /// # Returns
316    ///
317    /// - `Result<ImageAsset, String>` - Decoded `ImageAsset` or parse/decompression error.
318    pub fn decode_png(bytes: &[u8], alt_text: &str) -> Result<ImageAsset, String> {
319        let decoded: DecodedRgbaImage = decode_png_rgba(bytes)?;
320        let width: u32 = decoded.get_width();
321        let height: u32 = decoded.get_height();
322        let meta: MediaMetadata = MediaMetadata {
323            title: alt_text.to_string(),
324            width,
325            height,
326            duration_secs: 0.0,
327            page_count: 1,
328            frame_count: 1,
329            sample_rate_hz: 0,
330            channels: 0,
331            format_label: FORMAT_LABEL_PNG.to_string(),
332        };
333        Ok(ImageAsset {
334            format: ImageFormat::Png,
335            buffer: decoded.into_image_buffer(),
336            alt_text: alt_text.to_string(),
337            metadata: meta,
338        })
339    }
340
341    /// Decodes a real Baseline JPEG byte stream into an `ImageAsset` using the pure-Rust JPEG codec.
342    ///
343    /// # Arguments
344    ///
345    /// - `&[u8]` - Raw `.jpg` / `.jpeg` file bytes.
346    /// - `&str` - Accessibility alt text.
347    ///
348    /// # Returns
349    ///
350    /// - `Result<ImageAsset, String>` - Decoded `ImageAsset` or parse/decode error.
351    pub fn decode_jpeg(bytes: &[u8], alt_text: &str) -> Result<ImageAsset, String> {
352        let decoded: DecodedRgbaImage = decode_jpeg_rgba(bytes)?;
353        let width: u32 = decoded.get_width();
354        let height: u32 = decoded.get_height();
355        let meta: MediaMetadata = MediaMetadata {
356            title: alt_text.to_string(),
357            width,
358            height,
359            duration_secs: 0.0,
360            page_count: 1,
361            frame_count: 1,
362            sample_rate_hz: 0,
363            channels: 0,
364            format_label: FORMAT_LABEL_JPEG.to_string(),
365        };
366        Ok(ImageAsset {
367            format: ImageFormat::Jpeg,
368            buffer: decoded.into_image_buffer(),
369            alt_text: alt_text.to_string(),
370            metadata: meta,
371        })
372    }
373
374    /// Auto-detects and decodes PNG, JPEG, BMP, Radiance HDR, or OpenEXR bytes into an `ImageAsset`.
375    ///
376    /// # Arguments
377    ///
378    /// - `&[u8]` - Raw image file bytes.
379    /// - `&str` - Accessibility alt text.
380    ///
381    /// # Returns
382    ///
383    /// - `Result<ImageAsset, String>` - Decoded `ImageAsset` or format error.
384    pub fn decode_image(bytes: &[u8], alt_text: &str) -> Result<ImageAsset, String> {
385        if bytes.starts_with(MAGIC_PNG) {
386            return Self::decode_png(bytes, alt_text);
387        }
388        if bytes.len() >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF {
389            return Self::decode_jpeg(bytes, alt_text);
390        }
391        if bytes.starts_with(MAGIC_BMP) {
392            return Self::decode_bmp(bytes, alt_text);
393        }
394        if let Ok(decoded) = decode_raster_image_rgba(bytes) {
395            let width: u32 = decoded.get_width();
396            let height: u32 = decoded.get_height();
397            let meta: MediaMetadata = MediaMetadata {
398                title: alt_text.to_string(),
399                width,
400                height,
401                duration_secs: 0.0,
402                page_count: 1,
403                frame_count: 1,
404                sample_rate_hz: 0,
405                channels: 0,
406                format_label: FORMAT_LABEL_HDR.to_string(),
407            };
408            return Ok(ImageAsset {
409                format: ImageFormat::Png,
410                buffer: decoded.into_image_buffer(),
411                alt_text: alt_text.to_string(),
412                metadata: meta,
413            });
414        }
415        Err(ERR_DECODE_IMAGE_UNSUPPORTED.to_string())
416    }
417
418    /// Decodes a real GIF87a/GIF89a byte stream using full LZW decompression, palettes, de-interlacing, transparency, and all 4 disposal methods.
419    ///
420    /// # Arguments
421    ///
422    /// - `&[u8]` - Raw `.gif` file bytes.
423    /// - `&str` - Asset title.
424    ///
425    /// # Returns
426    ///
427    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` with exact source dimensions or parse/decode error.
428    pub fn decode_gif(bytes: &[u8], title: &str) -> Result<GifAnimation, String> {
429        Self::decode_gif_with_config(bytes, title, GifDecodeConfig::default())
430    }
431
432    /// Decodes a GIF87a/GIF89a byte stream using explicit `GifDecodeConfig` memory budgets and frame-delay compatibility settings.
433    ///
434    /// # Arguments
435    ///
436    /// - `&[u8]` - Raw `.gif` file bytes.
437    /// - `&str` - Asset title.
438    /// - `GifDecodeConfig` - Canvas/cache byte budget and frame-delay compatibility policy.
439    ///
440    /// # Returns
441    ///
442    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` or parse/decode error.
443    pub fn decode_gif_with_config(
444        bytes: &[u8],
445        title: &str,
446        config: GifDecodeConfig,
447    ) -> Result<GifAnimation, String> {
448        let decoder: GifDecoder = GifDecoder::parse_with_config(bytes, config)?;
449        decoder.decode_all_animation(title)
450    }
451
452    /// Decodes a RIFF PCM WAV audio byte slice (8-bit or 16-bit) into a normalized `AudioTrack` with waveform peaks.
453    ///
454    /// # Arguments
455    ///
456    /// - `&[u8]` - Raw `.wav` bytes.
457    /// - `&str` - Track title.
458    ///
459    /// # Returns
460    ///
461    /// - `Result<AudioTrack, String>` - Decoded `AudioTrack` or format error.
462    pub fn decode_wav(bytes: &[u8], title: &str) -> Result<AudioTrack, String> {
463        let bad_riff: bool = bytes.len() < 44 || &bytes[0..4] != MAGIC_RIFF;
464        if bad_riff || &bytes[8..12] != MAGIC_WAVE {
465            return Err("invalid RIFF WAVE header".to_string());
466        }
467        let mut cursor: usize = 12;
468        let mut channels: u16 = 1;
469        let mut sample_rate: u32 = 44_100;
470        let mut bits_per_sample: u16 = 16;
471        let mut pcm_bytes: &[u8] = &[];
472        while cursor + 8 <= bytes.len() {
473            let chunk_id: &[u8] = &bytes[cursor..cursor + 4];
474            let chunk_size: usize = u32::from_le_bytes([
475                bytes[cursor + 4],
476                bytes[cursor + 5],
477                bytes[cursor + 6],
478                bytes[cursor + 7],
479            ]) as usize;
480            let body_start: usize = cursor + 8;
481            let body_end: usize = body_start.saturating_add(chunk_size).min(bytes.len());
482            if chunk_id == MAGIC_WAV_FMT && body_end - body_start >= 16 {
483                channels =
484                    u16::from_le_bytes([bytes[body_start + 2], bytes[body_start + 3]]).max(1);
485                sample_rate = u32::from_le_bytes([
486                    bytes[body_start + 4],
487                    bytes[body_start + 5],
488                    bytes[body_start + 6],
489                    bytes[body_start + 7],
490                ])
491                .max(8_000);
492                bits_per_sample =
493                    u16::from_le_bytes([bytes[body_start + 14], bytes[body_start + 15]]);
494            } else if chunk_id == MAGIC_WAV_DATA {
495                pcm_bytes = &bytes[body_start..body_end];
496            }
497            let padded: usize = chunk_size + (chunk_size & 1);
498            cursor = body_start.saturating_add(padded);
499        }
500        if pcm_bytes.is_empty() {
501            return Err("WAV file contained no data chunk".to_string());
502        }
503        let samples: Vec<f32> = if bits_per_sample == 16 {
504            let inv_scale: f32 = 1.0 / 32_768.0;
505            let chunks: &[[u8; 2]] = pcm_bytes.as_chunks::<2>().0;
506            let mut out: Vec<f32> = Vec::with_capacity(chunks.len());
507            for pair in chunks.iter() {
508                let source_val: i16 = i16::from_le_bytes(*pair);
509                out.push((source_val as f32) * inv_scale);
510            }
511            out
512        } else if bits_per_sample == 8 {
513            let inv_scale: f32 = 1.0 / 128.0;
514            let mut out: Vec<f32> = Vec::with_capacity(pcm_bytes.len());
515            for blue_val in pcm_bytes.iter().copied() {
516                out.push(((blue_val as f32) - 128.0) * inv_scale);
517            }
518            out
519        } else {
520            return Err("unsupported WAV bit depth (expected 8 or 16 bit PCM)".to_string());
521        };
522        let frames_total: usize = samples.len() / (channels as usize).max(1);
523        let duration_secs: f32 = (frames_total as f32) / (sample_rate as f32).max(1.0);
524        let waveform_peaks: Vec<f32> = Self::compute_waveform_peaks(&samples, 48);
525        Ok(AudioTrack {
526            metadata: MediaMetadata {
527                title: title.to_string(),
528                width: 0,
529                height: 0,
530                duration_secs,
531                page_count: 1,
532                frame_count: frames_total,
533                sample_rate_hz: sample_rate,
534                channels,
535                format_label: format!(
536                    "WAV · {:.1} kHz · {}",
537                    (sample_rate as f32) / 1000.0,
538                    if channels == 1 { "Mono" } else { "Stereo" }
539                ),
540            },
541            codec: AudioCodec::Wav,
542            samples,
543            waveform_peaks,
544            state: PlaybackState::Idle,
545            current_time_secs: 0.0,
546            volume: 0.85,
547            muted: false,
548            playback_rate: 1.0,
549            looping: true,
550        })
551    }
552
553    /// Parses a `%PDF-1.x` byte stream extracting version, info dictionary metadata, page count, and `Tj`/`TJ` text runs.
554    ///
555    /// # Arguments
556    ///
557    /// - `&[u8]` - Raw `.pdf` document bytes.
558    ///
559    /// # Returns
560    ///
561    /// - `Result<PdfDocument, String>` - Structured multi-page `PdfDocument` or format error.
562    pub fn parse_pdf(bytes: &[u8]) -> Result<PdfDocument, String> {
563        if bytes.len() < 8 || !bytes.starts_with(MAGIC_PDF) {
564            return Err("invalid PDF signature (expected %PDF-)".to_string());
565        }
566        let text: String = String::from_utf8_lossy(bytes).into_owned();
567        let version: String = text
568            .lines()
569            .next()
570            .and_then(|line: &str| line.strip_prefix(PREFIX_PDF))
571            .map(|text_value: &str| text_value.trim().to_string())
572            .filter(|label_str: &String| !label_str.is_empty())
573            .unwrap_or_else(|| "1.7".to_string());
574        let title: String = Self::extract_pdf_dict_string(&text, "/Title")
575            .unwrap_or_else(|| "Untitled PDF Document".to_string());
576        let author: String =
577            Self::extract_pdf_dict_string(&text, "/Author").unwrap_or_else(|| "euv".to_string());
578        let mut extracted_runs: Vec<String> = Vec::new();
579        let raw_bytes: &[u8] = text.as_bytes();
580        let mut item_index: usize = 0;
581        while item_index < raw_bytes.len() {
582            if raw_bytes[item_index] == BYTE_PAREN_OPEN {
583                let start: usize = item_index + 1;
584                let mut inner_index: usize = start;
585                let mut depth: i32 = 1;
586                while inner_index < raw_bytes.len() && depth > 0 {
587                    if raw_bytes[inner_index] == b'\\' && inner_index + 1 < raw_bytes.len() {
588                        inner_index += 2;
589                        continue;
590                    }
591                    if raw_bytes[inner_index] == BYTE_PAREN_OPEN {
592                        depth += 1;
593                    } else if raw_bytes[inner_index] == BYTE_PAREN_CLOSE {
594                        depth -= 1;
595                        if depth == 0 {
596                            break;
597                        }
598                    }
599                    inner_index += 1;
600                }
601                let tail: &str = text.get(inner_index..).unwrap_or("");
602                let trimmed_tail: &str = tail.trim_start_matches(')').trim_start();
603                if trimmed_tail.starts_with("Tj") || trimmed_tail.starts_with("] TJ") {
604                    let run: String = text[start..inner_index]
605                        .replace("\\(", "(")
606                        .replace("\\)", ")")
607                        .replace("\\\\", "\\")
608                        .trim()
609                        .to_string();
610                    if !run.is_empty() {
611                        extracted_runs.push(run);
612                    }
613                }
614                item_index = inner_index.saturating_add(1);
615            } else {
616                item_index += 1;
617            }
618        }
619        let declared_pages: usize = text
620            .matches("/Type /Page")
621            .count()
622            .saturating_sub(text.matches("/Type /Pages").count())
623            .max(1);
624        let mut pages: Vec<PdfPage> = Vec::with_capacity(declared_pages);
625        let per_page: usize = extracted_runs.len().div_ceil(declared_pages).max(1);
626        for p_idx in 0..declared_pages {
627            let start: usize = p_idx.saturating_mul(per_page);
628            let end: usize = start.saturating_add(per_page).min(extracted_runs.len());
629            let mut blocks: Vec<String> = if start < end {
630                extracted_runs[start..end].to_vec()
631            } else {
632                Vec::new()
633            };
634            if blocks.is_empty() {
635                blocks.push(format!(
636                    "Page {} content stream parsed from PDF {version}.",
637                    p_idx + 1
638                ));
639            }
640            let page_title: String = blocks
641                .first()
642                .cloned()
643                .unwrap_or_else(|| format!("Page {}", p_idx + 1));
644            pages.push(PdfPage {
645                page_number: p_idx + 1,
646                width_pt: 595.0,
647                height_pt: 842.0,
648                title: page_title,
649                text_blocks: blocks,
650                preview_image: None,
651            });
652        }
653        Ok(PdfDocument {
654            title,
655            author,
656            version,
657            pages,
658            current_page: 0,
659            zoom: 1.0,
660        })
661    }
662
663    /// Parses raw HTML5 markup into a sanitized, zero-JS `HtmlDocument` ready for native `euv` rendering.
664    ///
665    /// # Arguments
666    ///
667    /// - `&str` - Raw HTML markup string.
668    ///
669    /// # Returns
670    ///
671    /// - `HtmlDocument` - Parsed document title, links count, and ordered `HtmlBlock` items.
672    #[must_use]
673    pub fn parse_html(raw: &str) -> HtmlDocument {
674        let mut title: String = String::new();
675        let mut blocks: Vec<HtmlBlock> = Vec::new();
676        let mut links_count: usize = 0;
677        let bytes: &[u8] = raw.as_bytes();
678        let mut item_index: usize = 0;
679        let mut current_kind: Option<HtmlNodeKind> = None;
680        let mut current_href: Option<String> = None;
681        let mut in_title: bool = false;
682        let mut in_script_or_style: bool = false;
683        let mut buf: String = String::new();
684        while item_index < bytes.len() {
685            if bytes[item_index] == BYTE_ANGLE_OPEN {
686                let text_chunk: String = Self::decode_html_entities(buf.trim());
687                buf.clear();
688                if !text_chunk.is_empty() && !in_script_or_style {
689                    if in_title {
690                        title = text_chunk;
691                    } else {
692                        let kind: HtmlNodeKind = current_kind.unwrap_or(HtmlNodeKind::Paragraph);
693                        if kind == HtmlNodeKind::Link {
694                            links_count += 1;
695                        }
696                        blocks.push(HtmlBlock {
697                            kind,
698                            text: text_chunk,
699                            href: current_href.clone(),
700                            src: None,
701                        });
702                    }
703                }
704                let Some(close_rel) = raw[item_index..].find('>') else {
705                    break;
706                };
707                let tag_inner: &str = raw[item_index + 1..item_index + close_rel].trim();
708                let tag_b: &[u8] = tag_inner.as_bytes();
709                if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_SCRIPT)
710                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_STYLE)
711                {
712                    in_script_or_style = true;
713                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_SCRIPT)
714                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_STYLE)
715                {
716                    in_script_or_style = false;
717                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_TITLE) {
718                    in_title = true;
719                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_TITLE) {
720                    in_title = false;
721                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_HR) {
722                    blocks.push(HtmlBlock {
723                        kind: HtmlNodeKind::HorizontalRule,
724                        text: String::new(),
725                        href: None,
726                        src: None,
727                    });
728                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_IMG) {
729                    let src_val: Option<String> = Self::extract_html_attr(tag_inner, "src");
730                    let alt_val: String = Self::extract_html_attr(tag_inner, "alt")
731                        .unwrap_or_else(|| "Embedded Image".to_string());
732                    blocks.push(HtmlBlock {
733                        kind: HtmlNodeKind::Image,
734                        text: alt_val,
735                        href: None,
736                        src: src_val,
737                    });
738                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H1) {
739                    current_kind = Some(HtmlNodeKind::Heading(1));
740                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H2) {
741                    current_kind = Some(HtmlNodeKind::Heading(2));
742                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H3) {
743                    current_kind = Some(HtmlNodeKind::Heading(3));
744                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_BLOCKQUOTE) {
745                    current_kind = Some(HtmlNodeKind::Blockquote);
746                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_PRE)
747                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CODE)
748                {
749                    current_kind = Some(HtmlNodeKind::CodeBlock);
750                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_LI) {
751                    current_kind = Some(HtmlNodeKind::ListItem);
752                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_A_SPACE)
753                    || tag_b.eq_ignore_ascii_case(HTML_TAG_A)
754                {
755                    current_kind = Some(HtmlNodeKind::Link);
756                    current_href = Self::extract_html_attr(tag_inner, "href");
757                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_P_SPACE)
758                    || tag_b.eq_ignore_ascii_case(HTML_TAG_P)
759                {
760                    current_kind = Some(HtmlNodeKind::Paragraph);
761                } else if tag_b.starts_with(HTML_TAG_CLOSE_PREFIX) {
762                    current_kind = None;
763                    current_href = None;
764                }
765                item_index += close_rel + 1;
766            } else {
767                let ch: char = raw[item_index..].chars().next().unwrap_or(' ');
768                buf.push(ch);
769                item_index += ch.len_utf8();
770            }
771        }
772        let trailing: String = Self::decode_html_entities(buf.trim());
773        if !trailing.is_empty() && !in_script_or_style {
774            blocks.push(HtmlBlock {
775                kind: current_kind.unwrap_or(HtmlNodeKind::Paragraph),
776                text: trailing,
777                href: current_href,
778                src: None,
779            });
780        }
781        if title.is_empty() {
782            title = blocks
783                .iter()
784                .find(|blue_val: &&HtmlBlock| {
785                    matches!(blue_val.get_kind(), HtmlNodeKind::Heading(_))
786                })
787                .map(|byte_val: &HtmlBlock| byte_val.get_text().clone())
788                .unwrap_or_else(|| "HTML Document".to_string());
789        }
790        HtmlDocument {
791            title,
792            raw_html: raw.to_string(),
793            blocks,
794            links_count,
795        }
796    }
797
798    /// Parses an SVG document (`<svg>`, `<rect>`, `<circle>`, `<line>`) and rasterizes it into an `ImageBuffer`.
799    ///
800    /// # Arguments
801    ///
802    /// - `&str` - Raw SVG XML source.
803    /// - `u32` - Target rasterization width in pixels.
804    /// - `u32` - Target rasterization height in pixels.
805    /// - `f32` - Display scale factor.
806    ///
807    /// # Returns
808    ///
809    /// - `Result<SvgDocument, String>` - Parsed and rasterized `SvgDocument` or error.
810    pub fn parse_and_rasterize_svg_scaled(
811        raw_svg: &str,
812        logical_width: u32,
813        logical_height: u32,
814        scale_factor: f32,
815    ) -> Result<SvgDocument, String> {
816        let clamped_scale: f32 = if scale_factor.is_finite() {
817            scale_factor.clamp(1.0, 4.0)
818        } else {
819            1.0
820        };
821        let scaled_width: u32 = ((logical_width.max(1) as f32) * clamped_scale).round() as u32;
822        let scaled_height: u32 = ((logical_height.max(1) as f32) * clamped_scale).round() as u32;
823        Self::parse_and_rasterize_svg(raw_svg, scaled_width, scaled_height)
824    }
825
826    /// Parses and rasterizes a subset of vector SVG tags into an RGBA `SvgDocument` up to `2048x2048` physical pixels.
827    ///
828    /// # Arguments
829    ///
830    /// - `&str` - Raw SVG XML string.
831    /// - `u32` - Target raster width in physical pixels.
832    /// - `u32` - Target raster height in physical pixels.
833    ///
834    /// # Returns
835    ///
836    /// - `Result<SvgDocument, String>` - Parsed and rasterized `SvgDocument` or error.
837    pub fn parse_and_rasterize_svg(
838        raw_svg: &str,
839        out_w: u32,
840        out_h: u32,
841    ) -> Result<SvgDocument, String> {
842        if !raw_svg.contains(TAG_SVG_OPEN) {
843            return Err("invalid SVG document (missing <svg> root)".to_string());
844        }
845        let width_val: u32 = out_w.clamp(16, 2048);
846        let height_val: u32 = out_h.clamp(16, 2048);
847        let mut vb_w: f32 = width_val as f32;
848        let mut vb_h: f32 = height_val as f32;
849        if let Some(vb_str) = Self::extract_html_attr(raw_svg, "viewBox") {
850            let nums: Vec<f32> = vb_str
851                .split_whitespace()
852                .filter_map(|text_value: &str| text_value.parse::<f32>().ok())
853                .collect();
854            if nums.len() >= 4 {
855                vb_w = nums[2].max(1.0);
856                vb_h = nums[3].max(1.0);
857            }
858        }
859        let scale_x: f32 = (width_val as f32) / vb_w;
860        let scale_y: f32 = (height_val as f32) / vb_h;
861        let mut pixels: Vec<u8> = vec![0; (width_val as usize) * (height_val as usize) * 4];
862        let mut primitive_count: usize = 0;
863        let mut cursor: usize = 0;
864        while let Some(open_rel) = raw_svg[cursor..].find('<') {
865            let start: usize = cursor + open_rel;
866            let Some(close_rel) = raw_svg[start..].find('>') else {
867                break;
868            };
869            let tag: &str = raw_svg[start + 1..start + close_rel].trim();
870            cursor = start + close_rel + 1;
871            if tag.starts_with("rect") {
872                let pos_x: f32 = Self::attr_f32(tag, "x", 0.0) * scale_x;
873                let pos_y: f32 = Self::attr_f32(tag, "y", 0.0) * scale_y;
874                let rw: f32 = Self::attr_f32(tag, "width", vb_w) * scale_x;
875                let rh: f32 = Self::attr_f32(tag, "height", vb_h) * scale_y;
876                let col: Color = Self::parse_hex_color(
877                    Self::extract_html_attr(tag, "fill")
878                        .as_deref()
879                        .unwrap_or("#0F172A"),
880                );
881                Self::fill_rect_rgba(
882                    &mut pixels,
883                    width_val,
884                    height_val,
885                    Rect::new(pos_x, pos_y, rw, rh),
886                    col,
887                );
888                primitive_count += 1;
889            } else if tag.starts_with("circle") {
890                let cx: f32 = Self::attr_f32(tag, "cx", vb_w * 0.5) * scale_x;
891                let cy: f32 = Self::attr_f32(tag, "cy", vb_h * 0.5) * scale_y;
892                let red_val: f32 = Self::attr_f32(tag, "r", 16.0) * scale_x.min(scale_y);
893                let col: Color = Self::parse_hex_color(
894                    Self::extract_html_attr(tag, "fill")
895                        .as_deref()
896                        .unwrap_or("#38BDF8"),
897                );
898                Self::fill_circle_rgba(&mut pixels, width_val, height_val, cx, cy, red_val, col);
899                primitive_count += 1;
900            } else if tag.starts_with("line") {
901                let x1: f32 = Self::attr_f32(tag, "x1", 0.0) * scale_x;
902                let y1: f32 = Self::attr_f32(tag, "y1", 0.0) * scale_y;
903                let x2: f32 = Self::attr_f32(tag, "x2", vb_w) * scale_x;
904                let y2: f32 = Self::attr_f32(tag, "y2", vb_h) * scale_y;
905                let stroke_width_px: f32 =
906                    (Self::attr_f32(tag, "stroke-width", 1.0) * scale_x.min(scale_y)).max(1.0);
907                let col: Color = Self::parse_hex_color(
908                    Self::extract_html_attr(tag, "stroke")
909                        .as_deref()
910                        .unwrap_or("#FFFFFF"),
911                );
912                Self::draw_line_thick_rgba(
913                    &mut pixels,
914                    width_val,
915                    height_val,
916                    Point::new(x1, y1),
917                    Point::new(x2, y2),
918                    stroke_width_px,
919                    col,
920                );
921                primitive_count += 1;
922            }
923        }
924        Ok(SvgDocument {
925            view_box_width: vb_w,
926            view_box_height: vb_h,
927            raw_svg: raw_svg.to_string(),
928            rasterized: ImageBuffer::new(width_val, height_val, pixels),
929            primitive_count,
930        })
931    }
932
933    /// Computes normalized RMS waveform bar peaks (`0.08..=1.0`) from PCM samples.
934    ///
935    /// # Arguments
936    ///
937    /// - `&[f32]` - Input PCM samples.
938    /// - `usize` - Number of output bars.
939    ///
940    /// # Returns
941    ///
942    /// - `Vec<f32>` - Normalized bar peak heights.
943    #[must_use]
944    pub fn compute_waveform_peaks(samples: &[f32], bars: usize) -> Vec<f32> {
945        let count: usize = bars.max(8);
946        if samples.is_empty() {
947            return vec![0.25; count];
948        }
949        let step: usize = (samples.len() / count).max(1);
950        let mut peaks: Vec<f32> = Vec::with_capacity(count);
951        for item_index in 0..count {
952            let start: usize = (item_index * step).min(samples.len());
953            let end: usize = (start + step).min(samples.len());
954            let mut sum_sq: f32 = 0.0;
955            let len: usize = end.saturating_sub(start).max(1);
956            for source_val in &samples[start..end] {
957                sum_sq += (*source_val) * (*source_val);
958            }
959            let rms: f32 = (sum_sq / (len as f32)).sqrt();
960            peaks.push((rms * 1.45).clamp(0.10, 1.0));
961        }
962        peaks
963    }
964
965    /// Synthesizes a clean multi-band gradient + orbiting geometric emblem frame for sample GIF/Video/LIVE buffers.
966    ///
967    /// # Arguments
968    ///
969    /// - `u32` - Frame width in pixels.
970    /// - `u32` - Frame height in pixels.
971    /// - `Color` - Base background tone.
972    /// - `Color` - Primary accent tone.
973    /// - `usize` - Animation frame index.
974    ///
975    /// # Returns
976    ///
977    /// - `ImageBuffer` - Rendered RGBA8 bitmap frame.
978    #[must_use]
979    pub fn synthesize_frame(
980        width: u32,
981        height: u32,
982        bg: Color,
983        accent: Color,
984        frame_idx: usize,
985    ) -> ImageBuffer {
986        let width_val: u32 = width.max(16);
987        let height_val: u32 = height.max(16);
988        let mut pixels: Vec<u8> = vec![0; (width_val as usize) * (height_val as usize) * 4];
989        let phase: f32 = (frame_idx as f32) * 0.55;
990        let orb_x: f32 = (width_val as f32) * (0.5 + 0.28 * phase.cos());
991        let orb_y: f32 = (height_val as f32) * (0.48 + 0.18 * (phase * 1.3).sin());
992        let orb_r: f32 = (width_val.min(height_val) as f32) * 0.22;
993        let bg_r: f32 = bg.get_red() as f32;
994        let bg_g: f32 = bg.get_green() as f32;
995        let bg_b: f32 = bg.get_blue() as f32;
996        let ac_r: f32 = accent.get_red() as f32;
997        let ac_g: f32 = accent.get_green() as f32;
998        let ac_b: f32 = accent.get_blue() as f32;
999        for pos_y in 0..height_val {
1000            let fy: f32 = pos_y as f32;
1001            let item_val: f32 = fy / (height_val as f32);
1002            let row: usize = (pos_y as usize) * (width_val as usize) * 4;
1003            for pos_x in 0..width_val {
1004                let fx: f32 = pos_x as f32;
1005                let tex_u: f32 = fx / (width_val as f32);
1006                let dx: f32 = fx - orb_x;
1007                let dy: f32 = fy - orb_y;
1008                let dist: f32 = (dx * dx + dy * dy).sqrt();
1009                let glow: f32 = (1.0 - (dist / (orb_r * 2.2)).clamp(0.0, 1.0)).powf(2.0);
1010                let horizon: f32 = if item_val > 0.68 {
1011                    (item_val - 0.68) * 1.4
1012                } else {
1013                    0.0
1014                };
1015                let wave: f32 = ((tex_u * 8.0 + phase).sin() * 0.5 + 0.5) * horizon;
1016                let mix: f32 = (glow * 0.85 + wave * 0.45 + item_val * 0.18).clamp(0.0, 1.0);
1017                let idx: usize = row + (pos_x as usize) * 4;
1018                pixels[idx] = (bg_r + (ac_r - bg_r) * mix).clamp(0.0, 255.0) as u8;
1019                pixels[idx + 1] = (bg_g + (ac_g - bg_g) * mix).clamp(0.0, 255.0) as u8;
1020                pixels[idx + 2] = (bg_b + (ac_b - bg_b) * mix).clamp(0.0, 255.0) as u8;
1021                pixels[idx + 3] = 255;
1022            }
1023        }
1024        ImageBuffer::new(width_val, height_val, pixels)
1025    }
1026
1027    /// Extracts a PDF Info dictionary parenthesized value such as `/Title (Hello)`.
1028    ///
1029    /// # Arguments
1030    ///
1031    /// - `&str` - Decoded PDF ASCII text.
1032    /// - `&str` - Dictionary key prefix (e.g. `"/Title"`).
1033    ///
1034    /// # Returns
1035    ///
1036    /// - `Option<String>` - Extracted string value if present.
1037    #[must_use]
1038    fn extract_pdf_dict_string(text: &str, key: &str) -> Option<String> {
1039        let pos: usize = text.find(key)?;
1040        let rest: &str = text.get(pos + key.len()..)?.trim_start();
1041        let after_open: &str = rest.strip_prefix('(')?;
1042        let close: usize = after_open.find(')')?;
1043        let val: String = after_open[..close].trim().to_string();
1044        if val.is_empty() { None } else { Some(val) }
1045    }
1046
1047    /// Extracts an HTML/XML quoted attribute value (`attr="value"` or `attr='value'`).
1048    ///
1049    /// # Arguments
1050    ///
1051    /// - `&str` - Tag inner source slice.
1052    /// - `&str` - Attribute name.
1053    ///
1054    /// # Returns
1055    ///
1056    /// - `Option<String>` - Unquoted attribute value if present.
1057    #[must_use]
1058    fn extract_html_attr(tag: &str, attr: &str) -> Option<String> {
1059        let needle_dq: String = format!("{attr}=\"");
1060        if let Some(pos) = tag.find(&needle_dq) {
1061            let rest: &str = &tag[pos + needle_dq.len()..];
1062            let end: usize = rest.find('"')?;
1063            return Some(rest[..end].to_string());
1064        }
1065        let needle_sq: String = format!("{attr}='");
1066        if let Some(pos) = tag.find(&needle_sq) {
1067            let rest: &str = &tag[pos + needle_sq.len()..];
1068            let end: usize = rest.find('\'')?;
1069            return Some(rest[..end].to_string());
1070        }
1071        None
1072    }
1073
1074    /// Parses a numeric SVG attribute with fallback default.
1075    ///
1076    /// # Arguments
1077    ///
1078    /// - `&str` - Tag inner string.
1079    /// - `&str` - Attribute name.
1080    /// - `f32` - Default fallback scalar.
1081    ///
1082    /// # Returns
1083    ///
1084    /// - `f32` - Parsed value or default.
1085    #[must_use]
1086    fn attr_f32(tag: &str, attr: &str, default: f32) -> f32 {
1087        Self::extract_html_attr(tag, attr)
1088            .and_then(|text_value: String| text_value.trim_end_matches("px").parse::<f32>().ok())
1089            .unwrap_or(default)
1090    }
1091
1092    /// Decodes standard HTML character entities into UTF-8 text.
1093    ///
1094    /// # Arguments
1095    ///
1096    /// - `&str` - Input text slice.
1097    ///
1098    /// # Returns
1099    ///
1100    /// - `String` - Decoded string.
1101    #[must_use]
1102    fn decode_html_entities(text_value: &str) -> String {
1103        text_value
1104            .replace("&amp;", "&")
1105            .replace("&lt;", "<")
1106            .replace("&gt;", ">")
1107            .replace("&quot;", "\"")
1108            .replace("&#39;", "'")
1109            .replace("&nbsp;", " ")
1110    }
1111
1112    /// Parses a `#RRGGBB` hex color string with safe fallback.
1113    ///
1114    /// # Arguments
1115    ///
1116    /// - `&str` - Hex color text.
1117    ///
1118    /// # Returns
1119    ///
1120    /// - `Color` - Parsed RGBA color.
1121    #[must_use]
1122    fn parse_hex_color(raw: &str) -> Color {
1123        let trimmed: &str = raw.trim().trim_start_matches('#');
1124        if trimmed.len() == 6
1125            && let Ok(val) = u32::from_str_radix(trimmed, 16)
1126        {
1127            return Color::hex(val);
1128        }
1129        Color::hex(0x38BDF8)
1130    }
1131
1132    /// Rasterizes a solid axis-aligned rectangle into `pixels`.
1133    ///
1134    /// # Arguments
1135    ///
1136    /// - `&mut [u8]` - Destination RGBA8 buffer.
1137    /// - `u32` - Buffer width.
1138    /// - `u32` - Buffer height.
1139    /// - `Rect` - Rectangle bounds in pixel coordinates.
1140    /// - `Color` - Fill color.
1141    fn fill_rect_rgba(
1142        pixels: &mut [u8],
1143        width_val: u32,
1144        height_val: u32,
1145        rect: Rect,
1146        color: Color,
1147    ) {
1148        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(width_val);
1149        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(height_val);
1150        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(width_val);
1151        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(height_val);
1152        let rgba: [u8; 4] = color.to_rgba_bytes();
1153        for py in y0..y1 {
1154            let row: usize = (py as usize) * (width_val as usize) * 4;
1155            for px in x0..x1 {
1156                let idx: usize = row + (px as usize) * 4;
1157                pixels[idx..idx + 4].copy_from_slice(&rgba);
1158            }
1159        }
1160    }
1161
1162    /// Rasterizes a filled circle into `pixels`.
1163    ///
1164    /// # Arguments
1165    ///
1166    /// - `&mut [u8]` - Destination RGBA8 buffer.
1167    /// - `u32` - Buffer width.
1168    /// - `u32` - Buffer height.
1169    /// - `f32` - Center X coordinate.
1170    /// - `f32` - Center Y coordinate.
1171    /// - `f32` - Circle radius.
1172    /// - `Color` - Fill color.
1173    fn fill_circle_rgba(
1174        pixels: &mut [u8],
1175        width_val: u32,
1176        height_val: u32,
1177        cx: f32,
1178        cy: f32,
1179        red_val: f32,
1180        color: Color,
1181    ) {
1182        let pad: f32 = red_val + 1.5;
1183        let x0: u32 = ((cx - pad).floor().max(0.0) as u32).min(width_val);
1184        let y0: u32 = ((cy - pad).floor().max(0.0) as u32).min(height_val);
1185        let x1: u32 = ((cx + pad).ceil().max(0.0) as u32).min(width_val);
1186        let y1: u32 = ((cy + pad).ceil().max(0.0) as u32).min(height_val);
1187        let rgba: [u8; 4] = color.to_rgba_bytes();
1188        let src_a: f32 = (rgba[3] as f32) / 255.0;
1189        for py in y0..y1 {
1190            let dy: f32 = (py as f32) + 0.5 - cy;
1191            let row: usize = (py as usize) * (width_val as usize) * 4;
1192            for px in x0..x1 {
1193                let dx: f32 = (px as f32) + 0.5 - cx;
1194                let dist: f32 = (dx * dx + dy * dy).sqrt();
1195                let cov: f32 = (red_val + 0.5 - dist).clamp(0.0, 1.0) * src_a;
1196                if cov <= 0.0 {
1197                    continue;
1198                }
1199                let idx: usize = row + (px as usize) * 4;
1200                if cov >= 0.999 {
1201                    pixels[idx..idx + 4].copy_from_slice(&rgba);
1202                } else {
1203                    let inv: f32 = 1.0 - cov;
1204                    pixels[idx] =
1205                        ((rgba[0] as f32) * cov + (pixels[idx] as f32) * inv).round() as u8;
1206                    pixels[idx + 1] =
1207                        ((rgba[1] as f32) * cov + (pixels[idx + 1] as f32) * inv).round() as u8;
1208                    pixels[idx + 2] =
1209                        ((rgba[2] as f32) * cov + (pixels[idx + 2] as f32) * inv).round() as u8;
1210                    pixels[idx + 3] = 255;
1211                }
1212            }
1213        }
1214    }
1215
1216    /// Rasterizes a straight line segment into `pixels` using uniform sampling.
1217    ///
1218    /// # Arguments
1219    ///
1220    /// - `&mut [u8]` - Destination RGBA8 buffer.
1221    /// - `u32` - Buffer width.
1222    /// - `u32` - Buffer height.
1223    /// - `Point` - Segment start point.
1224    /// - `Point` - Segment end point.
1225    /// - `f32` - Stroke width in physical pixels.
1226    /// - `Color` - Stroke color.
1227    fn draw_line_thick_rgba(
1228        pixels: &mut [u8],
1229        width_px: u32,
1230        height_px: u32,
1231        from_point: Point,
1232        to_point: Point,
1233        stroke_width_px: f32,
1234        color: Color,
1235    ) {
1236        let delta_x: f32 = to_point.get_x() - from_point.get_x();
1237        let delta_y: f32 = to_point.get_y() - from_point.get_y();
1238        let step_count: usize = (delta_x.abs().max(delta_y.abs()).ceil() as usize).max(1);
1239        let rgba_bytes: [u8; 4] = color.to_rgba_bytes();
1240        let half_radius: i32 = ((stroke_width_px * 0.5).floor() as i32).max(0);
1241        for step_index in 0..=step_count {
1242            let ratio: f32 = (step_index as f32) / (step_count as f32);
1243            let center_x: i32 = (from_point.get_x() + delta_x * ratio).round() as i32;
1244            let center_y: i32 = (from_point.get_y() + delta_y * ratio).round() as i32;
1245            for offset_y in -half_radius..=half_radius {
1246                for offset_x in -half_radius..=half_radius {
1247                    let pixel_x: i32 = center_x + offset_x;
1248                    let pixel_y: i32 = center_y + offset_y;
1249                    if pixel_x >= 0
1250                        && pixel_y >= 0
1251                        && (pixel_x as u32) < width_px
1252                        && (pixel_y as u32) < height_px
1253                    {
1254                        let byte_index: usize =
1255                            ((pixel_y as usize) * (width_px as usize) + (pixel_x as usize)) * 4;
1256                        pixels[byte_index..byte_index + 4].copy_from_slice(&rgba_bytes);
1257                    }
1258                }
1259            }
1260        }
1261    }
1262}