1extern crate alloc;
7
8use alloc::format;
9use alloc::string::String;
10
11#[derive(Debug, Clone, PartialEq)]
13pub struct MediaSourceCandidate {
14 pub src: String,
15 pub type_attr: Option<String>,
16 pub media_attr: Option<String>,
17}
18
19pub fn can_play_type(mime_type: &str) -> &'static str {
24 let raw = mime_type.trim();
25 if raw.is_empty() {
26 return "";
27 }
28
29 let lower = raw.to_ascii_lowercase();
30
31 let mut parts = lower.split(';');
33 let base_mime = parts.next().unwrap_or("").trim();
34 let params_str = parts.next().unwrap_or("").trim();
35
36 let codec_param = if !params_str.is_empty() {
38 let p_trimmed = params_str.trim();
39 if let Some(rest) = p_trimmed.strip_prefix("codecs=") {
40 let val = rest.trim().trim_matches('"').trim_matches('\'').trim();
41 Some(val)
42 } else {
43 None
44 }
45 } else {
46 None
47 };
48
49 match base_mime {
50 "video/mp4" => {
51 if let Some(codec) = codec_param {
52 if codec.starts_with("avc1") || codec.starts_with("mp4v") {
54 "probably"
55 } else if codec.starts_with("mp4a") {
56 "maybe"
58 } else {
59 "" }
61 } else {
62 "maybe"
63 }
64 }
65 "audio/mp4" => {
66 if let Some(codec) = codec_param {
67 if codec.starts_with("mp4a") || codec.starts_with("mp3") {
68 "probably"
69 } else {
70 ""
71 }
72 } else {
73 "maybe"
74 }
75 }
76 "video/webm" => {
77 if let Some(codec) = codec_param {
78 if codec.starts_with("vp8") || codec.starts_with("vorbis") {
79 "probably"
80 } else {
81 ""
82 }
83 } else {
84 "maybe"
85 }
86 }
87 "audio/webm" => {
88 if let Some(codec) = codec_param {
89 if codec.starts_with("vorbis") || codec.starts_with("opus") {
90 "probably"
91 } else {
92 ""
93 }
94 } else {
95 "maybe"
96 }
97 }
98 "audio/wav" | "audio/x-wav" | "audio/wave" => "probably",
99 "audio/mpeg" | "audio/mp3" => "probably",
100 _ => "",
101 }
102}
103
104fn is_supported_media_extension(path: &str, parent_tag: &str) -> bool {
106 let lower = path.to_ascii_lowercase();
107 let ext = lower.rsplit('.').next().unwrap_or("");
108 match ext {
109 "mp4" | "m4v" => true,
110 "webm" => true,
111 "wav" => parent_tag == "audio" || parent_tag == "video",
112 "mp3" => parent_tag == "audio" || parent_tag == "video",
113 _ => false,
114 }
115}
116
117fn evaluate_media_attr(media_query: &str, viewport_width: u32) -> bool {
119 let mq = media_query.trim().to_ascii_lowercase();
120 if mq.is_empty() || mq == "all" || mq == "screen" {
121 return true;
122 }
123
124 if let Some(idx) = mq.find("min-width") {
126 if let Some(colon) = mq.get(idx..).and_then(|s| s.find(':')) {
127 let rest = mq.get(idx + colon + 1..).unwrap_or("");
128 let num_str: String = rest.chars().filter(|c| c.is_ascii_digit()).collect();
129 if let Ok(val) = num_str.parse::<u32>() {
130 if viewport_width < val {
131 return false;
132 }
133 }
134 }
135 }
136
137 if let Some(idx) = mq.find("max-width") {
138 if let Some(colon) = mq.get(idx..).and_then(|s| s.find(':')) {
139 let rest = mq.get(idx + colon + 1..).unwrap_or("");
140 let num_str: String = rest.chars().filter(|c| c.is_ascii_digit()).collect();
141 if let Ok(val) = num_str.parse::<u32>() {
142 if viewport_width > val {
143 return false;
144 }
145 }
146 }
147 }
148
149 true
150}
151
152pub fn select_media_source(
158 parent_tag: &str,
159 parent_src: Option<&str>,
160 sources: &[MediaSourceCandidate],
161 viewport_width: u32,
162 _viewport_height: u32,
163) -> Option<String> {
164 if let Some(src) = parent_src {
165 let trimmed = src.trim();
166 if !trimmed.is_empty() {
167 return Some(String::from(trimmed));
168 }
169 }
170
171 for candidate in sources {
172 let src = candidate.src.trim();
173 if src.is_empty() {
174 continue;
175 }
176
177 if let Some(ref mq) = candidate.media_attr {
179 if !evaluate_media_attr(mq, viewport_width) {
180 continue;
181 }
182 }
183
184 if let Some(ref type_str) = candidate.type_attr {
186 let result = can_play_type(type_str);
187 if result.is_empty() {
188 continue; }
190 } else {
191 if !is_supported_media_extension(src, parent_tag) {
193 continue;
194 }
195 }
196
197 return Some(String::from(src));
198 }
199
200 None
201}
202
203pub fn format_media_time(seconds: f64) -> String {
205 let total_secs = seconds.max(0.0) as u64;
206 let h = total_secs / 3600;
207 let m = (total_secs % 3600) / 60;
208 let s = total_secs % 60;
209 if h > 0 {
210 format!("{:02}:{:02}:{:02}", h, m, s)
211 } else {
212 format!("{:02}:{:02}", m, s)
213 }
214}
215
216#[derive(Debug, Clone, PartialEq)]
218pub struct MediaControlsState {
219 pub current_time: f64,
220 pub duration: f64,
221 pub volume: f32,
222 pub muted: bool,
223 pub paused: bool,
224 pub fullscreen: bool,
225 pub playback_rate: f32,
226 pub hud_text: Option<String>,
227 pub hud_ticks: u32,
228 pub subtitle_tracks: alloc::vec::Vec<crate::os_lib::web_engine::vtt::SubtitleTrack>,
229 pub active_track_idx: Option<usize>,
230 pub current_quality_idx: usize,
231 pub abr: crate::os_lib::mse::AbrController,
232}
233
234impl MediaControlsState {
235 pub const QUALITIES: [&'static str; 5] = ["Auto", "1080p HD", "720p HD", "480p", "360p"];
236
237 pub fn new(duration: f64) -> Self {
238 Self {
239 current_time: 0.0,
240 duration: duration.max(0.0),
241 volume: 1.0,
242 muted: false,
243 paused: true,
244 fullscreen: false,
245 playback_rate: 1.0,
246 hud_text: None,
247 hud_ticks: 0,
248 subtitle_tracks: alloc::vec::Vec::new(),
249 active_track_idx: None,
250 current_quality_idx: 0,
251 abr: crate::os_lib::mse::AbrController::new(),
252 }
253 }
254
255 pub fn current_quality(&self) -> &'static str {
257 Self::QUALITIES[self.current_quality_idx % Self::QUALITIES.len()]
258 }
259
260 pub fn quality_badge(&self) -> &'static str {
262 match self.current_quality_idx % Self::QUALITIES.len() {
263 0 => "AUTO",
264 1 => "FHD",
265 2 => "HD",
266 3 => "480",
267 4 => "360",
268 _ => "HD",
269 }
270 }
271
272 pub fn cycle_quality(&mut self) -> (&'static str, usize, usize) {
275 self.current_quality_idx = (self.current_quality_idx + 1) % Self::QUALITIES.len();
276 match self.current_quality_idx {
277 0 => self.abr.set_auto_mode(),
278 idx => self.abr.set_manual_index(idx - 1),
279 }
280 let name = self.current_quality();
281 (name, self.current_quality_idx + 1, Self::QUALITIES.len())
282 }
283
284 pub fn effective_quality_index(
286 &mut self,
287 reps: &[crate::os_lib::mse::StreamRepresentation],
288 buffer_ahead_sec: f64,
289 total_frames: u64,
290 dropped_frames: u64,
291 ) -> usize {
292 if reps.is_empty() {
293 return 0;
294 }
295 match self.abr.mode {
296 crate::os_lib::mse::AbrMode::Manual(_) => {
297 let target_height = match self.current_quality_idx {
298 1 => 1080,
299 2 => 720,
300 3 => 480,
301 4 => 360,
302 _ => 0,
303 };
304 if target_height > 0 {
305 let mut best_idx = 0;
306 let mut min_diff = u32::MAX;
307 for (i, rep) in reps.iter().enumerate() {
308 let diff = (rep.height as i32 - target_height).unsigned_abs();
309 if diff < min_diff {
310 min_diff = diff;
311 best_idx = i;
312 }
313 }
314 self.abr.set_manual_index(best_idx);
315 best_idx
316 } else {
317 self.abr.current_rep_index.min(reps.len() - 1)
318 }
319 }
320 crate::os_lib::mse::AbrMode::Auto => {
321 self.abr.evaluate_auto(reps, buffer_ahead_sec, total_frames, dropped_frames)
322 }
323 }
324 }
325
326 pub fn toggle_fullscreen(&mut self) -> bool {
328 self.fullscreen = !self.fullscreen;
329 self.fullscreen
330 }
331
332 pub fn set_subtitles(&mut self, vtt: crate::os_lib::web_engine::vtt::WebVtt) {
334 self.subtitle_tracks.clear();
335 self.subtitle_tracks.push(crate::os_lib::web_engine::vtt::SubtitleTrack::new(
336 "既定",
337 "und",
338 "subtitles",
339 vtt,
340 ));
341 self.active_track_idx = Some(0);
342 }
343
344 pub fn add_subtitle_track(&mut self, track: crate::os_lib::web_engine::vtt::SubtitleTrack) {
346 let is_first = self.subtitle_tracks.is_empty();
347 self.subtitle_tracks.push(track);
348 if is_first && self.active_track_idx.is_none() {
349 self.active_track_idx = Some(0);
350 }
351 }
352
353 pub fn cycle_subtitles(&mut self) -> Option<(String, usize, usize)> {
356 if self.subtitle_tracks.is_empty() {
357 self.active_track_idx = None;
358 return None;
359 }
360
361 match self.active_track_idx {
362 None => {
363 self.active_track_idx = Some(0);
364 }
365 Some(i) => {
366 if i + 1 < self.subtitle_tracks.len() {
367 self.active_track_idx = Some(i + 1);
368 } else {
369 self.active_track_idx = None; }
371 }
372 }
373
374 if let Some(idx) = self.active_track_idx {
375 let label = self.subtitle_tracks[idx].label.clone();
376 let total = self.subtitle_tracks.len();
377 Some((label, idx + 1, total))
378 } else {
379 None
380 }
381 }
382
383 pub fn active_subtitle_track(&self) -> Option<&crate::os_lib::web_engine::vtt::SubtitleTrack> {
385 self.active_track_idx.and_then(|idx| self.subtitle_tracks.get(idx))
386 }
387
388 pub fn toggle_subtitles(&mut self) -> bool {
390 if self.active_track_idx.is_some() {
391 self.active_track_idx = None;
392 false
393 } else if !self.subtitle_tracks.is_empty() {
394 self.active_track_idx = Some(0);
395 true
396 } else {
397 false
398 }
399 }
400
401 pub fn subtitles_enabled(&self) -> bool {
403 self.active_track_idx.is_some()
404 }
405
406 pub fn current_subtitle_text(&self) -> Option<String> {
408 self.active_subtitle_track().and_then(|t| t.vtt.active_text_at(self.current_time))
409 }
410
411 pub fn current_track_badge(&self) -> String {
413 if let Some(track) = self.active_subtitle_track() {
414 let lang = track.srclang.trim();
415 if !lang.is_empty() && lang != "und" {
416 lang.to_ascii_uppercase()
417 } else {
418 String::from("CC")
419 }
420 } else {
421 String::from("CC")
422 }
423 }
424
425 pub fn set_hud(&mut self, text: &str, ticks: u32) {
427 self.hud_text = Some(String::from(text));
428 self.hud_ticks = ticks;
429 }
430
431 pub fn tick_hud(&mut self) -> Option<&str> {
433 if self.hud_ticks > 0 {
434 self.hud_ticks -= 1;
435 self.hud_text.as_deref()
436 } else {
437 self.hud_text = None;
438 None
439 }
440 }
441
442 pub fn adjust_playback_rate(&mut self, step: i8) -> f32 {
444 let delta = (step as f32) * 0.25;
445 let new_rate = (self.playback_rate + delta).clamp(0.25, 2.0);
446 self.playback_rate = new_rate;
447 new_rate
448 }
449
450 pub fn progress_ratio(&self) -> f32 {
452 if self.duration <= 0.0 {
453 0.0
454 } else {
455 ((self.current_time / self.duration) as f32).clamp(0.0, 1.0)
456 }
457 }
458
459 pub fn format_display(&self) -> String {
461 format!(
462 "{} / {}",
463 format_media_time(self.current_time),
464 format_media_time(self.duration)
465 )
466 }
467
468 pub fn seek_by_ratio(&mut self, ratio: f32) {
470 let clamped = ratio.clamp(0.0, 1.0) as f64;
471 self.current_time = (self.duration * clamped).clamp(0.0, self.duration);
472 }
473
474 pub fn calculate_seek_time(click_x: i32, bar_x: i32, bar_width: i32, duration: f64) -> f64 {
476 if bar_width <= 0 || duration <= 0.0 {
477 return 0.0;
478 }
479 let offset = (click_x - bar_x).max(0);
480 let ratio = (offset as f64 / bar_width as f64).clamp(0.0, 1.0);
481 (duration * ratio).clamp(0.0, duration)
482 }
483
484 pub fn effective_volume(&self) -> f32 {
486 if self.muted {
487 0.0
488 } else {
489 self.volume
490 }
491 }
492
493 pub fn set_volume(&mut self, vol: f32) {
495 self.volume = vol.clamp(0.0, 1.0);
496 if self.volume == 0.0 {
497 self.muted = true;
498 } else if self.muted {
499 self.muted = false;
500 }
501 }
502
503 pub fn toggle_mute(&mut self) -> bool {
505 self.muted = !self.muted;
506 self.muted
507 }
508
509 pub fn toggle_play(&mut self) -> bool {
511 self.paused = !self.paused;
512 !self.paused
513 }
514}
515
516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
518pub enum MediaKeyAction {
519 TogglePlay,
520 ToggleMute,
521 ToggleFullscreen,
522 ToggleSubtitles,
523 CycleQuality, SeekRelative(i32), DirectSeekPercent(u8), VolumeRelative(i32), PlaybackRateStep(i8), None,
529}
530
531pub fn parse_media_key_action(keycode: u8, ascii: Option<char>) -> MediaKeyAction {
533 if let Some(c) = ascii {
534 match c {
535 ' ' | 'k' | 'K' => return MediaKeyAction::TogglePlay,
536 'm' | 'M' => return MediaKeyAction::ToggleMute,
537 'f' | 'F' => return MediaKeyAction::ToggleFullscreen,
538 'c' | 'C' => return MediaKeyAction::ToggleSubtitles,
539 'q' | 'Q' => return MediaKeyAction::CycleQuality,
540 'j' | 'J' => return MediaKeyAction::SeekRelative(-10),
541 'l' | 'L' => return MediaKeyAction::SeekRelative(10),
542 '>' | '.' => return MediaKeyAction::PlaybackRateStep(1),
543 '<' | ',' => return MediaKeyAction::PlaybackRateStep(-1),
544 '0'..='9' => {
545 let digit = (c as u8 - b'0') * 10;
546 return MediaKeyAction::DirectSeekPercent(digit);
547 }
548 _ => {}
549 }
550 }
551 match keycode {
552 0x39 => MediaKeyAction::TogglePlay, 0x21 => MediaKeyAction::ToggleFullscreen, 0x4B => MediaKeyAction::SeekRelative(-5), 0x4D => MediaKeyAction::SeekRelative(5), 0x48 => MediaKeyAction::VolumeRelative(10), 0x50 => MediaKeyAction::VolumeRelative(-10), _ => MediaKeyAction::None,
559 }
560}
561
562#[derive(Debug, Clone, Copy, PartialEq)]
564pub enum MediaClickRegion {
565 PlayPause,
566 SeekBar(f64), MuteToggle,
568 QualityToggle, SubtitleToggle, FullscreenToggle, Screen, None,
573}
574
575pub fn hit_test_media_controls(
577 local_x: i32,
578 rel_y: i32,
579 v_width: i32,
580 v_height: i32,
581 duration: f64,
582) -> MediaClickRegion {
583 if v_width <= 0 || v_height <= 0 || local_x < 0 || local_x > v_width || rel_y < 0 || rel_y > v_height {
584 return MediaClickRegion::None;
585 }
586 let bar_top = v_height.saturating_sub(40);
587 if rel_y >= bar_top {
588 let sb_w = v_width - 370;
590 if (40..=75).contains(&local_x) {
591 MediaClickRegion::PlayPause
592 } else if sb_w > 50 && local_x >= 80 && local_x <= 80 + sb_w {
593 let target = MediaControlsState::calculate_seek_time(local_x, 80, sb_w, duration);
594 MediaClickRegion::SeekBar(target)
595 } else if sb_w > 50 && local_x >= 80 + sb_w + 10 && local_x <= 80 + sb_w + 80 {
596 MediaClickRegion::MuteToggle
597 } else if local_x >= v_width - 150 && local_x <= v_width - 105 {
598 MediaClickRegion::QualityToggle
599 } else if local_x >= v_width - 100 && local_x <= v_width - 55 {
600 MediaClickRegion::SubtitleToggle
601 } else if local_x >= v_width - 50 && local_x <= v_width - 10 {
602 MediaClickRegion::FullscreenToggle
603 } else {
604 MediaClickRegion::None
605 }
606 } else {
607 MediaClickRegion::Screen
609 }
610}