1use serde::{Deserialize, Serialize};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
17#[non_exhaustive]
18pub struct MediaLimits {
19 #[serde(default, skip_serializing_if = "Option::is_none")]
21 pub max_images: Option<u32>,
22 #[serde(default, skip_serializing_if = "Option::is_none")]
25 pub image_tokens: Option<u32>,
26 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub image_patch: Option<u32>,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub image_edge: Option<u32>,
35 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub audio_max_seconds: Option<u32>,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub audio_tokens_per_minute: Option<u32>,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub max_request_bytes: Option<u64>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub video_max_seconds: Option<u32>,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
52 pub video_max_bytes: Option<u64>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub video_frames_per_minute: Option<u32>,
59}
60
61impl MediaLimits {
62 pub const UNKNOWN: Self = Self {
64 max_images: None,
65 image_tokens: None,
66 image_patch: None,
67 image_edge: None,
68 audio_max_seconds: None,
69 audio_tokens_per_minute: None,
70 max_request_bytes: None,
71 video_max_seconds: None,
72 video_max_bytes: None,
73 video_frames_per_minute: None,
74 };
75
76 pub fn new() -> Self {
77 Self::UNKNOWN
78 }
79
80 pub fn is_unknown(&self) -> bool {
82 *self == Self::UNKNOWN
83 }
84
85 pub fn with_max_images(mut self, n: u32) -> Self {
86 self.max_images = Some(n);
87 self
88 }
89
90 pub fn with_image_tokens(mut self, tokens: u32) -> Self {
92 self.image_tokens = Some(tokens);
93 self
94 }
95
96 pub fn with_image_patch(mut self, patch: u32) -> Self {
98 self.image_patch = Some(patch);
99 self
100 }
101
102 pub fn with_image_edge(mut self, pixels: u32) -> Self {
103 self.image_edge = Some(pixels);
104 self
105 }
106
107 pub fn with_audio_max_seconds(mut self, seconds: u32) -> Self {
108 self.audio_max_seconds = Some(seconds);
109 self
110 }
111
112 pub fn with_audio_tokens_per_minute(mut self, tokens: u32) -> Self {
113 self.audio_tokens_per_minute = Some(tokens);
114 self
115 }
116
117 pub fn with_max_request_bytes(mut self, bytes: u64) -> Self {
118 self.max_request_bytes = Some(bytes);
119 self
120 }
121
122 pub fn with_video_max_seconds(mut self, seconds: u32) -> Self {
123 self.video_max_seconds = Some(seconds);
124 self
125 }
126
127 pub fn with_video_max_bytes(mut self, bytes: u64) -> Self {
128 self.video_max_bytes = Some(bytes);
129 self
130 }
131
132 pub fn with_video_frames_per_minute(mut self, frames: u32) -> Self {
134 self.video_frames_per_minute = Some(frames);
135 self
136 }
137
138 pub fn video_frame_rate(&self) -> Option<f64> {
140 self.video_frames_per_minute.map(|f| f64::from(f) / 60.0)
141 }
142
143 pub fn video_frames(&self, millis: u64) -> Option<u64> {
145 self.video_frames_per_minute.map(|f| (u64::from(f) * millis).div_ceil(60_000))
146 }
147
148 pub fn check_video(&self, millis: u64, bytes: u64) -> Result<(), &'static str> {
152 if self.video_max_seconds.is_some_and(|s| millis > u64::from(s) * 1000) {
153 return Err("video_max_seconds");
154 }
155 if self.video_max_bytes.is_some_and(|b| bytes > b) {
156 return Err("video_max_bytes");
157 }
158 Ok(())
159 }
160
161 pub fn audio_tokens_per_second(&self) -> Option<f64> {
163 self.audio_tokens_per_minute.map(|t| f64::from(t) / 60.0)
164 }
165
166 pub fn image_cost(&self, width: u32, height: u32) -> Option<u32> {
170 let Some(patch) = self.image_patch.filter(|p| *p > 0) else {
171 return self.image_tokens;
172 };
173 let (w, h) = self.scaled(width, height);
174 let tokens = u64::from(w.div_ceil(patch)) * u64::from(h.div_ceil(patch));
175 let tokens = u32::try_from(tokens).unwrap_or(u32::MAX);
176 Some(self.image_tokens.map_or(tokens, |cap| tokens.min(cap)))
177 }
178
179 pub fn scaled(&self, width: u32, height: u32) -> (u32, u32) {
182 let long = width.max(height);
183 match self.image_edge {
184 Some(edge) if edge > 0 && long > edge => {
185 let s = |v: u32| ((u64::from(v) * u64::from(edge)).div_ceil(u64::from(long)) as u32).max(1);
186 (s(width), s(height))
187 }
188 _ => (width, height),
189 }
190 }
191
192 pub fn audio_cost(&self, millis: u64) -> Option<u64> {
194 self.audio_tokens_per_minute.map(|t| (u64::from(t) * millis).div_ceil(60_000))
195 }
196
197 pub fn or(self, fallback: Self) -> Self {
200 Self {
201 max_images: self.max_images.or(fallback.max_images),
202 image_tokens: self.image_tokens.or(fallback.image_tokens),
203 image_patch: self.image_patch.or(fallback.image_patch),
204 image_edge: self.image_edge.or(fallback.image_edge),
205 audio_max_seconds: self.audio_max_seconds.or(fallback.audio_max_seconds),
206 audio_tokens_per_minute: self.audio_tokens_per_minute.or(fallback.audio_tokens_per_minute),
207 max_request_bytes: self.max_request_bytes.or(fallback.max_request_bytes),
208 video_max_seconds: self.video_max_seconds.or(fallback.video_max_seconds),
209 video_max_bytes: self.video_max_bytes.or(fallback.video_max_bytes),
210 video_frames_per_minute: self.video_frames_per_minute.or(fallback.video_frames_per_minute),
211 }
212 }
213
214 pub fn tightest(self, other: Self) -> Self {
220 fn pick<T: Ord>(a: Option<T>, b: Option<T>, f: fn(T, T) -> T) -> Option<T> {
221 match (a, b) {
222 (Some(a), Some(b)) => Some(f(a, b)),
223 (a, b) => a.or(b),
224 }
225 }
226 Self {
227 max_images: pick(self.max_images, other.max_images, Ord::min),
228 image_tokens: pick(self.image_tokens, other.image_tokens, Ord::max),
229 image_patch: pick(self.image_patch, other.image_patch, Ord::min),
230 image_edge: pick(self.image_edge, other.image_edge, Ord::min),
231 audio_max_seconds: pick(self.audio_max_seconds, other.audio_max_seconds, Ord::min),
232 audio_tokens_per_minute: pick(self.audio_tokens_per_minute, other.audio_tokens_per_minute, Ord::max),
233 max_request_bytes: pick(self.max_request_bytes, other.max_request_bytes, Ord::min),
234 video_max_seconds: pick(self.video_max_seconds, other.video_max_seconds, Ord::min),
235 video_max_bytes: pick(self.video_max_bytes, other.video_max_bytes, Ord::min),
236 video_frames_per_minute: pick(self.video_frames_per_minute, other.video_frames_per_minute, Ord::min),
237 }
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 fn full() -> MediaLimits {
246 MediaLimits::new()
247 .with_max_images(8)
248 .with_image_tokens(1024)
249 .with_image_patch(28)
250 .with_image_edge(896)
251 .with_audio_max_seconds(30)
252 .with_audio_tokens_per_minute(375)
253 .with_max_request_bytes(32 << 20)
254 .with_video_max_seconds(60)
255 .with_video_max_bytes(16 << 20)
256 .with_video_frames_per_minute(120)
257 }
258
259 #[test]
260 fn unknown_limits_are_left_off_the_wire() {
261 assert!(MediaLimits::default().is_unknown());
262 assert_eq!(serde_json::to_string(&MediaLimits::UNKNOWN).unwrap(), "{}");
263 let partial = MediaLimits::new().with_max_images(4);
264 assert_eq!(serde_json::to_string(&partial).unwrap(), r#"{"max_images":4}"#);
265 let back: MediaLimits = serde_json::from_str("{}").unwrap();
266 assert!(back.is_unknown());
267 }
268
269 #[test]
270 fn round_trips_through_json_and_cbor() {
271 for l in [MediaLimits::UNKNOWN, MediaLimits::new().with_image_tokens(256), full()] {
272 let j: MediaLimits = serde_json::from_str(&serde_json::to_string(&l).unwrap()).unwrap();
273 assert_eq!(j, l);
274 let c: MediaLimits = cbor4ii::serde::from_slice(&cbor4ii::serde::to_vec(Vec::new(), &l).unwrap()).unwrap();
275 assert_eq!(c, l);
276 }
277 let v = serde_json::to_value(full()).unwrap();
278 for k in [
279 "max_images",
280 "image_tokens",
281 "image_patch",
282 "image_edge",
283 "audio_max_seconds",
284 "audio_tokens_per_minute",
285 "max_request_bytes",
286 "video_max_seconds",
287 "video_max_bytes",
288 "video_frames_per_minute",
289 ] {
290 assert!(v.get(k).is_some(), "{k}");
291 }
292 }
293
294 #[test]
295 fn image_and_audio_costs() {
296 let fixed = MediaLimits::new().with_image_tokens(256);
297 assert_eq!(fixed.image_cost(4000, 3000), Some(256));
298 assert_eq!(MediaLimits::UNKNOWN.image_cost(10, 10), None);
299 let patched = MediaLimits::new().with_image_patch(28).with_image_edge(896);
300 assert_eq!(patched.scaled(1792, 896), (896, 448));
301 assert_eq!(patched.scaled(500, 300), (500, 300));
302 assert_eq!(patched.image_cost(1792, 896), Some(32 * 16));
303 assert_eq!(patched.image_cost(29, 28), Some(2));
304 assert_eq!(patched.with_image_tokens(100).image_cost(1792, 896), Some(100), "capped");
305 assert_eq!(MediaLimits::new().with_image_patch(14).image_cost(28, 28), Some(4), "no edge: as sent");
306 let audio = MediaLimits::new().with_audio_tokens_per_minute(375);
307 assert_eq!(audio.audio_tokens_per_second(), Some(6.25));
308 assert_eq!(audio.audio_cost(60_000), Some(375));
309 assert_eq!(audio.audio_cost(1_000), Some(7), "rounded up");
310 assert_eq!(MediaLimits::UNKNOWN.audio_cost(1_000), None);
311 }
312
313 #[test]
314 fn video_limits() {
315 let none = MediaLimits::new().with_max_images(4);
316 assert_eq!(serde_json::to_value(none).unwrap(), serde_json::json!({"max_images": 4}), "unknown video fields stay off the wire");
317 assert_eq!((none.video_frame_rate(), none.video_frames(10_000)), (None, None));
318 assert_eq!(none.check_video(u64::MAX, u64::MAX), Ok(()), "nothing known, nothing checked");
319 let v = MediaLimits::new().with_video_max_seconds(30).with_video_max_bytes(8 << 20).with_video_frames_per_minute(30);
320 assert_eq!(
321 serde_json::to_value(v).unwrap(),
322 serde_json::json!({"video_max_seconds": 30, "video_max_bytes": 8388608, "video_frames_per_minute": 30})
323 );
324 assert_eq!(v.video_frame_rate(), Some(0.5));
325 assert_eq!(v.video_frames(10_000), Some(5));
326 assert_eq!(v.video_frames(10_001), Some(6), "rounded up");
327 assert_eq!(v.check_video(30_000, 8 << 20), Ok(()));
328 assert_eq!(v.check_video(30_001, 1), Err("video_max_seconds"));
329 assert_eq!(v.check_video(1_000, (8 << 20) + 1), Err("video_max_bytes"));
330 let old: MediaLimits = serde_json::from_str(r#"{"max_images":2,"audio_max_seconds":30}"#).unwrap();
332 assert_eq!(old, MediaLimits::new().with_max_images(2).with_audio_max_seconds(30));
333 let newer: MediaLimits = serde_json::from_str(r#"{"video_max_seconds":5,"video_codecs":["h264"]}"#).unwrap();
334 assert_eq!(newer, MediaLimits::new().with_video_max_seconds(5));
335 let a = MediaLimits::new().with_video_max_seconds(60).with_video_frames_per_minute(120);
337 let b = MediaLimits::new().with_video_max_seconds(20).with_video_max_bytes(4 << 20).with_video_frames_per_minute(60);
338 let t = a.tightest(b);
339 assert_eq!((t.video_max_seconds, t.video_max_bytes, t.video_frames_per_minute), (Some(20), Some(4 << 20), Some(60)));
340 assert_eq!(a.tightest(MediaLimits::UNKNOWN), a);
341 let o = MediaLimits::new().with_video_max_bytes(1 << 20).or(b);
342 assert_eq!(
343 (o.video_max_seconds, o.video_max_bytes, o.video_frames_per_minute),
344 (Some(20), Some(1 << 20), Some(60)),
345 "operator over measured"
346 );
347 assert!(!MediaLimits::new().with_video_frames_per_minute(1).is_unknown());
348 }
349
350 #[test]
351 fn merging() {
352 let a = MediaLimits::new().with_max_images(8).with_image_tokens(256).with_max_request_bytes(10);
353 let b = MediaLimits::new().with_max_images(2).with_image_tokens(576).with_image_edge(336);
354 let t = a.tightest(b);
355 assert_eq!((t.max_images, t.image_tokens, t.image_edge, t.max_request_bytes), (Some(2), Some(576), Some(336), Some(10)));
356 assert_eq!(t.audio_max_seconds, None);
357 assert_eq!(a.tightest(MediaLimits::UNKNOWN), a);
358 let operator = MediaLimits::new().with_max_images(1);
359 let o = operator.or(a);
360 assert_eq!((o.max_images, o.image_tokens), (Some(1), Some(256)));
361 }
362}