1extern crate alloc;
7use alloc::string::String;
8use alloc::vec::Vec;
9
10pub fn write_proto_varint(mut v: u64, out: &mut Vec<u8>) {
13 while v >= 0x80 {
14 out.push(((v & 0x7f) as u8) | 0x80);
15 v >>= 7;
16 }
17 out.push(v as u8);
18}
19
20pub fn read_proto_varint(b: &[u8], pos: &mut usize) -> Option<u64> {
23 let mut v: u64 = 0;
24 for shift in (0..64).step_by(7) {
25 let x = *b.get(*pos)?;
26 *pos += 1;
27 v |= ((x & 0x7f) as u64) << shift;
28 if x & 0x80 == 0 {
29 return Some(v);
30 }
31 }
32 None
33}
34
35pub fn write_ump_varint(v: u64, out: &mut Vec<u8>) {
38 if v < (1 << 7) {
39 out.push(v as u8);
40 } else if v < (1 << 14) {
41 out.push(0x80 | ((v & 0x3f) as u8));
42 out.push((v >> 6) as u8);
43 } else if v < (1 << 21) {
44 out.push(0xc0 | ((v & 0x1f) as u8));
45 out.push((v >> 5) as u8);
46 out.push((v >> 13) as u8);
47 } else if v < (1 << 28) {
48 out.push(0xe0 | ((v & 0x0f) as u8));
49 out.push((v >> 4) as u8);
50 out.push((v >> 12) as u8);
51 out.push((v >> 20) as u8);
52 } else {
53 out.push(0xf0);
54 out.extend_from_slice(&(v as u32).to_le_bytes());
55 }
56}
57
58pub fn read_ump_varint(b: &[u8], pos: &mut usize) -> Option<u64> {
61 let first = *b.get(*pos)?;
62 let len = match first {
63 0x00..=0x7f => 1,
64 0x80..=0xbf => 2,
65 0xc0..=0xdf => 3,
66 0xe0..=0xef => 4,
67 _ => 5,
68 };
69 let bytes = b.get(*pos..*pos + len)?;
70 *pos += len;
71 let v = if len == 5 {
72 u32::from_le_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]) as u64
73 } else {
74 let mut v = (first & (0xffu8 >> len)) as u64;
75 for (i, &x) in bytes.iter().enumerate().skip(1) {
76 v |= (x as u64) << (8 * i - len);
77 }
78 v
79 };
80 Some(v)
81}
82
83pub const INITIAL_PO_TOKEN_BYTES: [u8; 10] = [
85 0x22, 0x08, 0xe2, 0x38, 0xe2, 0x3a, 0x88, 0xd6, 0xbe, 0x7c,
86];
87
88pub const INITIAL_POT_URL_PARAM: &str =
90 "IgjiMDIwMDkxNi0yMTozNTozNigCMgI4ODoEAAAABEIc4jjimDqI1r58Whdvd0pnY0NlX1d5VjFocnBrcmJ3U2dRYg";
91
92pub fn sanitize_sabr_request(body: &[u8]) -> Option<Vec<u8>> {
100 let mut pos = 0;
101 let mut needs_rewrite = false;
102
103 while pos < body.len() {
104 let key = read_proto_varint(body, &mut pos)?;
105 let (field, wt) = (key >> 3, key & 7);
106 match wt {
107 0 => { read_proto_varint(body, &mut pos)?; }
108 1 => { pos += 8; }
109 2 => {
110 let n = read_proto_varint(body, &mut pos)? as usize;
111 let end = pos.saturating_add(n).min(body.len());
112 if field == 19 {
113 let mut sc_pos = pos;
114 let mut found_f2 = false;
115 while sc_pos < end {
116 let sc_key = match read_proto_varint(body, &mut sc_pos) {
117 Some(k) => k,
118 None => break,
119 };
120 let (sc_field, sc_wt) = (sc_key >> 3, sc_key & 7);
121 if sc_field == 3 {
122 needs_rewrite = true;
123 }
124 if sc_field == 2 {
125 found_f2 = true;
126 }
127 match sc_wt {
128 0 => { if read_proto_varint(body, &mut sc_pos).is_none() { break; } }
129 1 => { sc_pos += 8; }
130 2 => {
131 let Some(sn) = read_proto_varint(body, &mut sc_pos) else { break; };
132 sc_pos = sc_pos.saturating_add(sn as usize).min(end);
133 }
134 5 => { sc_pos += 4; }
135 _ => break,
136 }
137 }
138 if !found_f2 {
139 needs_rewrite = true;
140 }
141 }
142 pos = end;
143 }
144 5 => { pos += 4; }
145 _ => return None,
146 }
147 }
148
149 if !needs_rewrite {
150 return None;
151 }
152
153 let mut out = Vec::with_capacity(body.len() + 16);
155 pos = 0;
156 while pos < body.len() {
157 let key_start = pos;
158 let key = read_proto_varint(body, &mut pos)?;
159 let (field, wt) = (key >> 3, key & 7);
160 match wt {
161 0 => {
162 read_proto_varint(body, &mut pos)?;
163 out.extend_from_slice(&body[key_start..pos]);
164 }
165 1 => {
166 pos += 8;
167 out.extend_from_slice(&body[key_start..pos]);
168 }
169 2 => {
170 let n = read_proto_varint(body, &mut pos)? as usize;
171 let end = pos.saturating_add(n).min(body.len());
172 if field == 19 {
173 let mut new_sc = Vec::new();
174 let mut sc_pos = pos;
175 let mut wrote_f2 = false;
176 while sc_pos < end {
177 let sc_start = sc_pos;
178 let sc_key = match read_proto_varint(body, &mut sc_pos) {
179 Some(k) => k,
180 None => break,
181 };
182 let (sc_field, sc_wt) = (sc_key >> 3, sc_key & 7);
183 match sc_wt {
184 0 => {
185 if read_proto_varint(body, &mut sc_pos).is_none() { break; }
186 if sc_field != 3 {
187 new_sc.extend_from_slice(&body[sc_start..sc_pos]);
188 }
189 }
190 1 => {
191 sc_pos += 8;
192 if sc_field != 3 {
193 new_sc.extend_from_slice(&body[sc_start..sc_pos]);
194 }
195 }
196 2 => {
197 let Some(sn) = read_proto_varint(body, &mut sc_pos) else { break; };
198 let sc_end = sc_pos.saturating_add(sn as usize).min(end);
199 sc_pos = sc_end;
200 if sc_field == 3 {
201 } else if sc_field == 2 {
203 new_sc.extend_from_slice(&body[sc_start..sc_pos]);
205 wrote_f2 = true;
206 } else {
207 new_sc.extend_from_slice(&body[sc_start..sc_pos]);
208 }
209 }
210 5 => {
211 sc_pos += 4;
212 if sc_field != 3 {
213 new_sc.extend_from_slice(&body[sc_start..sc_pos]);
214 }
215 }
216 _ => break,
217 }
218 }
219 if !wrote_f2 {
220 write_proto_varint((2 << 3) | 2, &mut new_sc);
221 write_proto_varint(INITIAL_PO_TOKEN_BYTES.len() as u64, &mut new_sc);
222 new_sc.extend_from_slice(&INITIAL_PO_TOKEN_BYTES);
223 }
224 write_proto_varint(key, &mut out);
225 write_proto_varint(new_sc.len() as u64, &mut out);
226 out.extend_from_slice(&new_sc);
227 } else {
228 out.extend_from_slice(&body[key_start..end]);
229 }
230 pos = end;
231 }
232 5 => {
233 pos += 4;
234 out.extend_from_slice(&body[key_start..pos]);
235 }
236 _ => break,
237 }
238 }
239
240 Some(out)
241}
242
243pub fn replace_or_append_query_param(url: &str, key: &str, new_value: &str) -> alloc::string::String {
246 let prefix1 = alloc::format!("?{}=", key);
247 let prefix2 = alloc::format!("&{}=", key);
248 let (match_start, prefix_len) = if let Some(idx) = url.find(&prefix1) {
249 (idx, prefix1.len())
250 } else if let Some(idx) = url.find(&prefix2) {
251 (idx, prefix2.len())
252 } else {
253 let mut res = alloc::string::String::from(url);
254 if res.contains('?') {
255 res.push('&');
256 } else {
257 res.push('?');
258 }
259 res.push_str(key);
260 res.push('=');
261 res.push_str(new_value);
262 return res;
263 };
264
265 let val_start = match_start + prefix_len;
266 let Some(value_and_rest) = url.get(val_start..) else {
267 return alloc::string::String::from(url);
268 };
269 let val_end = value_and_rest
270 .find('&')
271 .map(|i| val_start + i)
272 .unwrap_or(url.len());
273 let Some(prefix) = url.get(..val_start) else {
274 return alloc::string::String::from(url);
275 };
276 let Some(suffix) = url.get(val_end..) else {
277 return alloc::string::String::from(url);
278 };
279
280 let mut res = alloc::string::String::with_capacity(url.len() + new_value.len());
281 res.push_str(prefix);
282 res.push_str(new_value);
283 res.push_str(suffix);
284 res
285}
286
287pub fn ensure_query_param(url: &str, key: &str, default_value: &str) -> alloc::string::String {
290 let prefix1 = alloc::format!("?{}=", key);
291 let prefix2 = alloc::format!("&{}=", key);
292 if url.contains(&prefix1) || url.contains(&prefix2) {
293 return alloc::string::String::from(url);
294 }
295 let mut res = alloc::string::String::from(url);
296 if res.contains('?') {
297 res.push('&');
298 } else {
299 res.push('?');
300 }
301 res.push_str(key);
302 res.push('=');
303 res.push_str(default_value);
304 res
305}
306
307pub fn normalize_sabr_url(url: &str) -> alloc::string::String {
313 let Some((base_part, query_part)) = url.split_once('?') else {
314 return alloc::string::String::from(url);
315 };
316
317 let mut latest_cpn: Option<&str> = None;
318 let mut latest_pot: Option<&str> = None;
319 let mut kept_kvs = Vec::new();
320
321 for kv in query_part.split('&') {
322 if let Some(cpn_val) = kv.strip_prefix("cpn=") {
323 latest_cpn = Some(cpn_val);
324 } else if let Some(pot_val) = kv.strip_prefix("pot=") {
325 latest_pot = Some(pot_val);
326 } else if !kv.is_empty() {
327 kept_kvs.push(kv);
328 }
329 }
330
331 let mut new_url = alloc::string::String::with_capacity(url.len() + 32);
332 new_url.push_str(base_part);
333 new_url.push('?');
334 let joined = kept_kvs.join("&");
335 new_url.push_str(&joined);
336
337 if let Some(cpn) = latest_cpn {
338 if !joined.is_empty() {
339 new_url.push('&');
340 }
341 new_url.push_str("cpn=");
342 new_url.push_str(cpn);
343 }
344
345 if let Some(pot) = latest_pot {
346 if !joined.is_empty() || latest_cpn.is_some() {
347 new_url.push('&');
348 }
349 new_url.push_str("pot=");
350 new_url.push_str(pot);
351 } else {
352 if !joined.is_empty() || latest_cpn.is_some() {
353 new_url.push('&');
354 }
355 new_url.push_str("pot=");
356 new_url.push_str(INITIAL_POT_URL_PARAM);
357 }
358
359 new_url
360}
361
362pub fn generate_random_cpn(seed: u64) -> alloc::string::String {
365 const CHARSET: &[u8; 64] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
366 let mut state = if seed == 0 { 0x853c49e6748fea9b } else { seed };
367 let mut res = alloc::string::String::with_capacity(16);
368 for _ in 0..16 {
369 state ^= state >> 12;
370 state ^= state << 25;
371 state ^= state >> 27;
372 let v = state.wrapping_mul(0x2545F4914F6CDD1D);
373 let idx = (v as usize) % CHARSET.len();
374 res.push(CHARSET[idx] as char);
375 }
376 res
377}
378
379pub fn has_sps_reject(raw: &[u8]) -> bool {
382 let mut pos = 0;
383 while pos < raw.len() {
384 let (Some(ty), Some(size)) = (read_ump_varint(raw, &mut pos), read_ump_varint(raw, &mut pos)) else {
385 break;
386 };
387 let end = pos.saturating_add(size as usize).min(raw.len());
388 let payload = raw.get(pos..end).unwrap_or(&[]);
389 if ty == 58 {
390 let mut p_pos = 0;
392 while p_pos < payload.len() {
393 let Some(k) = read_proto_varint(payload, &mut p_pos) else { break };
394 let (f, wt) = (k >> 3, k & 7);
395 if f == 1 && wt == 0 {
396 if let Some(st) = read_proto_varint(payload, &mut p_pos) {
397 if st == 3 {
398 return true;
399 }
400 }
401 } else {
402 match wt {
403 0 => { let _ = read_proto_varint(payload, &mut p_pos); }
404 1 => { p_pos += 8; }
405 2 => {
406 if let Some(len) = read_proto_varint(payload, &mut p_pos) {
407 p_pos = p_pos.saturating_add(len as usize).min(payload.len());
408 }
409 }
410 5 => { p_pos += 4; }
411 _ => break,
412 }
413 }
414 }
415 }
416 pos = end;
417 }
418 false
419}
420
421#[derive(Debug, PartialEq, Eq, Clone)]
423pub struct UmpPart<'a> {
424 pub part_type: u64,
425 pub payload: &'a [u8],
426}
427
428pub fn parse_ump_parts<'a>(raw: &'a [u8]) -> Vec<UmpPart<'a>> {
431 let mut parts = Vec::new();
432 let mut pos = 0;
433 while pos < raw.len() {
434 let (Some(ty), Some(size)) = (read_ump_varint(raw, &mut pos), read_ump_varint(raw, &mut pos)) else {
435 break;
436 };
437 let end = pos.saturating_add(size as usize).min(raw.len());
438 if let Some(payload) = raw.get(pos..end) {
439 parts.push(UmpPart {
440 part_type: ty,
441 payload,
442 });
443 }
444 pos = end;
445 }
446 parts
447}
448
449pub fn extract_media_payloads(raw: &[u8]) -> Vec<u8> {
452 let parts = parse_ump_parts(raw);
453 let total_len: usize = parts.iter().filter(|p| p.part_type == 21).map(|p| p.payload.len()).sum();
454 let mut out = Vec::with_capacity(total_len);
455 for part in parts {
456 if part.part_type == 21 {
457 out.extend_from_slice(part.payload);
458 }
459 }
460 out
461}
462
463#[derive(Debug, Default, PartialEq, Eq, Clone)]
465pub struct NextRequestPolicy {
466 pub target_url: Option<alloc::string::String>,
468 pub backoff_ms: u64,
470 pub context_token: Vec<u8>,
472}
473
474pub fn extract_next_request_policy(raw: &[u8]) -> Option<NextRequestPolicy> {
477 let parts = parse_ump_parts(raw);
478 let p37 = parts.into_iter().find(|p| p.part_type == 37)?;
479 let b = p37.payload;
480 let mut pos = 0;
481 let mut policy = NextRequestPolicy::default();
482
483 while pos < b.len() {
484 let key = read_proto_varint(b, &mut pos)?;
485 let (field, wt) = (key >> 3, key & 7);
486 match wt {
487 0 => {
488 let v = read_proto_varint(b, &mut pos)?;
489 if field == 2 {
490 policy.backoff_ms = v;
491 }
492 }
493 1 => { pos += 8; }
494 2 => {
495 let len = read_proto_varint(b, &mut pos)? as usize;
496 let end = pos.saturating_add(len).min(b.len());
497 let data = &b[pos..end];
498 pos = end;
499 if field == 1 {
500 if let Ok(s) = core::str::from_utf8(data) {
501 policy.target_url = Some(alloc::string::String::from(s));
502 }
503 } else if field == 3 {
504 policy.context_token = data.to_vec();
505 }
506 }
507 5 => { pos += 4; }
508 _ => break,
509 }
510 }
511
512 Some(policy)
513}
514
515#[derive(Debug, Default, PartialEq, Eq, Clone)]
517pub struct PlaybackWindow {
518 pub current_media_time_ms: u64,
520 pub start_time_ms: u64,
522 pub duration_ms: u64,
524 pub sq_start: u64,
526 pub sq_end: u64,
528}
529
530pub fn parse_playback_window(body: &[u8]) -> Option<PlaybackWindow> {
533 let mut window = PlaybackWindow::default();
534 let mut pos = 0;
535 let mut found = false;
536
537 while pos < body.len() {
538 let key = read_proto_varint(body, &mut pos)?;
539 let (field, wt) = (key >> 3, key & 7);
540 match wt {
541 0 => { let _ = read_proto_varint(body, &mut pos)?; }
542 1 => { pos += 8; }
543 2 => {
544 let len = read_proto_varint(body, &mut pos)? as usize;
545 let end = pos.saturating_add(len).min(body.len());
546 let sub_data = &body[pos..end];
547 pos = end;
548
549 if field == 1 {
550 found = true;
551 let mut s_pos = 0;
553 while s_pos < sub_data.len() {
554 let Some(s_key) = read_proto_varint(sub_data, &mut s_pos) else { break };
555 let (s_field, s_wt) = (s_key >> 3, s_key & 7);
556 match s_wt {
557 0 => {
558 let v = match read_proto_varint(sub_data, &mut s_pos) {
559 Some(val) => val,
560 None => break,
561 };
562 if s_field == 28 {
563 window.current_media_time_ms = v;
564 }
565 }
566 1 => { s_pos += 8; }
567 2 => {
568 let Some(s_len) = read_proto_varint(sub_data, &mut s_pos) else { break };
569 s_pos = s_pos.saturating_add(s_len as usize).min(sub_data.len());
570 }
571 5 => { s_pos += 4; }
572 _ => break,
573 }
574 }
575 } else if field == 3 {
576 found = true;
577 let mut s_pos = 0;
579 while s_pos < sub_data.len() {
580 let Some(s_key) = read_proto_varint(sub_data, &mut s_pos) else { break };
581 let (s_field, s_wt) = (s_key >> 3, s_key & 7);
582 match s_wt {
583 0 => {
584 let v = match read_proto_varint(sub_data, &mut s_pos) {
585 Some(val) => val,
586 None => break,
587 };
588 match s_field {
589 2 => window.start_time_ms = v,
590 3 => window.duration_ms = v,
591 4 => window.sq_start = v,
592 5 => window.sq_end = v,
593 _ => {}
594 }
595 }
596 1 => { s_pos += 8; }
597 2 => {
598 let Some(s_len) = read_proto_varint(sub_data, &mut s_pos) else { break };
599 s_pos = s_pos.saturating_add(s_len as usize).min(sub_data.len());
600 }
601 5 => { s_pos += 4; }
602 _ => break,
603 }
604 }
605 }
606 }
607 5 => { pos += 4; }
608 _ => break,
609 }
610 }
611
612 if found {
613 Some(window)
614 } else {
615 None
616 }
617}
618
619pub fn extract_cpn_from_url(url: &str) -> Option<&str> {
622 let (_, query) = url.split_once('?')?;
623 let mut latest_cpn = None;
624 for kv in query.split('&') {
625 if let Some(val) = kv.strip_prefix("cpn=") {
626 if !val.is_empty() {
627 latest_cpn = Some(val);
628 }
629 }
630 }
631 latest_cpn
632}
633
634fn is_valid_cpn(b: &[u8]) -> bool {
636 b.len() == 16 && b.iter().all(|&c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
637}
638
639pub fn align_sabr_request_cpn(body: &[u8], target_cpn: &str) -> Option<Vec<u8>> {
644 let target_bytes = target_cpn.as_bytes();
645 if !is_valid_cpn(target_bytes) {
646 return None;
647 }
648
649 let mut pos = 0;
651 let mut needs_replace = false;
652 while pos < body.len() {
653 let key = read_proto_varint(body, &mut pos)?;
654 let (field, wt) = (key >> 3, key & 7);
655 match wt {
656 0 => { read_proto_varint(body, &mut pos)?; }
657 1 => { pos += 8; }
658 2 => {
659 let len = read_proto_varint(body, &mut pos)? as usize;
660 let end = pos.saturating_add(len).min(body.len());
661 let sub_data = &body[pos..end];
662 if field == 5 || field == 19 {
663 let mut s_pos = 0;
664 while s_pos < sub_data.len() {
665 let Some(s_key) = read_proto_varint(sub_data, &mut s_pos) else { break };
666 let (_s_field, s_wt) = (s_key >> 3, s_key & 7);
667 match s_wt {
668 0 => { if read_proto_varint(sub_data, &mut s_pos).is_none() { break; } }
669 1 => { s_pos += 8; }
670 2 => {
671 let Some(s_len) = read_proto_varint(sub_data, &mut s_pos) else { break };
672 let s_end = s_pos.saturating_add(s_len as usize).min(sub_data.len());
673 let val = &sub_data[s_pos..s_end];
674 s_pos = s_end;
675 if is_valid_cpn(val) && val != target_bytes {
676 needs_replace = true;
677 break;
678 }
679 }
680 5 => { s_pos += 4; }
681 _ => break,
682 }
683 }
684 }
685 pos = end;
686 }
687 5 => { pos += 4; }
688 _ => return None,
689 }
690 }
691
692 if !needs_replace {
693 return None;
694 }
695
696 let mut out = Vec::with_capacity(body.len());
698 pos = 0;
699 while pos < body.len() {
700 let key_start = pos;
701 let key = read_proto_varint(body, &mut pos)?;
702 let (field, wt) = (key >> 3, key & 7);
703 match wt {
704 0 => {
705 read_proto_varint(body, &mut pos)?;
706 out.extend_from_slice(&body[key_start..pos]);
707 }
708 1 => {
709 pos += 8;
710 out.extend_from_slice(&body[key_start..pos]);
711 }
712 2 => {
713 let len = read_proto_varint(body, &mut pos)? as usize;
714 let end = pos.saturating_add(len).min(body.len());
715 let sub_data = &body[pos..end];
716 if field == 5 || field == 19 {
717 let mut new_sub = Vec::with_capacity(len);
718 let mut s_pos = 0;
719 while s_pos < sub_data.len() {
720 let s_key_start = s_pos;
721 let Some(s_key) = read_proto_varint(sub_data, &mut s_pos) else { break };
722 let (_s_field, s_wt) = (s_key >> 3, s_key & 7);
723 match s_wt {
724 0 => {
725 if read_proto_varint(sub_data, &mut s_pos).is_none() { break; }
726 new_sub.extend_from_slice(&sub_data[s_key_start..s_pos]);
727 }
728 1 => {
729 s_pos += 8;
730 new_sub.extend_from_slice(&sub_data[s_key_start..s_pos]);
731 }
732 2 => {
733 let Some(s_len) = read_proto_varint(sub_data, &mut s_pos) else { break };
734 let s_end = s_pos.saturating_add(s_len as usize).min(sub_data.len());
735 let val = &sub_data[s_pos..s_end];
736 s_pos = s_end;
737 write_proto_varint(s_key, &mut new_sub);
738 if is_valid_cpn(val) && val != target_bytes {
739 write_proto_varint(target_bytes.len() as u64, &mut new_sub);
740 new_sub.extend_from_slice(target_bytes);
741 } else {
742 write_proto_varint(s_len, &mut new_sub);
743 new_sub.extend_from_slice(val);
744 }
745 }
746 5 => {
747 s_pos += 4;
748 new_sub.extend_from_slice(&sub_data[s_key_start..s_pos]);
749 }
750 _ => break,
751 }
752 }
753 write_proto_varint(key, &mut out);
754 write_proto_varint(new_sub.len() as u64, &mut out);
755 out.extend_from_slice(&new_sub);
756 } else {
757 out.extend_from_slice(&body[key_start..end]);
758 }
759 pos = end;
760 }
761 5 => {
762 pos += 4;
763 out.extend_from_slice(&body[key_start..pos]);
764 }
765 _ => break,
766 }
767 }
768
769 Some(out)
770}
771
772pub fn extract_video_id_from_url(url: &str) -> Option<&str> {
775 let query = url.split_once('?')?.1;
776 for param in query.split('&') {
777 let (k, v) = param.split_once('=')?;
778 if k == "id" || k == "docid" || k == "v" {
779 let val = v.split('#').next().unwrap_or(v);
780 if !val.is_empty() {
781 return Some(val);
782 }
783 }
784 }
785 None
786}
787
788pub fn extract_po_token_from_request(body: &[u8]) -> Option<Vec<u8>> {
791 let mut pos = 0;
792 while pos < body.len() {
793 let key = read_proto_varint(body, &mut pos)?;
794 let (field, wt) = (key >> 3, key & 7);
795 match wt {
796 0 => { read_proto_varint(body, &mut pos)?; }
797 1 => { pos += 8; }
798 2 => {
799 let len = read_proto_varint(body, &mut pos)? as usize;
800 let end = pos.saturating_add(len).min(body.len());
801 let sub_data = &body[pos..end];
802 pos = end;
803
804 if field == 19 {
805 let mut s_pos = 0;
806 while s_pos < sub_data.len() {
807 let Some(s_key) = read_proto_varint(sub_data, &mut s_pos) else { break };
808 let (s_field, s_wt) = (s_key >> 3, s_key & 7);
809 match s_wt {
810 0 => { if read_proto_varint(sub_data, &mut s_pos).is_none() { break; } }
811 1 => { s_pos += 8; }
812 2 => {
813 let Some(s_len) = read_proto_varint(sub_data, &mut s_pos) else { break };
814 let s_end = s_pos.saturating_add(s_len as usize).min(sub_data.len());
815 if s_field == 2 {
816 return Some(sub_data[s_pos..s_end].to_vec());
817 }
818 s_pos = s_end;
819 }
820 5 => { s_pos += 4; }
821 _ => break,
822 }
823 }
824 }
825 }
826 5 => { pos += 4; }
827 _ => break,
828 }
829 }
830 None
831}
832
833#[derive(Debug, Clone, PartialEq, Eq)]
836pub struct SabrPlaybackSession {
837 pub video_id: String,
838 pub cpn: String,
839 pub current_url: String,
840 pub po_token: Option<Vec<u8>>,
841 pub context_token: Option<Vec<u8>>,
842 pub backoff_ms: u32,
843 pub current_media_time_ms: u64,
844 pub buffered_media_time_ms: u64,
845 pub next_sq: u64,
846 pub segment_duration_ms: u64,
847 pub last_request_time_ms: u64,
848}
849
850impl SabrPlaybackSession {
851 pub fn new(video_id: &str, cpn: &str, initial_url: &str) -> Self {
853 Self {
854 video_id: String::from(video_id),
855 cpn: String::from(cpn),
856 current_url: String::from(initial_url),
857 po_token: None,
858 context_token: None,
859 backoff_ms: 0,
860 current_media_time_ms: 0,
861 buffered_media_time_ms: 0,
862 next_sq: 0,
863 segment_duration_ms: 5000,
864 last_request_time_ms: 0,
865 }
866 }
867
868 pub fn update_with_request(&mut self, url: &str, body: &[u8]) {
870 if !url.is_empty() {
871 self.current_url = String::from(url);
872 }
873 if let Some(cpn) = extract_cpn_from_url(url) {
874 self.cpn = String::from(cpn);
875 }
876 if let Some(vid) = extract_video_id_from_url(url) {
877 if self.video_id.is_empty() {
878 self.video_id = String::from(vid);
879 }
880 }
881 if let Some(token) = extract_po_token_from_request(body) {
882 self.po_token = Some(token);
883 }
884 if let Some(win) = parse_playback_window(body) {
885 self.current_media_time_ms = win.current_media_time_ms;
886 let end_time = win.start_time_ms.saturating_add(win.duration_ms);
887 if end_time > self.buffered_media_time_ms {
888 self.buffered_media_time_ms = end_time;
889 }
890 if win.sq_end >= self.next_sq {
891 self.next_sq = win.sq_end.saturating_add(1);
892 }
893 if win.duration_ms > 0 {
894 self.segment_duration_ms = win.duration_ms;
895 }
896 }
897 }
898
899 pub fn cached_po_token(&self) -> Option<&[u8]> {
901 self.po_token.as_deref()
902 }
903
904 pub fn update_playback_head(&mut self, current_ms: u64) {
906 self.current_media_time_ms = current_ms;
907 }
908
909 pub fn needs_refill(&self, buffer_threshold_ms: u64) -> bool {
911 let remaining = self.buffered_media_time_ms.saturating_sub(self.current_media_time_ms);
912 remaining < buffer_threshold_ms
913 }
914
915 pub fn process_response(&mut self, ump_data: &[u8]) -> Option<Vec<u8>> {
918 if let Some(policy) = extract_next_request_policy(ump_data) {
920 if let Some(url) = policy.target_url {
921 if !url.is_empty() {
922 self.current_url = url;
923 }
924 }
925 if !policy.context_token.is_empty() {
926 self.context_token = Some(policy.context_token);
927 }
928 self.backoff_ms = policy.backoff_ms as u32;
929 }
930
931 let media = extract_media_payloads(ump_data);
932 if !media.is_empty() {
933 self.buffered_media_time_ms = self.buffered_media_time_ms.saturating_add(self.segment_duration_ms);
934 self.next_sq += 1;
935 Some(media)
936 } else {
937 None
938 }
939 }
940
941 pub fn next_window(&self) -> PlaybackWindow {
943 PlaybackWindow {
944 current_media_time_ms: self.current_media_time_ms,
945 start_time_ms: self.buffered_media_time_ms,
946 duration_ms: self.segment_duration_ms,
947 sq_start: self.next_sq,
948 sq_end: self.next_sq,
949 }
950 }
951
952 pub fn encode_request_body(&self, po_token: Option<&[u8]>) -> Vec<u8> {
955 let mut out = Vec::new();
956
957 let mut client_info = Vec::new();
960 write_proto_varint(28 << 3, &mut client_info);
961 write_proto_varint(self.current_media_time_ms, &mut client_info);
962 write_proto_varint((1 << 3) | 2, &mut out);
963 write_proto_varint(client_info.len() as u64, &mut out);
964 out.extend_from_slice(&client_info);
965
966 let mut vp_req = Vec::new();
973 write_proto_varint(2 << 3, &mut vp_req);
974 write_proto_varint(self.buffered_media_time_ms, &mut vp_req);
975 write_proto_varint(3 << 3, &mut vp_req);
976 write_proto_varint(self.segment_duration_ms, &mut vp_req);
977 write_proto_varint(4 << 3, &mut vp_req);
978 write_proto_varint(self.next_sq, &mut vp_req);
979 write_proto_varint(5 << 3, &mut vp_req);
980 write_proto_varint(self.next_sq, &mut vp_req);
981 if let Some(ref token) = self.context_token {
982 write_proto_varint((8 << 3) | 2, &mut vp_req);
983 write_proto_varint(token.len() as u64, &mut vp_req);
984 vp_req.extend_from_slice(token);
985 }
986 write_proto_varint((3 << 3) | 2, &mut out);
987 write_proto_varint(vp_req.len() as u64, &mut out);
988 out.extend_from_slice(&vp_req);
989
990 let mut pb_ctx = Vec::new();
993 write_proto_varint((1 << 3) | 2, &mut pb_ctx);
994 write_proto_varint(self.cpn.len() as u64, &mut pb_ctx);
995 pb_ctx.extend_from_slice(self.cpn.as_bytes());
996 write_proto_varint((5 << 3) | 2, &mut out);
997 write_proto_varint(pb_ctx.len() as u64, &mut out);
998 out.extend_from_slice(&pb_ctx);
999
1000 let mut st_ctx = Vec::new();
1004 write_proto_varint((1 << 3) | 2, &mut st_ctx);
1005 write_proto_varint(self.cpn.len() as u64, &mut st_ctx);
1006 st_ctx.extend_from_slice(self.cpn.as_bytes());
1007 let effective_po = po_token.or(self.po_token.as_deref());
1008 if let Some(token) = effective_po {
1009 write_proto_varint((2 << 3) | 2, &mut st_ctx);
1010 write_proto_varint(token.len() as u64, &mut st_ctx);
1011 st_ctx.extend_from_slice(token);
1012 } else {
1013 write_proto_varint((2 << 3) | 2, &mut st_ctx);
1014 write_proto_varint(INITIAL_PO_TOKEN_BYTES.len() as u64, &mut st_ctx);
1015 st_ctx.extend_from_slice(&INITIAL_PO_TOKEN_BYTES);
1016 }
1017 write_proto_varint((19 << 3) | 2, &mut out);
1018 write_proto_varint(st_ctx.len() as u64, &mut out);
1019 out.extend_from_slice(&st_ctx);
1020
1021 out
1022 }
1023}
1024
1025use spin::Mutex;
1026
1027pub static GLOBAL_SABR_SESSION: Mutex<Option<SabrPlaybackSession>> = Mutex::new(None);
1029
1030pub fn record_sabr_request(url: &str, body: &[u8]) {
1033 let mut lock = GLOBAL_SABR_SESSION.lock();
1034 if let Some(ref mut session) = *lock {
1035 session.update_with_request(url, body);
1036 } else {
1037 let cpn = extract_cpn_from_url(url).unwrap_or("");
1038 let vid = extract_video_id_from_url(url).unwrap_or("");
1039 let mut session = SabrPlaybackSession::new(vid, cpn, url);
1040 session.update_with_request(url, body);
1041 *lock = Some(session);
1042 }
1043}
1044
1045pub fn record_sabr_response(raw_ump: &[u8]) {
1048 let mut lock = GLOBAL_SABR_SESSION.lock();
1049 if let Some(ref mut session) = *lock {
1050 let _ = session.process_response(raw_ump);
1051 }
1052}
1053
1054pub fn get_sabr_session_copy() -> Option<SabrPlaybackSession> {
1057 GLOBAL_SABR_SESSION.lock().clone()
1058}
1059
1060pub fn reset_sabr_session() {
1063 *GLOBAL_SABR_SESSION.lock() = None;
1064}
1065
1066pub fn parse_url_host_path(url: &str) -> Option<(bool, String, String)> {
1069 let (is_https, rest) = if let Some(r) = url.strip_prefix("https://") {
1070 (true, r)
1071 } else if let Some(r) = url.strip_prefix("http://") {
1072 (false, r)
1073 } else {
1074 return None;
1075 };
1076 let (host, path) = rest
1077 .split_once('/')
1078 .map(|(host, path)| (String::from(host), alloc::format!("/{path}")))
1079 .unwrap_or_else(|| (String::from(rest), String::from("/")));
1080 Some((is_https, host, path))
1081}
1082
1083pub type SabrTransportFn = fn(url: &str, body: &[u8]) -> Result<Vec<u8>, &'static str>;
1085
1086pub static SABR_TRANSPORT: Mutex<Option<SabrTransportFn>> = Mutex::new(None);
1087
1088pub fn set_sabr_transport(handler: Option<SabrTransportFn>) {
1091 *SABR_TRANSPORT.lock() = handler;
1092}
1093
1094pub fn fetch_sabr_http_post(url: &str, body: &[u8]) -> Result<Vec<u8>, &'static str> {
1096 let handler = *SABR_TRANSPORT.lock();
1097 if let Some(f) = handler {
1098 f(url, body)
1099 } else {
1100 Err("SABR HTTP transport not registered")
1101 }
1102}
1103
1104pub fn request_sabr_segment(url: &str, body: &[u8]) -> Result<Vec<u8>, &'static str> {
1107 let effective_url = normalize_sabr_url(url);
1108 let target_cpn = extract_cpn_from_url(&effective_url).unwrap_or("");
1109 let mid_body = if !target_cpn.is_empty() {
1110 if let Some(aligned) = align_sabr_request_cpn(body, target_cpn) {
1111 aligned
1112 } else {
1113 body.to_vec()
1114 }
1115 } else {
1116 body.to_vec()
1117 };
1118 let clean_body = if let Some(sanitized) = sanitize_sabr_request(&mid_body) {
1119 sanitized
1120 } else {
1121 mid_body
1122 };
1123
1124 record_sabr_request(&effective_url, &clean_body);
1125
1126 let raw = fetch_sabr_http_post(&effective_url, &clean_body)?;
1127 record_sabr_response(&raw);
1128 Ok(raw)
1129}
1130
1131pub fn trigger_sabr_auto_refill(ms_id: usize) -> bool {
1135 let (target_url, req_body) = {
1136 let mut lock = GLOBAL_SABR_SESSION.lock();
1137 let Some(ref mut session) = *lock else { return false };
1138 if !session.needs_refill(25_000) {
1139 return false;
1140 }
1141 let now = crate::kernel::timer::get_system_time_ms();
1142 if now.saturating_sub(session.last_request_time_ms) < session.backoff_ms as u64 {
1143 return false;
1144 }
1145 session.last_request_time_ms = now;
1146 (session.current_url.clone(), session.encode_request_body(None))
1147 };
1148
1149 crate::warn!("[SABR] Triggering autonomous buffer refill from server...");
1150 let raw_ump = match request_sabr_segment(&target_url, &req_body) {
1151 Ok(data) => data,
1152 Err(e) => {
1153 crate::warn!("[SABR] Autonomous refill request failed: {}", e);
1154 return false;
1155 }
1156 };
1157
1158 let media_chunks = extract_media_payloads(&raw_ump);
1159 if media_chunks.is_empty() {
1160 crate::warn!("[SABR] Refill response contained 0 media bytes");
1161 return false;
1162 }
1163
1164 crate::warn!(
1165 "[SABR] Autonomous refill received {} media bytes, appending to SourceBuffer id={}",
1166 media_chunks.len(),
1167 ms_id
1168 );
1169 let mut list = crate::os_lib::mse::SOURCE_BUFFERS.lock();
1170 let mut appended = false;
1171 for sb in list.iter_mut().filter(|b| b.owner == ms_id) {
1172 if sb.append_buffer(&media_chunks).is_ok() {
1173 appended = true;
1174 }
1175 }
1176 appended
1177}
1178
1179