1use super::*;
2
3impl MediaCodecRegistry {
5 #[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 #[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 #[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 #[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, b"<svg ")
104 {
105 return MediaKind::Svg;
106 }
107 let is_doc_or_html: bool = Self::starts_with_ignore_ascii_case(head, b"<!doctype html")
108 || Self::starts_with_ignore_ascii_case(head, b"<html");
109 let is_art_or_div: bool = Self::starts_with_ignore_ascii_case(head, b"<article")
110 || Self::starts_with_ignore_ascii_case(head, b"<div");
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, b".live")
120 || Self::ends_with_ignore_ascii_case(uri_b, b".livp")
121 {
122 return MediaKind::LivePhoto;
123 }
124 let vid_a: bool = Self::ends_with_ignore_ascii_case(uri_b, b".mp4")
125 || Self::ends_with_ignore_ascii_case(uri_b, b".mov");
126 let vid_b: bool = Self::ends_with_ignore_ascii_case(uri_b, b".webm")
127 || Self::ends_with_ignore_ascii_case(uri_b, b".mkv");
128 if vid_a || vid_b {
129 return MediaKind::Video;
130 }
131 let aud_a: bool = Self::ends_with_ignore_ascii_case(uri_b, b".wav")
132 || Self::ends_with_ignore_ascii_case(uri_b, b".mp3");
133 let aud_b: bool = Self::ends_with_ignore_ascii_case(uri_b, b".aac")
134 || Self::ends_with_ignore_ascii_case(uri_b, b".ogg");
135 let aud_ab: bool = aud_a || aud_b;
136 if aud_ab || Self::ends_with_ignore_ascii_case(uri_b, b".flac") {
137 return MediaKind::Audio;
138 }
139 if Self::ends_with_ignore_ascii_case(uri_b, b".pdf") {
140 return MediaKind::Pdf;
141 }
142 if Self::ends_with_ignore_ascii_case(uri_b, b".html")
143 || Self::ends_with_ignore_ascii_case(uri_b, b".htm")
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 #[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, b".jpg")
182 || Self::ends_with_ignore_ascii_case(uri_b, b".jpeg")
183 {
184 ImageFormat::Jpeg
185 } else if Self::ends_with_ignore_ascii_case(uri_b, b".webp") {
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, b".bmp") {
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, b".heic")
194 || Self::ends_with_ignore_ascii_case(uri_b, b".heif")
195 {
196 ImageFormat::Heic
197 } else if Self::ends_with_ignore_ascii_case(uri_b, b".avif") {
198 ImageFormat::Avif
199 } else {
200 ImageFormat::Png
201 }
202 }
203
204 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 y in 0..h_usize {
249 let src_y: usize = if top_down { y } else { h_usize - 1 - 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 = y * dst_row_bytes;
253 for (x, px) in src_slice.as_chunks::<4>().0.iter().enumerate() {
254 unsafe {
256 dst_ptr
257 .add(dst_row_off + 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 y in 0..h_usize {
266 let src_y: usize = if top_down { y } else { h_usize - 1 - y };
267 let src_off: usize = data_offset + src_y * row_stride;
268 let src_slice: &[u8] = &bytes[src_off..(src_off + src_row_bytes)];
269 let dst_row_off: usize = y * dst_row_bytes;
270 for (x, px) in src_slice.as_chunks::<3>().0.iter().enumerate() {
271 unsafe {
273 dst_ptr
274 .add(dst_row_off + x * 4)
275 .cast::<[u8; 4]>()
276 .write([px[2], px[1], px[0], 255]);
277 }
278 }
279 }
280 }
281 unsafe {
283 rgba.set_len(total_bytes);
284 }
285 let meta: MediaMetadata = MediaMetadata {
286 title: alt_text.to_string(),
287 width,
288 height,
289 duration_secs: 0.0,
290 page_count: 1,
291 frame_count: 1,
292 sample_rate_hz: 0,
293 channels: 0,
294 format_label: "BMP".to_string(),
295 };
296 Ok(ImageAsset {
297 format: ImageFormat::Bmp,
298 buffer: ImageBuffer::new(width, height, rgba),
299 alt_text: alt_text.to_string(),
300 metadata: meta,
301 })
302 }
303
304 pub fn decode_gif(bytes: &[u8], title: &str) -> Result<GifAnimation, String> {
315 let valid_sig: bool = bytes.starts_with(MAGIC_GIF87A) || bytes.starts_with(MAGIC_GIF89A);
316 if bytes.len() < 13 || !valid_sig {
317 return Err("invalid GIF87a/GIF89a header".to_string());
318 }
319 let width: u32 = u16::from_le_bytes([bytes[6], bytes[7]]).max(1) as u32;
320 let height: u32 = u16::from_le_bytes([bytes[8], bytes[9]]).max(1) as u32;
321 let packed: u8 = bytes[10];
322 let has_gct: bool = (packed & 0x80) != 0;
323 let gct_entries: usize = if has_gct {
324 1_usize << ((packed & 0x07) + 1)
325 } else {
326 0
327 };
328 let mut cursor: usize = 13;
329 let mut palette: Vec<Color> = Vec::new();
330 if has_gct && cursor + gct_entries * 3 <= bytes.len() {
331 for i in 0..gct_entries {
332 let off: usize = cursor + i * 3;
333 palette.push(Color::rgb(bytes[off], bytes[off + 1], bytes[off + 2]));
334 }
335 cursor += gct_entries * 3;
336 }
337 if palette.is_empty() {
338 palette.push(Color::hex(0x0F172A));
339 palette.push(Color::hex(0x38BDF8));
340 palette.push(Color::hex(0xA855F7));
341 palette.push(Color::hex(0x34D399));
342 }
343 let mut frames: Vec<MediaFrame> = Vec::new();
344 let mut next_delay_ms: u32 = 100;
345 let mut elapsed_sec: f32 = 0.0;
346 while cursor < bytes.len() {
347 let intro: u8 = bytes[cursor];
348 cursor += 1;
349 if intro == 0x3B {
350 break;
351 }
352 if intro == 0x21 && cursor < bytes.len() {
353 let label: u8 = bytes[cursor];
354 cursor += 1;
355 if label == 0xF9 && cursor + 5 < bytes.len() && bytes[cursor] == 4 {
356 let delay_cs: u16 = u16::from_le_bytes([bytes[cursor + 2], bytes[cursor + 3]]);
357 next_delay_ms = ((delay_cs as u32) * 10).max(20);
358 }
359 while cursor < bytes.len() {
360 let sub_len: usize = bytes[cursor] as usize;
361 cursor += 1;
362 if sub_len == 0 {
363 break;
364 }
365 cursor = cursor.saturating_add(sub_len).min(bytes.len());
366 }
367 } else if intro == 0x2C && cursor + 9 <= bytes.len() {
368 let img_packed: u8 = bytes[cursor + 8];
369 cursor += 9;
370 if (img_packed & 0x80) != 0 {
371 let lct_len: usize = (1_usize << ((img_packed & 0x07) + 1)) * 3;
372 cursor = cursor.saturating_add(lct_len).min(bytes.len());
373 }
374 if cursor < bytes.len() {
375 cursor += 1;
376 }
377 while cursor < bytes.len() {
378 let sub_len: usize = bytes[cursor] as usize;
379 cursor += 1;
380 if sub_len == 0 {
381 break;
382 }
383 cursor = cursor.saturating_add(sub_len).min(bytes.len());
384 }
385 let frame_idx: usize = frames.len();
386 let bg: Color = palette[frame_idx % palette.len()];
387 let accent: Color = palette[(frame_idx + 1) % palette.len()];
388 let img: ImageBuffer =
389 Self::synthesize_frame(width.min(320), height.min(200), bg, accent, frame_idx);
390 frames.push(MediaFrame {
391 image: img,
392 delay_ms: next_delay_ms,
393 timestamp_secs: elapsed_sec,
394 });
395 elapsed_sec += (next_delay_ms as f32) / 1000.0;
396 next_delay_ms = 100;
397 }
398 }
399 if frames.is_empty() {
400 frames.push(MediaFrame {
401 image: Self::synthesize_frame(
402 width.min(320),
403 height.min(200),
404 palette[0],
405 palette[1 % palette.len()],
406 0,
407 ),
408 delay_ms: 100,
409 timestamp_secs: 0.0,
410 });
411 elapsed_sec = 0.1;
412 }
413 let frame_count: usize = frames.len();
414 Ok(GifAnimation {
415 frames,
416 loop_count: 0,
417 current_frame: 0,
418 elapsed_ms: 0,
419 playing: true,
420 metadata: MediaMetadata {
421 title: title.to_string(),
422 width,
423 height,
424 duration_secs: elapsed_sec,
425 page_count: 1,
426 frame_count,
427 sample_rate_hz: 0,
428 channels: 0,
429 format_label: "GIF89a".to_string(),
430 },
431 })
432 }
433
434 pub fn decode_wav(bytes: &[u8], title: &str) -> Result<AudioTrack, String> {
445 let bad_riff: bool = bytes.len() < 44 || &bytes[0..4] != MAGIC_RIFF;
446 if bad_riff || &bytes[8..12] != MAGIC_WAVE {
447 return Err("invalid RIFF WAVE header".to_string());
448 }
449 let mut cursor: usize = 12;
450 let mut channels: u16 = 1;
451 let mut sample_rate: u32 = 44_100;
452 let mut bits_per_sample: u16 = 16;
453 let mut pcm_bytes: &[u8] = &[];
454 while cursor + 8 <= bytes.len() {
455 let chunk_id: &[u8] = &bytes[cursor..cursor + 4];
456 let chunk_size: usize = u32::from_le_bytes([
457 bytes[cursor + 4],
458 bytes[cursor + 5],
459 bytes[cursor + 6],
460 bytes[cursor + 7],
461 ]) as usize;
462 let body_start: usize = cursor + 8;
463 let body_end: usize = body_start.saturating_add(chunk_size).min(bytes.len());
464 if chunk_id == MAGIC_WAV_FMT && body_end - body_start >= 16 {
465 channels =
466 u16::from_le_bytes([bytes[body_start + 2], bytes[body_start + 3]]).max(1);
467 sample_rate = u32::from_le_bytes([
468 bytes[body_start + 4],
469 bytes[body_start + 5],
470 bytes[body_start + 6],
471 bytes[body_start + 7],
472 ])
473 .max(8_000);
474 bits_per_sample =
475 u16::from_le_bytes([bytes[body_start + 14], bytes[body_start + 15]]);
476 } else if chunk_id == MAGIC_WAV_DATA {
477 pcm_bytes = &bytes[body_start..body_end];
478 }
479 let padded: usize = chunk_size + (chunk_size & 1);
480 cursor = body_start.saturating_add(padded);
481 }
482 if pcm_bytes.is_empty() {
483 return Err("WAV file contained no data chunk".to_string());
484 }
485 let samples: Vec<f32> = if bits_per_sample == 16 {
486 let inv_scale: f32 = 1.0 / 32_768.0;
487 let chunks: &[[u8; 2]] = pcm_bytes.as_chunks::<2>().0;
488 let mut out: Vec<f32> = Vec::with_capacity(chunks.len());
489 for pair in chunks.iter() {
490 let s: i16 = i16::from_le_bytes(*pair);
491 out.push((s as f32) * inv_scale);
492 }
493 out
494 } else if bits_per_sample == 8 {
495 let inv_scale: f32 = 1.0 / 128.0;
496 let mut out: Vec<f32> = Vec::with_capacity(pcm_bytes.len());
497 for b in pcm_bytes.iter().copied() {
498 out.push(((b as f32) - 128.0) * inv_scale);
499 }
500 out
501 } else {
502 return Err("unsupported WAV bit depth (expected 8 or 16 bit PCM)".to_string());
503 };
504 let frames_total: usize = samples.len() / (channels as usize).max(1);
505 let duration_secs: f32 = (frames_total as f32) / (sample_rate as f32).max(1.0);
506 let waveform_peaks: Vec<f32> = Self::compute_waveform_peaks(&samples, 48);
507 Ok(AudioTrack {
508 metadata: MediaMetadata {
509 title: title.to_string(),
510 width: 0,
511 height: 0,
512 duration_secs,
513 page_count: 1,
514 frame_count: frames_total,
515 sample_rate_hz: sample_rate,
516 channels,
517 format_label: format!(
518 "WAV · {:.1} kHz · {}",
519 (sample_rate as f32) / 1000.0,
520 if channels == 1 { "Mono" } else { "Stereo" }
521 ),
522 },
523 codec: AudioCodec::Wav,
524 samples,
525 waveform_peaks,
526 state: PlaybackState::Idle,
527 current_time_secs: 0.0,
528 volume: 0.85,
529 muted: false,
530 playback_rate: 1.0,
531 looping: true,
532 })
533 }
534
535 pub fn parse_pdf(bytes: &[u8]) -> Result<PdfDocument, String> {
545 if bytes.len() < 8 || !bytes.starts_with(MAGIC_PDF) {
546 return Err("invalid PDF signature (expected %PDF-)".to_string());
547 }
548 let text: String = String::from_utf8_lossy(bytes).into_owned();
549 let version: String = text
550 .lines()
551 .next()
552 .and_then(|line: &str| line.strip_prefix(PREFIX_PDF))
553 .map(|v: &str| v.trim().to_string())
554 .filter(|v: &String| !v.is_empty())
555 .unwrap_or_else(|| "1.7".to_string());
556 let title: String = Self::extract_pdf_dict_string(&text, "/Title")
557 .unwrap_or_else(|| "Untitled PDF Document".to_string());
558 let author: String =
559 Self::extract_pdf_dict_string(&text, "/Author").unwrap_or_else(|| "euv".to_string());
560 let mut extracted_runs: Vec<String> = Vec::new();
561 let raw_bytes: &[u8] = text.as_bytes();
562 let mut i: usize = 0;
563 while i < raw_bytes.len() {
564 if raw_bytes[i] == BYTE_PAREN_OPEN {
565 let start: usize = i + 1;
566 let mut j: usize = start;
567 let mut depth: i32 = 1;
568 while j < raw_bytes.len() && depth > 0 {
569 if raw_bytes[j] == b'\\' && j + 1 < raw_bytes.len() {
570 j += 2;
571 continue;
572 }
573 if raw_bytes[j] == BYTE_PAREN_OPEN {
574 depth += 1;
575 } else if raw_bytes[j] == BYTE_PAREN_CLOSE {
576 depth -= 1;
577 if depth == 0 {
578 break;
579 }
580 }
581 j += 1;
582 }
583 let tail: &str = text.get(j..).unwrap_or("");
584 let trimmed_tail: &str = tail.trim_start_matches(')').trim_start();
585 if trimmed_tail.starts_with("Tj") || trimmed_tail.starts_with("] TJ") {
586 let run: String = text[start..j]
587 .replace("\\(", "(")
588 .replace("\\)", ")")
589 .replace("\\\\", "\\")
590 .trim()
591 .to_string();
592 if !run.is_empty() {
593 extracted_runs.push(run);
594 }
595 }
596 i = j.saturating_add(1);
597 } else {
598 i += 1;
599 }
600 }
601 let declared_pages: usize = text
602 .matches("/Type /Page")
603 .count()
604 .saturating_sub(text.matches("/Type /Pages").count())
605 .max(1);
606 let mut pages: Vec<PdfPage> = Vec::with_capacity(declared_pages);
607 let per_page: usize = extracted_runs.len().div_ceil(declared_pages).max(1);
608 for p_idx in 0..declared_pages {
609 let start: usize = p_idx.saturating_mul(per_page);
610 let end: usize = start.saturating_add(per_page).min(extracted_runs.len());
611 let mut blocks: Vec<String> = if start < end {
612 extracted_runs[start..end].to_vec()
613 } else {
614 Vec::new()
615 };
616 if blocks.is_empty() {
617 blocks.push(format!(
618 "Page {} content stream parsed from PDF {version}.",
619 p_idx + 1
620 ));
621 }
622 let page_title: String = blocks
623 .first()
624 .cloned()
625 .unwrap_or_else(|| format!("Page {}", p_idx + 1));
626 pages.push(PdfPage {
627 page_number: p_idx + 1,
628 width_pt: 595.0,
629 height_pt: 842.0,
630 title: page_title,
631 text_blocks: blocks,
632 preview_image: None,
633 });
634 }
635 Ok(PdfDocument {
636 title,
637 author,
638 version,
639 pages,
640 current_page: 0,
641 zoom: 1.0,
642 })
643 }
644
645 #[must_use]
655 pub fn parse_html(raw: &str) -> HtmlDocument {
656 let mut title: String = String::new();
657 let mut blocks: Vec<HtmlBlock> = Vec::new();
658 let mut links_count: usize = 0;
659 let bytes: &[u8] = raw.as_bytes();
660 let mut i: usize = 0;
661 let mut current_kind: Option<HtmlNodeKind> = None;
662 let mut current_href: Option<String> = None;
663 let mut in_title: bool = false;
664 let mut in_script_or_style: bool = false;
665 let mut buf: String = String::new();
666 while i < bytes.len() {
667 if bytes[i] == BYTE_ANGLE_OPEN {
668 let text_chunk: String = Self::decode_html_entities(buf.trim());
669 buf.clear();
670 if !text_chunk.is_empty() && !in_script_or_style {
671 if in_title {
672 title = text_chunk;
673 } else {
674 let kind: HtmlNodeKind = current_kind.unwrap_or(HtmlNodeKind::Paragraph);
675 if kind == HtmlNodeKind::Link {
676 links_count += 1;
677 }
678 blocks.push(HtmlBlock {
679 kind,
680 text: text_chunk,
681 href: current_href.clone(),
682 src: None,
683 });
684 }
685 }
686 let Some(close_rel) = raw[i..].find('>') else {
687 break;
688 };
689 let tag_inner: &str = raw[i + 1..i + close_rel].trim();
690 let tag_b: &[u8] = tag_inner.as_bytes();
691 if Self::starts_with_ignore_ascii_case(tag_b, b"script")
692 || Self::starts_with_ignore_ascii_case(tag_b, b"style")
693 {
694 in_script_or_style = true;
695 } else if Self::starts_with_ignore_ascii_case(tag_b, b"/script")
696 || Self::starts_with_ignore_ascii_case(tag_b, b"/style")
697 {
698 in_script_or_style = false;
699 } else if Self::starts_with_ignore_ascii_case(tag_b, b"title") {
700 in_title = true;
701 } else if Self::starts_with_ignore_ascii_case(tag_b, b"/title") {
702 in_title = false;
703 } else if Self::starts_with_ignore_ascii_case(tag_b, b"hr") {
704 blocks.push(HtmlBlock {
705 kind: HtmlNodeKind::HorizontalRule,
706 text: String::new(),
707 href: None,
708 src: None,
709 });
710 } else if Self::starts_with_ignore_ascii_case(tag_b, b"img") {
711 let src_val: Option<String> = Self::extract_html_attr(tag_inner, "src");
712 let alt_val: String = Self::extract_html_attr(tag_inner, "alt")
713 .unwrap_or_else(|| "Embedded Image".to_string());
714 blocks.push(HtmlBlock {
715 kind: HtmlNodeKind::Image,
716 text: alt_val,
717 href: None,
718 src: src_val,
719 });
720 } else if Self::starts_with_ignore_ascii_case(tag_b, b"h1") {
721 current_kind = Some(HtmlNodeKind::Heading(1));
722 } else if Self::starts_with_ignore_ascii_case(tag_b, b"h2") {
723 current_kind = Some(HtmlNodeKind::Heading(2));
724 } else if Self::starts_with_ignore_ascii_case(tag_b, b"h3") {
725 current_kind = Some(HtmlNodeKind::Heading(3));
726 } else if Self::starts_with_ignore_ascii_case(tag_b, b"blockquote") {
727 current_kind = Some(HtmlNodeKind::Blockquote);
728 } else if Self::starts_with_ignore_ascii_case(tag_b, b"pre")
729 || Self::starts_with_ignore_ascii_case(tag_b, b"code")
730 {
731 current_kind = Some(HtmlNodeKind::CodeBlock);
732 } else if Self::starts_with_ignore_ascii_case(tag_b, b"li") {
733 current_kind = Some(HtmlNodeKind::ListItem);
734 } else if Self::starts_with_ignore_ascii_case(tag_b, b"a ")
735 || tag_b.eq_ignore_ascii_case(b"a")
736 {
737 current_kind = Some(HtmlNodeKind::Link);
738 current_href = Self::extract_html_attr(tag_inner, "href");
739 } else if Self::starts_with_ignore_ascii_case(tag_b, b"p ")
740 || tag_b.eq_ignore_ascii_case(b"p")
741 {
742 current_kind = Some(HtmlNodeKind::Paragraph);
743 } else if tag_b.starts_with(b"/") {
744 current_kind = None;
745 current_href = None;
746 }
747 i += close_rel + 1;
748 } else {
749 let ch: char = raw[i..].chars().next().unwrap_or(' ');
750 buf.push(ch);
751 i += ch.len_utf8();
752 }
753 }
754 let trailing: String = Self::decode_html_entities(buf.trim());
755 if !trailing.is_empty() && !in_script_or_style {
756 blocks.push(HtmlBlock {
757 kind: current_kind.unwrap_or(HtmlNodeKind::Paragraph),
758 text: trailing,
759 href: current_href,
760 src: None,
761 });
762 }
763 if title.is_empty() {
764 title = blocks
765 .iter()
766 .find(|b: &&HtmlBlock| matches!(b.get_kind(), HtmlNodeKind::Heading(_)))
767 .map(|b: &HtmlBlock| b.get_text().clone())
768 .unwrap_or_else(|| "HTML Document".to_string());
769 }
770 HtmlDocument {
771 title,
772 raw_html: raw.to_string(),
773 blocks,
774 links_count,
775 }
776 }
777
778 pub fn parse_and_rasterize_svg(
790 raw_svg: &str,
791 out_w: u32,
792 out_h: u32,
793 ) -> Result<SvgDocument, String> {
794 if !raw_svg.contains(TAG_SVG_OPEN) {
795 return Err("invalid SVG document (missing <svg> root)".to_string());
796 }
797 let w: u32 = out_w.clamp(16, 512);
798 let h: u32 = out_h.clamp(16, 512);
799 let mut vb_w: f32 = w as f32;
800 let mut vb_h: f32 = h as f32;
801 if let Some(vb_str) = Self::extract_html_attr(raw_svg, "viewBox") {
802 let nums: Vec<f32> = vb_str
803 .split_whitespace()
804 .filter_map(|s: &str| s.parse::<f32>().ok())
805 .collect();
806 if nums.len() >= 4 {
807 vb_w = nums[2].max(1.0);
808 vb_h = nums[3].max(1.0);
809 }
810 }
811 let scale_x: f32 = (w as f32) / vb_w;
812 let scale_y: f32 = (h as f32) / vb_h;
813 let mut pixels: Vec<u8> = vec![0; (w as usize) * (h as usize) * 4];
814 let mut primitive_count: usize = 0;
815 let mut cursor: usize = 0;
816 while let Some(open_rel) = raw_svg[cursor..].find('<') {
817 let start: usize = cursor + open_rel;
818 let Some(close_rel) = raw_svg[start..].find('>') else {
819 break;
820 };
821 let tag: &str = raw_svg[start + 1..start + close_rel].trim();
822 cursor = start + close_rel + 1;
823 if tag.starts_with("rect") {
824 let x: f32 = Self::attr_f32(tag, "x", 0.0) * scale_x;
825 let y: f32 = Self::attr_f32(tag, "y", 0.0) * scale_y;
826 let rw: f32 = Self::attr_f32(tag, "width", vb_w) * scale_x;
827 let rh: f32 = Self::attr_f32(tag, "height", vb_h) * scale_y;
828 let col: Color = Self::parse_hex_color(
829 Self::extract_html_attr(tag, "fill")
830 .as_deref()
831 .unwrap_or("#0F172A"),
832 );
833 Self::fill_rect_rgba(&mut pixels, w, h, Rect::new(x, y, rw, rh), col);
834 primitive_count += 1;
835 } else if tag.starts_with("circle") {
836 let cx: f32 = Self::attr_f32(tag, "cx", vb_w * 0.5) * scale_x;
837 let cy: f32 = Self::attr_f32(tag, "cy", vb_h * 0.5) * scale_y;
838 let r: f32 = Self::attr_f32(tag, "r", 16.0) * scale_x.min(scale_y);
839 let col: Color = Self::parse_hex_color(
840 Self::extract_html_attr(tag, "fill")
841 .as_deref()
842 .unwrap_or("#38BDF8"),
843 );
844 Self::fill_circle_rgba(&mut pixels, w, h, cx, cy, r, col);
845 primitive_count += 1;
846 } else if tag.starts_with("line") {
847 let x1: f32 = Self::attr_f32(tag, "x1", 0.0) * scale_x;
848 let y1: f32 = Self::attr_f32(tag, "y1", 0.0) * scale_y;
849 let x2: f32 = Self::attr_f32(tag, "x2", vb_w) * scale_x;
850 let y2: f32 = Self::attr_f32(tag, "y2", vb_h) * scale_y;
851 let col: Color = Self::parse_hex_color(
852 Self::extract_html_attr(tag, "stroke")
853 .as_deref()
854 .unwrap_or("#FFFFFF"),
855 );
856 Self::draw_line_rgba(
857 &mut pixels,
858 w,
859 h,
860 Point::new(x1, y1),
861 Point::new(x2, y2),
862 col,
863 );
864 primitive_count += 1;
865 }
866 }
867 Ok(SvgDocument {
868 view_box_width: vb_w,
869 view_box_height: vb_h,
870 raw_svg: raw_svg.to_string(),
871 rasterized: ImageBuffer::new(w, h, pixels),
872 primitive_count,
873 })
874 }
875
876 #[must_use]
887 pub fn compute_waveform_peaks(samples: &[f32], bars: usize) -> Vec<f32> {
888 let count: usize = bars.max(8);
889 if samples.is_empty() {
890 return vec![0.25; count];
891 }
892 let step: usize = (samples.len() / count).max(1);
893 let mut peaks: Vec<f32> = Vec::with_capacity(count);
894 for i in 0..count {
895 let start: usize = (i * step).min(samples.len());
896 let end: usize = (start + step).min(samples.len());
897 let mut sum_sq: f32 = 0.0;
898 let len: usize = end.saturating_sub(start).max(1);
899 for s in &samples[start..end] {
900 sum_sq += (*s) * (*s);
901 }
902 let rms: f32 = (sum_sq / (len as f32)).sqrt();
903 peaks.push((rms * 1.45).clamp(0.10, 1.0));
904 }
905 peaks
906 }
907
908 #[must_use]
922 pub fn synthesize_frame(
923 width: u32,
924 height: u32,
925 bg: Color,
926 accent: Color,
927 frame_idx: usize,
928 ) -> ImageBuffer {
929 let w: u32 = width.max(16);
930 let h: u32 = height.max(16);
931 let mut pixels: Vec<u8> = vec![0; (w as usize) * (h as usize) * 4];
932 let phase: f32 = (frame_idx as f32) * 0.55;
933 let orb_x: f32 = (w as f32) * (0.5 + 0.28 * phase.cos());
934 let orb_y: f32 = (h as f32) * (0.48 + 0.18 * (phase * 1.3).sin());
935 let orb_r: f32 = (w.min(h) as f32) * 0.22;
936 let bg_r: f32 = bg.get_r() as f32;
937 let bg_g: f32 = bg.get_g() as f32;
938 let bg_b: f32 = bg.get_b() as f32;
939 let ac_r: f32 = accent.get_r() as f32;
940 let ac_g: f32 = accent.get_g() as f32;
941 let ac_b: f32 = accent.get_b() as f32;
942 for y in 0..h {
943 let fy: f32 = y as f32;
944 let v: f32 = fy / (h as f32);
945 let row: usize = (y as usize) * (w as usize) * 4;
946 for x in 0..w {
947 let fx: f32 = x as f32;
948 let u: f32 = fx / (w as f32);
949 let dx: f32 = fx - orb_x;
950 let dy: f32 = fy - orb_y;
951 let dist: f32 = (dx * dx + dy * dy).sqrt();
952 let glow: f32 = (1.0 - (dist / (orb_r * 2.2)).clamp(0.0, 1.0)).powf(2.0);
953 let horizon: f32 = if v > 0.68 { (v - 0.68) * 1.4 } else { 0.0 };
954 let wave: f32 = ((u * 8.0 + phase).sin() * 0.5 + 0.5) * horizon;
955 let mix: f32 = (glow * 0.85 + wave * 0.45 + v * 0.18).clamp(0.0, 1.0);
956 let idx: usize = row + (x as usize) * 4;
957 pixels[idx] = (bg_r + (ac_r - bg_r) * mix).clamp(0.0, 255.0) as u8;
958 pixels[idx + 1] = (bg_g + (ac_g - bg_g) * mix).clamp(0.0, 255.0) as u8;
959 pixels[idx + 2] = (bg_b + (ac_b - bg_b) * mix).clamp(0.0, 255.0) as u8;
960 pixels[idx + 3] = 255;
961 }
962 }
963 ImageBuffer::new(w, h, pixels)
964 }
965
966 #[must_use]
977 fn extract_pdf_dict_string(text: &str, key: &str) -> Option<String> {
978 let pos: usize = text.find(key)?;
979 let rest: &str = text.get(pos + key.len()..)?.trim_start();
980 let after_open: &str = rest.strip_prefix('(')?;
981 let close: usize = after_open.find(')')?;
982 let val: String = after_open[..close].trim().to_string();
983 if val.is_empty() { None } else { Some(val) }
984 }
985
986 #[must_use]
997 fn extract_html_attr(tag: &str, attr: &str) -> Option<String> {
998 let needle_dq: String = format!("{attr}=\"");
999 if let Some(pos) = tag.find(&needle_dq) {
1000 let rest: &str = &tag[pos + needle_dq.len()..];
1001 let end: usize = rest.find('"')?;
1002 return Some(rest[..end].to_string());
1003 }
1004 let needle_sq: String = format!("{attr}='");
1005 if let Some(pos) = tag.find(&needle_sq) {
1006 let rest: &str = &tag[pos + needle_sq.len()..];
1007 let end: usize = rest.find('\'')?;
1008 return Some(rest[..end].to_string());
1009 }
1010 None
1011 }
1012
1013 #[must_use]
1025 fn attr_f32(tag: &str, attr: &str, default: f32) -> f32 {
1026 Self::extract_html_attr(tag, attr)
1027 .and_then(|s: String| s.trim_end_matches("px").parse::<f32>().ok())
1028 .unwrap_or(default)
1029 }
1030
1031 #[must_use]
1041 fn decode_html_entities(s: &str) -> String {
1042 s.replace("&", "&")
1043 .replace("<", "<")
1044 .replace(">", ">")
1045 .replace(""", "\"")
1046 .replace("'", "'")
1047 .replace(" ", " ")
1048 }
1049
1050 #[must_use]
1060 fn parse_hex_color(raw: &str) -> Color {
1061 let trimmed: &str = raw.trim().trim_start_matches('#');
1062 if trimmed.len() == 6
1063 && let Ok(val) = u32::from_str_radix(trimmed, 16)
1064 {
1065 return Color::hex(val);
1066 }
1067 Color::hex(0x38BDF8)
1068 }
1069
1070 fn fill_rect_rgba(pixels: &mut [u8], w: u32, h: u32, rect: Rect, color: Color) {
1080 let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(w);
1081 let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(h);
1082 let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(w);
1083 let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(h);
1084 let rgba: [u8; 4] = color.to_rgba_bytes();
1085 for py in y0..y1 {
1086 let row: usize = (py as usize) * (w as usize) * 4;
1087 for px in x0..x1 {
1088 let idx: usize = row + (px as usize) * 4;
1089 pixels[idx..idx + 4].copy_from_slice(&rgba);
1090 }
1091 }
1092 }
1093
1094 fn fill_circle_rgba(pixels: &mut [u8], w: u32, h: u32, cx: f32, cy: f32, r: f32, color: Color) {
1106 let pad: f32 = r + 1.5;
1107 let x0: u32 = ((cx - pad).floor().max(0.0) as u32).min(w);
1108 let y0: u32 = ((cy - pad).floor().max(0.0) as u32).min(h);
1109 let x1: u32 = ((cx + pad).ceil().max(0.0) as u32).min(w);
1110 let y1: u32 = ((cy + pad).ceil().max(0.0) as u32).min(h);
1111 let rgba: [u8; 4] = color.to_rgba_bytes();
1112 let src_a: f32 = (rgba[3] as f32) / 255.0;
1113 for py in y0..y1 {
1114 let dy: f32 = (py as f32) + 0.5 - cy;
1115 let row: usize = (py as usize) * (w as usize) * 4;
1116 for px in x0..x1 {
1117 let dx: f32 = (px as f32) + 0.5 - cx;
1118 let dist: f32 = (dx * dx + dy * dy).sqrt();
1119 let cov: f32 = (r + 0.5 - dist).clamp(0.0, 1.0) * src_a;
1120 if cov <= 0.0 {
1121 continue;
1122 }
1123 let idx: usize = row + (px as usize) * 4;
1124 if cov >= 0.999 {
1125 pixels[idx..idx + 4].copy_from_slice(&rgba);
1126 } else {
1127 let inv: f32 = 1.0 - cov;
1128 pixels[idx] =
1129 ((rgba[0] as f32) * cov + (pixels[idx] as f32) * inv).round() as u8;
1130 pixels[idx + 1] =
1131 ((rgba[1] as f32) * cov + (pixels[idx + 1] as f32) * inv).round() as u8;
1132 pixels[idx + 2] =
1133 ((rgba[2] as f32) * cov + (pixels[idx + 2] as f32) * inv).round() as u8;
1134 pixels[idx + 3] = 255;
1135 }
1136 }
1137 }
1138 }
1139
1140 fn draw_line_rgba(pixels: &mut [u8], w: u32, h: u32, from: Point, to: Point, color: Color) {
1151 let dx: f32 = to.get_x() - from.get_x();
1152 let dy: f32 = to.get_y() - from.get_y();
1153 let steps: usize = (dx.abs().max(dy.abs()).ceil() as usize).max(1);
1154 let rgba: [u8; 4] = color.to_rgba_bytes();
1155 for i in 0..=steps {
1156 let t: f32 = (i as f32) / (steps as f32);
1157 let px: i32 = (from.get_x() + dx * t).round() as i32;
1158 let py: i32 = (from.get_y() + dy * t).round() as i32;
1159 if px >= 0 && py >= 0 && (px as u32) < w && (py as u32) < h {
1160 let idx: usize = ((py as usize) * (w as usize) + (px as usize)) * 4;
1161 pixels[idx..idx + 4].copy_from_slice(&rgba);
1162 }
1163 }
1164 }
1165}