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 GIF87a/GIF89a byte stream using full LZW decompression, palettes, de-interlacing, transparency, and all 4 disposal methods.
309    ///
310    /// # Arguments
311    ///
312    /// - `&[u8]` - Raw `.gif` file bytes.
313    /// - `&str` - Asset title.
314    ///
315    /// # Returns
316    ///
317    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` with exact source dimensions or parse/decode error.
318    pub fn decode_gif(bytes: &[u8], title: &str) -> Result<GifAnimation, String> {
319        Self::decode_gif_with_config(bytes, title, GifDecodeConfig::default())
320    }
321
322    /// Decodes a GIF87a/GIF89a byte stream using explicit `GifDecodeConfig` memory budgets and frame-delay compatibility settings.
323    ///
324    /// # Arguments
325    ///
326    /// - `&[u8]` - Raw `.gif` file bytes.
327    /// - `&str` - Asset title.
328    /// - `GifDecodeConfig` - Canvas/cache byte budget and frame-delay compatibility policy.
329    ///
330    /// # Returns
331    ///
332    /// - `Result<GifAnimation, String>` - Decoded multi-frame `GifAnimation` or parse/decode error.
333    pub fn decode_gif_with_config(
334        bytes: &[u8],
335        title: &str,
336        config: GifDecodeConfig,
337    ) -> Result<GifAnimation, String> {
338        let decoder: GifDecoder = GifDecoder::parse_with_config(bytes, config)?;
339        decoder.decode_all_animation(title)
340    }
341
342    /// Decodes a RIFF PCM WAV audio byte slice (8-bit or 16-bit) into a normalized `AudioTrack` with waveform peaks.
343    ///
344    /// # Arguments
345    ///
346    /// - `&[u8]` - Raw `.wav` bytes.
347    /// - `&str` - Track title.
348    ///
349    /// # Returns
350    ///
351    /// - `Result<AudioTrack, String>` - Decoded `AudioTrack` or format error.
352    pub fn decode_wav(bytes: &[u8], title: &str) -> Result<AudioTrack, String> {
353        let bad_riff: bool = bytes.len() < 44 || &bytes[0..4] != MAGIC_RIFF;
354        if bad_riff || &bytes[8..12] != MAGIC_WAVE {
355            return Err("invalid RIFF WAVE header".to_string());
356        }
357        let mut cursor: usize = 12;
358        let mut channels: u16 = 1;
359        let mut sample_rate: u32 = 44_100;
360        let mut bits_per_sample: u16 = 16;
361        let mut pcm_bytes: &[u8] = &[];
362        while cursor + 8 <= bytes.len() {
363            let chunk_id: &[u8] = &bytes[cursor..cursor + 4];
364            let chunk_size: usize = u32::from_le_bytes([
365                bytes[cursor + 4],
366                bytes[cursor + 5],
367                bytes[cursor + 6],
368                bytes[cursor + 7],
369            ]) as usize;
370            let body_start: usize = cursor + 8;
371            let body_end: usize = body_start.saturating_add(chunk_size).min(bytes.len());
372            if chunk_id == MAGIC_WAV_FMT && body_end - body_start >= 16 {
373                channels =
374                    u16::from_le_bytes([bytes[body_start + 2], bytes[body_start + 3]]).max(1);
375                sample_rate = u32::from_le_bytes([
376                    bytes[body_start + 4],
377                    bytes[body_start + 5],
378                    bytes[body_start + 6],
379                    bytes[body_start + 7],
380                ])
381                .max(8_000);
382                bits_per_sample =
383                    u16::from_le_bytes([bytes[body_start + 14], bytes[body_start + 15]]);
384            } else if chunk_id == MAGIC_WAV_DATA {
385                pcm_bytes = &bytes[body_start..body_end];
386            }
387            let padded: usize = chunk_size + (chunk_size & 1);
388            cursor = body_start.saturating_add(padded);
389        }
390        if pcm_bytes.is_empty() {
391            return Err("WAV file contained no data chunk".to_string());
392        }
393        let samples: Vec<f32> = if bits_per_sample == 16 {
394            let inv_scale: f32 = 1.0 / 32_768.0;
395            let chunks: &[[u8; 2]] = pcm_bytes.as_chunks::<2>().0;
396            let mut out: Vec<f32> = Vec::with_capacity(chunks.len());
397            for pair in chunks.iter() {
398                let source_val: i16 = i16::from_le_bytes(*pair);
399                out.push((source_val as f32) * inv_scale);
400            }
401            out
402        } else if bits_per_sample == 8 {
403            let inv_scale: f32 = 1.0 / 128.0;
404            let mut out: Vec<f32> = Vec::with_capacity(pcm_bytes.len());
405            for blue_val in pcm_bytes.iter().copied() {
406                out.push(((blue_val as f32) - 128.0) * inv_scale);
407            }
408            out
409        } else {
410            return Err("unsupported WAV bit depth (expected 8 or 16 bit PCM)".to_string());
411        };
412        let frames_total: usize = samples.len() / (channels as usize).max(1);
413        let duration_secs: f32 = (frames_total as f32) / (sample_rate as f32).max(1.0);
414        let waveform_peaks: Vec<f32> = Self::compute_waveform_peaks(&samples, 48);
415        Ok(AudioTrack {
416            metadata: MediaMetadata {
417                title: title.to_string(),
418                width: 0,
419                height: 0,
420                duration_secs,
421                page_count: 1,
422                frame_count: frames_total,
423                sample_rate_hz: sample_rate,
424                channels,
425                format_label: format!(
426                    "WAV · {:.1} kHz · {}",
427                    (sample_rate as f32) / 1000.0,
428                    if channels == 1 { "Mono" } else { "Stereo" }
429                ),
430            },
431            codec: AudioCodec::Wav,
432            samples,
433            waveform_peaks,
434            state: PlaybackState::Idle,
435            current_time_secs: 0.0,
436            volume: 0.85,
437            muted: false,
438            playback_rate: 1.0,
439            looping: true,
440        })
441    }
442
443    /// Parses a `%PDF-1.x` byte stream extracting version, info dictionary metadata, page count, and `Tj`/`TJ` text runs.
444    ///
445    /// # Arguments
446    ///
447    /// - `&[u8]` - Raw `.pdf` document bytes.
448    ///
449    /// # Returns
450    ///
451    /// - `Result<PdfDocument, String>` - Structured multi-page `PdfDocument` or format error.
452    pub fn parse_pdf(bytes: &[u8]) -> Result<PdfDocument, String> {
453        if bytes.len() < 8 || !bytes.starts_with(MAGIC_PDF) {
454            return Err("invalid PDF signature (expected %PDF-)".to_string());
455        }
456        let text: String = String::from_utf8_lossy(bytes).into_owned();
457        let version: String = text
458            .lines()
459            .next()
460            .and_then(|line: &str| line.strip_prefix(PREFIX_PDF))
461            .map(|text_value: &str| text_value.trim().to_string())
462            .filter(|label_str: &String| !label_str.is_empty())
463            .unwrap_or_else(|| "1.7".to_string());
464        let title: String = Self::extract_pdf_dict_string(&text, "/Title")
465            .unwrap_or_else(|| "Untitled PDF Document".to_string());
466        let author: String =
467            Self::extract_pdf_dict_string(&text, "/Author").unwrap_or_else(|| "euv".to_string());
468        let mut extracted_runs: Vec<String> = Vec::new();
469        let raw_bytes: &[u8] = text.as_bytes();
470        let mut item_index: usize = 0;
471        while item_index < raw_bytes.len() {
472            if raw_bytes[item_index] == BYTE_PAREN_OPEN {
473                let start: usize = item_index + 1;
474                let mut inner_index: usize = start;
475                let mut depth: i32 = 1;
476                while inner_index < raw_bytes.len() && depth > 0 {
477                    if raw_bytes[inner_index] == b'\\' && inner_index + 1 < raw_bytes.len() {
478                        inner_index += 2;
479                        continue;
480                    }
481                    if raw_bytes[inner_index] == BYTE_PAREN_OPEN {
482                        depth += 1;
483                    } else if raw_bytes[inner_index] == BYTE_PAREN_CLOSE {
484                        depth -= 1;
485                        if depth == 0 {
486                            break;
487                        }
488                    }
489                    inner_index += 1;
490                }
491                let tail: &str = text.get(inner_index..).unwrap_or("");
492                let trimmed_tail: &str = tail.trim_start_matches(')').trim_start();
493                if trimmed_tail.starts_with("Tj") || trimmed_tail.starts_with("] TJ") {
494                    let run: String = text[start..inner_index]
495                        .replace("\\(", "(")
496                        .replace("\\)", ")")
497                        .replace("\\\\", "\\")
498                        .trim()
499                        .to_string();
500                    if !run.is_empty() {
501                        extracted_runs.push(run);
502                    }
503                }
504                item_index = inner_index.saturating_add(1);
505            } else {
506                item_index += 1;
507            }
508        }
509        let declared_pages: usize = text
510            .matches("/Type /Page")
511            .count()
512            .saturating_sub(text.matches("/Type /Pages").count())
513            .max(1);
514        let mut pages: Vec<PdfPage> = Vec::with_capacity(declared_pages);
515        let per_page: usize = extracted_runs.len().div_ceil(declared_pages).max(1);
516        for p_idx in 0..declared_pages {
517            let start: usize = p_idx.saturating_mul(per_page);
518            let end: usize = start.saturating_add(per_page).min(extracted_runs.len());
519            let mut blocks: Vec<String> = if start < end {
520                extracted_runs[start..end].to_vec()
521            } else {
522                Vec::new()
523            };
524            if blocks.is_empty() {
525                blocks.push(format!(
526                    "Page {} content stream parsed from PDF {version}.",
527                    p_idx + 1
528                ));
529            }
530            let page_title: String = blocks
531                .first()
532                .cloned()
533                .unwrap_or_else(|| format!("Page {}", p_idx + 1));
534            pages.push(PdfPage {
535                page_number: p_idx + 1,
536                width_pt: 595.0,
537                height_pt: 842.0,
538                title: page_title,
539                text_blocks: blocks,
540                preview_image: None,
541            });
542        }
543        Ok(PdfDocument {
544            title,
545            author,
546            version,
547            pages,
548            current_page: 0,
549            zoom: 1.0,
550        })
551    }
552
553    /// Parses raw HTML5 markup into a sanitized, zero-JS `HtmlDocument` ready for native `euv` rendering.
554    ///
555    /// # Arguments
556    ///
557    /// - `&str` - Raw HTML markup string.
558    ///
559    /// # Returns
560    ///
561    /// - `HtmlDocument` - Parsed document title, links count, and ordered `HtmlBlock` items.
562    #[must_use]
563    pub fn parse_html(raw: &str) -> HtmlDocument {
564        let mut title: String = String::new();
565        let mut blocks: Vec<HtmlBlock> = Vec::new();
566        let mut links_count: usize = 0;
567        let bytes: &[u8] = raw.as_bytes();
568        let mut item_index: usize = 0;
569        let mut current_kind: Option<HtmlNodeKind> = None;
570        let mut current_href: Option<String> = None;
571        let mut in_title: bool = false;
572        let mut in_script_or_style: bool = false;
573        let mut buf: String = String::new();
574        while item_index < bytes.len() {
575            if bytes[item_index] == BYTE_ANGLE_OPEN {
576                let text_chunk: String = Self::decode_html_entities(buf.trim());
577                buf.clear();
578                if !text_chunk.is_empty() && !in_script_or_style {
579                    if in_title {
580                        title = text_chunk;
581                    } else {
582                        let kind: HtmlNodeKind = current_kind.unwrap_or(HtmlNodeKind::Paragraph);
583                        if kind == HtmlNodeKind::Link {
584                            links_count += 1;
585                        }
586                        blocks.push(HtmlBlock {
587                            kind,
588                            text: text_chunk,
589                            href: current_href.clone(),
590                            src: None,
591                        });
592                    }
593                }
594                let Some(close_rel) = raw[item_index..].find('>') else {
595                    break;
596                };
597                let tag_inner: &str = raw[item_index + 1..item_index + close_rel].trim();
598                let tag_b: &[u8] = tag_inner.as_bytes();
599                if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_SCRIPT)
600                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_STYLE)
601                {
602                    in_script_or_style = true;
603                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_SCRIPT)
604                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_STYLE)
605                {
606                    in_script_or_style = false;
607                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_TITLE) {
608                    in_title = true;
609                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CLOSE_TITLE) {
610                    in_title = false;
611                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_HR) {
612                    blocks.push(HtmlBlock {
613                        kind: HtmlNodeKind::HorizontalRule,
614                        text: String::new(),
615                        href: None,
616                        src: None,
617                    });
618                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_IMG) {
619                    let src_val: Option<String> = Self::extract_html_attr(tag_inner, "src");
620                    let alt_val: String = Self::extract_html_attr(tag_inner, "alt")
621                        .unwrap_or_else(|| "Embedded Image".to_string());
622                    blocks.push(HtmlBlock {
623                        kind: HtmlNodeKind::Image,
624                        text: alt_val,
625                        href: None,
626                        src: src_val,
627                    });
628                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H1) {
629                    current_kind = Some(HtmlNodeKind::Heading(1));
630                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H2) {
631                    current_kind = Some(HtmlNodeKind::Heading(2));
632                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_H3) {
633                    current_kind = Some(HtmlNodeKind::Heading(3));
634                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_BLOCKQUOTE) {
635                    current_kind = Some(HtmlNodeKind::Blockquote);
636                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_PRE)
637                    || Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_CODE)
638                {
639                    current_kind = Some(HtmlNodeKind::CodeBlock);
640                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_LI) {
641                    current_kind = Some(HtmlNodeKind::ListItem);
642                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_A_SPACE)
643                    || tag_b.eq_ignore_ascii_case(HTML_TAG_A)
644                {
645                    current_kind = Some(HtmlNodeKind::Link);
646                    current_href = Self::extract_html_attr(tag_inner, "href");
647                } else if Self::starts_with_ignore_ascii_case(tag_b, HTML_TAG_P_SPACE)
648                    || tag_b.eq_ignore_ascii_case(HTML_TAG_P)
649                {
650                    current_kind = Some(HtmlNodeKind::Paragraph);
651                } else if tag_b.starts_with(HTML_TAG_CLOSE_PREFIX) {
652                    current_kind = None;
653                    current_href = None;
654                }
655                item_index += close_rel + 1;
656            } else {
657                let ch: char = raw[item_index..].chars().next().unwrap_or(' ');
658                buf.push(ch);
659                item_index += ch.len_utf8();
660            }
661        }
662        let trailing: String = Self::decode_html_entities(buf.trim());
663        if !trailing.is_empty() && !in_script_or_style {
664            blocks.push(HtmlBlock {
665                kind: current_kind.unwrap_or(HtmlNodeKind::Paragraph),
666                text: trailing,
667                href: current_href,
668                src: None,
669            });
670        }
671        if title.is_empty() {
672            title = blocks
673                .iter()
674                .find(|blue_val: &&HtmlBlock| {
675                    matches!(blue_val.get_kind(), HtmlNodeKind::Heading(_))
676                })
677                .map(|byte_val: &HtmlBlock| byte_val.get_text().clone())
678                .unwrap_or_else(|| "HTML Document".to_string());
679        }
680        HtmlDocument {
681            title,
682            raw_html: raw.to_string(),
683            blocks,
684            links_count,
685        }
686    }
687
688    /// Parses an SVG document (`<svg>`, `<rect>`, `<circle>`, `<line>`) and rasterizes it into an `ImageBuffer`.
689    ///
690    /// # Arguments
691    ///
692    /// - `&str` - Raw SVG XML source.
693    /// - `u32` - Target rasterization width in pixels.
694    /// - `u32` - Target rasterization height in pixels.
695    /// - `f32` - Display scale factor.
696    ///
697    /// # Returns
698    ///
699    /// - `Result<SvgDocument, String>` - Parsed and rasterized `SvgDocument` or error.
700    pub fn parse_and_rasterize_svg_scaled(
701        raw_svg: &str,
702        logical_width: u32,
703        logical_height: u32,
704        scale_factor: f32,
705    ) -> Result<SvgDocument, String> {
706        let clamped_scale: f32 = if scale_factor.is_finite() {
707            scale_factor.clamp(1.0, 4.0)
708        } else {
709            1.0
710        };
711        let scaled_width: u32 = ((logical_width.max(1) as f32) * clamped_scale).round() as u32;
712        let scaled_height: u32 = ((logical_height.max(1) as f32) * clamped_scale).round() as u32;
713        Self::parse_and_rasterize_svg(raw_svg, scaled_width, scaled_height)
714    }
715
716    /// Parses and rasterizes a subset of vector SVG tags into an RGBA `SvgDocument` up to `2048x2048` physical pixels.
717    ///
718    /// # Arguments
719    ///
720    /// - `&str` - Raw SVG XML string.
721    /// - `u32` - Target raster width in physical pixels.
722    /// - `u32` - Target raster height in physical pixels.
723    ///
724    /// # Returns
725    ///
726    /// - `Result<SvgDocument, String>` - Parsed and rasterized `SvgDocument` or error.
727    pub fn parse_and_rasterize_svg(
728        raw_svg: &str,
729        out_w: u32,
730        out_h: u32,
731    ) -> Result<SvgDocument, String> {
732        if !raw_svg.contains(TAG_SVG_OPEN) {
733            return Err("invalid SVG document (missing <svg> root)".to_string());
734        }
735        let width_val: u32 = out_w.clamp(16, 2048);
736        let height_val: u32 = out_h.clamp(16, 2048);
737        let mut vb_w: f32 = width_val as f32;
738        let mut vb_h: f32 = height_val as f32;
739        if let Some(vb_str) = Self::extract_html_attr(raw_svg, "viewBox") {
740            let nums: Vec<f32> = vb_str
741                .split_whitespace()
742                .filter_map(|text_value: &str| text_value.parse::<f32>().ok())
743                .collect();
744            if nums.len() >= 4 {
745                vb_w = nums[2].max(1.0);
746                vb_h = nums[3].max(1.0);
747            }
748        }
749        let scale_x: f32 = (width_val as f32) / vb_w;
750        let scale_y: f32 = (height_val as f32) / vb_h;
751        let mut pixels: Vec<u8> = vec![0; (width_val as usize) * (height_val as usize) * 4];
752        let mut primitive_count: usize = 0;
753        let mut cursor: usize = 0;
754        while let Some(open_rel) = raw_svg[cursor..].find('<') {
755            let start: usize = cursor + open_rel;
756            let Some(close_rel) = raw_svg[start..].find('>') else {
757                break;
758            };
759            let tag: &str = raw_svg[start + 1..start + close_rel].trim();
760            cursor = start + close_rel + 1;
761            if tag.starts_with("rect") {
762                let pos_x: f32 = Self::attr_f32(tag, "x", 0.0) * scale_x;
763                let pos_y: f32 = Self::attr_f32(tag, "y", 0.0) * scale_y;
764                let rw: f32 = Self::attr_f32(tag, "width", vb_w) * scale_x;
765                let rh: f32 = Self::attr_f32(tag, "height", vb_h) * scale_y;
766                let col: Color = Self::parse_hex_color(
767                    Self::extract_html_attr(tag, "fill")
768                        .as_deref()
769                        .unwrap_or("#0F172A"),
770                );
771                Self::fill_rect_rgba(
772                    &mut pixels,
773                    width_val,
774                    height_val,
775                    Rect::new(pos_x, pos_y, rw, rh),
776                    col,
777                );
778                primitive_count += 1;
779            } else if tag.starts_with("circle") {
780                let cx: f32 = Self::attr_f32(tag, "cx", vb_w * 0.5) * scale_x;
781                let cy: f32 = Self::attr_f32(tag, "cy", vb_h * 0.5) * scale_y;
782                let red_val: f32 = Self::attr_f32(tag, "r", 16.0) * scale_x.min(scale_y);
783                let col: Color = Self::parse_hex_color(
784                    Self::extract_html_attr(tag, "fill")
785                        .as_deref()
786                        .unwrap_or("#38BDF8"),
787                );
788                Self::fill_circle_rgba(&mut pixels, width_val, height_val, cx, cy, red_val, col);
789                primitive_count += 1;
790            } else if tag.starts_with("line") {
791                let x1: f32 = Self::attr_f32(tag, "x1", 0.0) * scale_x;
792                let y1: f32 = Self::attr_f32(tag, "y1", 0.0) * scale_y;
793                let x2: f32 = Self::attr_f32(tag, "x2", vb_w) * scale_x;
794                let y2: f32 = Self::attr_f32(tag, "y2", vb_h) * scale_y;
795                let stroke_width_px: f32 =
796                    (Self::attr_f32(tag, "stroke-width", 1.0) * scale_x.min(scale_y)).max(1.0);
797                let col: Color = Self::parse_hex_color(
798                    Self::extract_html_attr(tag, "stroke")
799                        .as_deref()
800                        .unwrap_or("#FFFFFF"),
801                );
802                Self::draw_line_thick_rgba(
803                    &mut pixels,
804                    width_val,
805                    height_val,
806                    Point::new(x1, y1),
807                    Point::new(x2, y2),
808                    stroke_width_px,
809                    col,
810                );
811                primitive_count += 1;
812            }
813        }
814        Ok(SvgDocument {
815            view_box_width: vb_w,
816            view_box_height: vb_h,
817            raw_svg: raw_svg.to_string(),
818            rasterized: ImageBuffer::new(width_val, height_val, pixels),
819            primitive_count,
820        })
821    }
822
823    /// Computes normalized RMS waveform bar peaks (`0.08..=1.0`) from PCM samples.
824    ///
825    /// # Arguments
826    ///
827    /// - `&[f32]` - Input PCM samples.
828    /// - `usize` - Number of output bars.
829    ///
830    /// # Returns
831    ///
832    /// - `Vec<f32>` - Normalized bar peak heights.
833    #[must_use]
834    pub fn compute_waveform_peaks(samples: &[f32], bars: usize) -> Vec<f32> {
835        let count: usize = bars.max(8);
836        if samples.is_empty() {
837            return vec![0.25; count];
838        }
839        let step: usize = (samples.len() / count).max(1);
840        let mut peaks: Vec<f32> = Vec::with_capacity(count);
841        for item_index in 0..count {
842            let start: usize = (item_index * step).min(samples.len());
843            let end: usize = (start + step).min(samples.len());
844            let mut sum_sq: f32 = 0.0;
845            let len: usize = end.saturating_sub(start).max(1);
846            for source_val in &samples[start..end] {
847                sum_sq += (*source_val) * (*source_val);
848            }
849            let rms: f32 = (sum_sq / (len as f32)).sqrt();
850            peaks.push((rms * 1.45).clamp(0.10, 1.0));
851        }
852        peaks
853    }
854
855    /// Synthesizes a clean multi-band gradient + orbiting geometric emblem frame for sample GIF/Video/LIVE buffers.
856    ///
857    /// # Arguments
858    ///
859    /// - `u32` - Frame width in pixels.
860    /// - `u32` - Frame height in pixels.
861    /// - `Color` - Base background tone.
862    /// - `Color` - Primary accent tone.
863    /// - `usize` - Animation frame index.
864    ///
865    /// # Returns
866    ///
867    /// - `ImageBuffer` - Rendered RGBA8 bitmap frame.
868    #[must_use]
869    pub fn synthesize_frame(
870        width: u32,
871        height: u32,
872        bg: Color,
873        accent: Color,
874        frame_idx: usize,
875    ) -> ImageBuffer {
876        let width_val: u32 = width.max(16);
877        let height_val: u32 = height.max(16);
878        let mut pixels: Vec<u8> = vec![0; (width_val as usize) * (height_val as usize) * 4];
879        let phase: f32 = (frame_idx as f32) * 0.55;
880        let orb_x: f32 = (width_val as f32) * (0.5 + 0.28 * phase.cos());
881        let orb_y: f32 = (height_val as f32) * (0.48 + 0.18 * (phase * 1.3).sin());
882        let orb_r: f32 = (width_val.min(height_val) as f32) * 0.22;
883        let bg_r: f32 = bg.get_red() as f32;
884        let bg_g: f32 = bg.get_green() as f32;
885        let bg_b: f32 = bg.get_blue() as f32;
886        let ac_r: f32 = accent.get_red() as f32;
887        let ac_g: f32 = accent.get_green() as f32;
888        let ac_b: f32 = accent.get_blue() as f32;
889        for pos_y in 0..height_val {
890            let fy: f32 = pos_y as f32;
891            let item_val: f32 = fy / (height_val as f32);
892            let row: usize = (pos_y as usize) * (width_val as usize) * 4;
893            for pos_x in 0..width_val {
894                let fx: f32 = pos_x as f32;
895                let tex_u: f32 = fx / (width_val as f32);
896                let dx: f32 = fx - orb_x;
897                let dy: f32 = fy - orb_y;
898                let dist: f32 = (dx * dx + dy * dy).sqrt();
899                let glow: f32 = (1.0 - (dist / (orb_r * 2.2)).clamp(0.0, 1.0)).powf(2.0);
900                let horizon: f32 = if item_val > 0.68 {
901                    (item_val - 0.68) * 1.4
902                } else {
903                    0.0
904                };
905                let wave: f32 = ((tex_u * 8.0 + phase).sin() * 0.5 + 0.5) * horizon;
906                let mix: f32 = (glow * 0.85 + wave * 0.45 + item_val * 0.18).clamp(0.0, 1.0);
907                let idx: usize = row + (pos_x as usize) * 4;
908                pixels[idx] = (bg_r + (ac_r - bg_r) * mix).clamp(0.0, 255.0) as u8;
909                pixels[idx + 1] = (bg_g + (ac_g - bg_g) * mix).clamp(0.0, 255.0) as u8;
910                pixels[idx + 2] = (bg_b + (ac_b - bg_b) * mix).clamp(0.0, 255.0) as u8;
911                pixels[idx + 3] = 255;
912            }
913        }
914        ImageBuffer::new(width_val, height_val, pixels)
915    }
916
917    /// Extracts a PDF Info dictionary parenthesized value such as `/Title (Hello)`.
918    ///
919    /// # Arguments
920    ///
921    /// - `&str` - Decoded PDF ASCII text.
922    /// - `&str` - Dictionary key prefix (e.g. `"/Title"`).
923    ///
924    /// # Returns
925    ///
926    /// - `Option<String>` - Extracted string value if present.
927    #[must_use]
928    fn extract_pdf_dict_string(text: &str, key: &str) -> Option<String> {
929        let pos: usize = text.find(key)?;
930        let rest: &str = text.get(pos + key.len()..)?.trim_start();
931        let after_open: &str = rest.strip_prefix('(')?;
932        let close: usize = after_open.find(')')?;
933        let val: String = after_open[..close].trim().to_string();
934        if val.is_empty() { None } else { Some(val) }
935    }
936
937    /// Extracts an HTML/XML quoted attribute value (`attr="value"` or `attr='value'`).
938    ///
939    /// # Arguments
940    ///
941    /// - `&str` - Tag inner source slice.
942    /// - `&str` - Attribute name.
943    ///
944    /// # Returns
945    ///
946    /// - `Option<String>` - Unquoted attribute value if present.
947    #[must_use]
948    fn extract_html_attr(tag: &str, attr: &str) -> Option<String> {
949        let needle_dq: String = format!("{attr}=\"");
950        if let Some(pos) = tag.find(&needle_dq) {
951            let rest: &str = &tag[pos + needle_dq.len()..];
952            let end: usize = rest.find('"')?;
953            return Some(rest[..end].to_string());
954        }
955        let needle_sq: String = format!("{attr}='");
956        if let Some(pos) = tag.find(&needle_sq) {
957            let rest: &str = &tag[pos + needle_sq.len()..];
958            let end: usize = rest.find('\'')?;
959            return Some(rest[..end].to_string());
960        }
961        None
962    }
963
964    /// Parses a numeric SVG attribute with fallback default.
965    ///
966    /// # Arguments
967    ///
968    /// - `&str` - Tag inner string.
969    /// - `&str` - Attribute name.
970    /// - `f32` - Default fallback scalar.
971    ///
972    /// # Returns
973    ///
974    /// - `f32` - Parsed value or default.
975    #[must_use]
976    fn attr_f32(tag: &str, attr: &str, default: f32) -> f32 {
977        Self::extract_html_attr(tag, attr)
978            .and_then(|text_value: String| text_value.trim_end_matches("px").parse::<f32>().ok())
979            .unwrap_or(default)
980    }
981
982    /// Decodes standard HTML character entities into UTF-8 text.
983    ///
984    /// # Arguments
985    ///
986    /// - `&str` - Input text slice.
987    ///
988    /// # Returns
989    ///
990    /// - `String` - Decoded string.
991    #[must_use]
992    fn decode_html_entities(text_value: &str) -> String {
993        text_value
994            .replace("&amp;", "&")
995            .replace("&lt;", "<")
996            .replace("&gt;", ">")
997            .replace("&quot;", "\"")
998            .replace("&#39;", "'")
999            .replace("&nbsp;", " ")
1000    }
1001
1002    /// Parses a `#RRGGBB` hex color string with safe fallback.
1003    ///
1004    /// # Arguments
1005    ///
1006    /// - `&str` - Hex color text.
1007    ///
1008    /// # Returns
1009    ///
1010    /// - `Color` - Parsed RGBA color.
1011    #[must_use]
1012    fn parse_hex_color(raw: &str) -> Color {
1013        let trimmed: &str = raw.trim().trim_start_matches('#');
1014        if trimmed.len() == 6
1015            && let Ok(val) = u32::from_str_radix(trimmed, 16)
1016        {
1017            return Color::hex(val);
1018        }
1019        Color::hex(0x38BDF8)
1020    }
1021
1022    /// Rasterizes a solid axis-aligned rectangle into `pixels`.
1023    ///
1024    /// # Arguments
1025    ///
1026    /// - `&mut [u8]` - Destination RGBA8 buffer.
1027    /// - `u32` - Buffer width.
1028    /// - `u32` - Buffer height.
1029    /// - `Rect` - Rectangle bounds in pixel coordinates.
1030    /// - `Color` - Fill color.
1031    fn fill_rect_rgba(
1032        pixels: &mut [u8],
1033        width_val: u32,
1034        height_val: u32,
1035        rect: Rect,
1036        color: Color,
1037    ) {
1038        let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(width_val);
1039        let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(height_val);
1040        let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(width_val);
1041        let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(height_val);
1042        let rgba: [u8; 4] = color.to_rgba_bytes();
1043        for py in y0..y1 {
1044            let row: usize = (py as usize) * (width_val as usize) * 4;
1045            for px in x0..x1 {
1046                let idx: usize = row + (px as usize) * 4;
1047                pixels[idx..idx + 4].copy_from_slice(&rgba);
1048            }
1049        }
1050    }
1051
1052    /// Rasterizes a filled circle into `pixels`.
1053    ///
1054    /// # Arguments
1055    ///
1056    /// - `&mut [u8]` - Destination RGBA8 buffer.
1057    /// - `u32` - Buffer width.
1058    /// - `u32` - Buffer height.
1059    /// - `f32` - Center X coordinate.
1060    /// - `f32` - Center Y coordinate.
1061    /// - `f32` - Circle radius.
1062    /// - `Color` - Fill color.
1063    fn fill_circle_rgba(
1064        pixels: &mut [u8],
1065        width_val: u32,
1066        height_val: u32,
1067        cx: f32,
1068        cy: f32,
1069        red_val: f32,
1070        color: Color,
1071    ) {
1072        let pad: f32 = red_val + 1.5;
1073        let x0: u32 = ((cx - pad).floor().max(0.0) as u32).min(width_val);
1074        let y0: u32 = ((cy - pad).floor().max(0.0) as u32).min(height_val);
1075        let x1: u32 = ((cx + pad).ceil().max(0.0) as u32).min(width_val);
1076        let y1: u32 = ((cy + pad).ceil().max(0.0) as u32).min(height_val);
1077        let rgba: [u8; 4] = color.to_rgba_bytes();
1078        let src_a: f32 = (rgba[3] as f32) / 255.0;
1079        for py in y0..y1 {
1080            let dy: f32 = (py as f32) + 0.5 - cy;
1081            let row: usize = (py as usize) * (width_val as usize) * 4;
1082            for px in x0..x1 {
1083                let dx: f32 = (px as f32) + 0.5 - cx;
1084                let dist: f32 = (dx * dx + dy * dy).sqrt();
1085                let cov: f32 = (red_val + 0.5 - dist).clamp(0.0, 1.0) * src_a;
1086                if cov <= 0.0 {
1087                    continue;
1088                }
1089                let idx: usize = row + (px as usize) * 4;
1090                if cov >= 0.999 {
1091                    pixels[idx..idx + 4].copy_from_slice(&rgba);
1092                } else {
1093                    let inv: f32 = 1.0 - cov;
1094                    pixels[idx] =
1095                        ((rgba[0] as f32) * cov + (pixels[idx] as f32) * inv).round() as u8;
1096                    pixels[idx + 1] =
1097                        ((rgba[1] as f32) * cov + (pixels[idx + 1] as f32) * inv).round() as u8;
1098                    pixels[idx + 2] =
1099                        ((rgba[2] as f32) * cov + (pixels[idx + 2] as f32) * inv).round() as u8;
1100                    pixels[idx + 3] = 255;
1101                }
1102            }
1103        }
1104    }
1105
1106    /// Rasterizes a straight line segment into `pixels` using uniform sampling.
1107    ///
1108    /// # Arguments
1109    ///
1110    /// - `&mut [u8]` - Destination RGBA8 buffer.
1111    /// - `u32` - Buffer width.
1112    /// - `u32` - Buffer height.
1113    /// - `Point` - Segment start point.
1114    /// - `Point` - Segment end point.
1115    /// - `f32` - Stroke width in physical pixels.
1116    /// - `Color` - Stroke color.
1117    fn draw_line_thick_rgba(
1118        pixels: &mut [u8],
1119        width_px: u32,
1120        height_px: u32,
1121        from_point: Point,
1122        to_point: Point,
1123        stroke_width_px: f32,
1124        color: Color,
1125    ) {
1126        let delta_x: f32 = to_point.get_x() - from_point.get_x();
1127        let delta_y: f32 = to_point.get_y() - from_point.get_y();
1128        let step_count: usize = (delta_x.abs().max(delta_y.abs()).ceil() as usize).max(1);
1129        let rgba_bytes: [u8; 4] = color.to_rgba_bytes();
1130        let half_radius: i32 = ((stroke_width_px * 0.5).floor() as i32).max(0);
1131        for step_index in 0..=step_count {
1132            let ratio: f32 = (step_index as f32) / (step_count as f32);
1133            let center_x: i32 = (from_point.get_x() + delta_x * ratio).round() as i32;
1134            let center_y: i32 = (from_point.get_y() + delta_y * ratio).round() as i32;
1135            for offset_y in -half_radius..=half_radius {
1136                for offset_x in -half_radius..=half_radius {
1137                    let pixel_x: i32 = center_x + offset_x;
1138                    let pixel_y: i32 = center_y + offset_y;
1139                    if pixel_x >= 0
1140                        && pixel_y >= 0
1141                        && (pixel_x as u32) < width_px
1142                        && (pixel_y as u32) < height_px
1143                    {
1144                        let byte_index: usize =
1145                            ((pixel_y as usize) * (width_px as usize) + (pixel_x as usize)) * 4;
1146                        pixels[byte_index..byte_index + 4].copy_from_slice(&rgba_bytes);
1147                    }
1148                }
1149            }
1150        }
1151    }
1152}