Skip to main content

kaeso_kpp/
video.rs

1use serde::{Deserialize, Serialize};
2
3use crate::block::Source;
4use crate::error::KppError;
5use crate::extras::Extras;
6use crate::image::ImageSize;
7use crate::response::Usage;
8
9/// What a video request asks for.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum VideoOperation {
14    /// A new video from a prompt and the images that guide it.
15    #[default]
16    Generate,
17    /// A new video made by changing an earlier one with a new prompt.
18    Remix,
19}
20
21impl VideoOperation {
22    /// The operation's name in logs and messages: `generate` or `remix`.
23    pub const fn as_str(self) -> &'static str {
24        match self {
25            VideoOperation::Generate => "generate",
26            VideoOperation::Remix => "remix",
27        }
28    }
29}
30
31/// What an image given to a video request is for.
32#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34#[non_exhaustive]
35pub enum VideoImageRole {
36    /// The video starts with this image.
37    #[default]
38    FirstFrame,
39    /// The video ends with this image.
40    LastFrame,
41    /// The image guides what the video shows, without being one of its frames.
42    Reference,
43}
44
45impl VideoImageRole {
46    /// The role's name in messages: `first_frame`, `last_frame` or `reference`.
47    pub const fn as_str(self) -> &'static str {
48        match self {
49            VideoImageRole::FirstFrame => "first_frame",
50            VideoImageRole::LastFrame => "last_frame",
51            VideoImageRole::Reference => "reference",
52        }
53    }
54}
55
56/// An image a video request sends, and what it is for.
57#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
58#[non_exhaustive]
59pub struct VideoImage {
60    pub source: Source,
61    #[serde(default)]
62    pub role: VideoImageRole,
63    /// The file name an upload carried.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub filename: Option<String>,
66    #[serde(default, skip_serializing_if = "Extras::is_empty")]
67    pub extras: Extras,
68}
69
70impl VideoImage {
71    pub fn new(source: Source, role: VideoImageRole) -> Self {
72        VideoImage {
73            source,
74            role,
75            filename: None,
76            extras: Extras::default(),
77        }
78    }
79
80    #[must_use]
81    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
82        self.filename = Some(filename.into());
83        self
84    }
85}
86
87/// A request that starts a video job: a generation or a remix.
88#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
89#[non_exhaustive]
90pub struct VideoRequest {
91    pub model: String,
92    #[serde(default)]
93    pub operation: VideoOperation,
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub prompt: Option<String>,
96    /// The images that guide the video, in order.
97    #[serde(default, skip_serializing_if = "Vec::is_empty")]
98    pub images: Vec<VideoImage>,
99    /// The provider's id of the earlier video a remix changes.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub remix_of: Option<String>,
102    /// The earlier video itself, for providers that take the video to change by link.
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub source_video: Option<Source>,
105    /// How long the video lasts, in whole seconds.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub seconds: Option<u32>,
108    /// The output size in pixels, `WIDTHxHEIGHT`.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub size: Option<ImageSize>,
111    /// The output aspect ratio, such as `16:9`, for providers that take one instead of a size.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub aspect_ratio: Option<String>,
114    /// The output resolution tier, such as `720p`, as the provider spells it.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub resolution: Option<String>,
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub seed: Option<i64>,
119    /// What the video should not show.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub negative_prompt: Option<String>,
122    /// Whether the video has sound.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    pub audio: Option<bool>,
125    /// How many videos to make.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub count: Option<u32>,
128    /// A stable identifier of the app's end user.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub user: Option<String>,
131    #[serde(default, skip_serializing_if = "Extras::is_empty")]
132    pub extras: Extras,
133}
134
135impl VideoRequest {
136    pub fn new(model: impl Into<String>, operation: VideoOperation) -> Self {
137        VideoRequest {
138            model: model.into(),
139            operation,
140            ..VideoRequest::default()
141        }
142    }
143
144    #[must_use]
145    pub fn with_prompt(mut self, prompt: impl Into<String>) -> Self {
146        self.prompt = Some(prompt.into());
147        self
148    }
149
150    #[must_use]
151    pub fn with_image(mut self, image: VideoImage) -> Self {
152        self.images.push(image);
153        self
154    }
155
156    /// The images given for `role`.
157    pub fn images_for(&self, role: VideoImageRole) -> impl Iterator<Item = &VideoImage> {
158        self.images.iter().filter(move |i| i.role == role)
159    }
160
161    /// Checks what every video request needs, whatever its format: a model, a prompt or an
162    /// image to start from, at most one first and one last frame, and counts in range.
163    pub fn validate(&self) -> Result<(), KppError> {
164        let invalid = |message: &str, param: &str| {
165            Err(KppError::invalid_request(message.to_owned()).with_param(param.to_owned()))
166        };
167        if self.model.is_empty() {
168            return invalid("`model` must not be empty.", "model");
169        }
170        let prompt = self.prompt.as_deref().is_some_and(|p| !p.is_empty());
171        match self.operation {
172            VideoOperation::Generate if !prompt && self.images.is_empty() => {
173                return invalid("`prompt` must not be empty.", "prompt");
174            }
175            VideoOperation::Remix if !prompt => {
176                return invalid("`prompt` must not be empty.", "prompt");
177            }
178            VideoOperation::Remix if self.remix_of.is_none() && self.source_video.is_none() => {
179                return invalid("A remix names the video it changes.", "video_id");
180            }
181            _ => {}
182        }
183        for role in [VideoImageRole::FirstFrame, VideoImageRole::LastFrame] {
184            if self.images_for(role).count() > 1 {
185                return invalid(
186                    &format!("Send at most one image as the {} frame.", frame_word(role)),
187                    "input_reference",
188                );
189            }
190        }
191        if self.images_for(VideoImageRole::LastFrame).next().is_some()
192            && self.images_for(VideoImageRole::FirstFrame).next().is_none()
193        {
194            return invalid(
195                "A last frame needs a first frame to start from.",
196                "input_reference",
197            );
198        }
199        if self.seconds == Some(0) {
200            return invalid("`seconds` must be at least 1.", "seconds");
201        }
202        if self.count == Some(0) {
203            return invalid("`n` must be at least 1.", "n");
204        }
205        Ok(())
206    }
207
208    /// What a model must be able to do to serve the request.
209    pub fn required_capabilities(&self) -> crate::Capabilities {
210        crate::Capabilities {
211            images: !self.images.is_empty(),
212            video_input: self.source_video.is_some(),
213            video_output: true,
214            ..crate::Capabilities::default()
215        }
216    }
217}
218
219fn frame_word(role: VideoImageRole) -> &'static str {
220    match role {
221        VideoImageRole::LastFrame => "last",
222        _ => "first",
223    }
224}
225
226/// How far a video job has come.
227#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
228#[serde(rename_all = "snake_case")]
229#[non_exhaustive]
230pub enum VideoStatus {
231    /// Waiting for the provider to start.
232    #[default]
233    Queued,
234    /// Being made.
235    InProgress,
236    /// Made; its outputs can be fetched.
237    Completed,
238    /// Ended without a video.
239    Failed,
240}
241
242impl VideoStatus {
243    /// The status as OpenAI's Videos API writes it: `queued`, `in_progress`, `completed` or
244    /// `failed`.
245    pub const fn as_str(self) -> &'static str {
246        match self {
247            VideoStatus::Queued => "queued",
248            VideoStatus::InProgress => "in_progress",
249            VideoStatus::Completed => "completed",
250            VideoStatus::Failed => "failed",
251        }
252    }
253
254    /// The status of `as_str`'s spelling.
255    pub fn from_wire(s: &str) -> Option<VideoStatus> {
256        Some(match s {
257            "queued" => VideoStatus::Queued,
258            "in_progress" => VideoStatus::InProgress,
259            "completed" => VideoStatus::Completed,
260            "failed" => VideoStatus::Failed,
261            _ => return None,
262        })
263    }
264
265    /// Whether the job has ended, made or not.
266    pub const fn is_done(self) -> bool {
267        matches!(self, VideoStatus::Completed | VideoStatus::Failed)
268    }
269}
270
271/// Which file of a made video an output is.
272#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
273#[serde(rename_all = "snake_case")]
274#[non_exhaustive]
275pub enum VideoVariant {
276    /// The video itself.
277    #[default]
278    Video,
279    /// A still image of the video.
280    Thumbnail,
281    /// A grid of stills across the video.
282    Spritesheet,
283}
284
285impl VideoVariant {
286    /// The variant as OpenAI's `variant` query parameter spells it.
287    pub const fn as_str(self) -> &'static str {
288        match self {
289            VideoVariant::Video => "video",
290            VideoVariant::Thumbnail => "thumbnail",
291            VideoVariant::Spritesheet => "spritesheet",
292        }
293    }
294
295    /// The variant of `as_str`'s spelling.
296    pub fn from_wire(s: &str) -> Option<VideoVariant> {
297        Some(match s {
298            "video" => VideoVariant::Video,
299            "thumbnail" => VideoVariant::Thumbnail,
300            "spritesheet" => VideoVariant::Spritesheet,
301            _ => return None,
302        })
303    }
304}
305
306/// A file a finished video job made: where to fetch it, and its media type when known.
307#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
308#[non_exhaustive]
309pub struct VideoOutput {
310    #[serde(default)]
311    pub variant: VideoVariant,
312    /// A link, the bytes themselves, or a file id the provider resolves to a link.
313    pub source: Source,
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub media_type: Option<String>,
316}
317
318impl VideoOutput {
319    pub fn new(variant: VideoVariant, source: Source) -> Self {
320        VideoOutput {
321            variant,
322            source,
323            media_type: None,
324        }
325    }
326
327    #[must_use]
328    pub fn with_media_type(mut self, media_type: impl Into<String>) -> Self {
329        self.media_type = Some(media_type.into());
330        self
331    }
332}
333
334/// Why a video job failed, as the provider says it.
335#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
336#[non_exhaustive]
337pub struct VideoError {
338    /// The provider's code for the failure.
339    pub code: String,
340    pub message: String,
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub param: Option<String>,
343    /// The provider's error type, when it names one apart from the code.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub kind: Option<String>,
346}
347
348impl VideoError {
349    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
350        VideoError {
351            code: code.into(),
352            message: message.into(),
353            param: None,
354            kind: None,
355        }
356    }
357}
358
359/// A video job as the provider reports it: when it is started, and each time it is asked.
360#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
361#[non_exhaustive]
362pub struct VideoJob {
363    /// The job's id at the provider, which the provider is asked about later.
364    pub id: String,
365    #[serde(default)]
366    pub model: String,
367    #[serde(default)]
368    pub status: VideoStatus,
369    /// How far the job has come, 0 to 100, when the provider says.
370    #[serde(default, skip_serializing_if = "Option::is_none")]
371    pub progress: Option<u32>,
372    /// When the job was created, in Unix seconds.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub created_at: Option<i64>,
375    /// When the job ended, in Unix seconds.
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub completed_at: Option<i64>,
378    /// When the outputs stop being available, in Unix seconds.
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub expires_at: Option<i64>,
381    #[serde(default, skip_serializing_if = "Option::is_none")]
382    pub prompt: Option<String>,
383    /// How long the video lasts, in whole seconds.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub seconds: Option<u32>,
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub size: Option<ImageSize>,
388    #[serde(default, skip_serializing_if = "Option::is_none")]
389    pub resolution: Option<String>,
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub aspect_ratio: Option<String>,
392    /// Whether the video has sound, when the provider says.
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub audio: Option<bool>,
395    /// The id of the video this one remixes.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub remixed_from: Option<String>,
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub error: Option<VideoError>,
400    /// The files a finished job made.
401    #[serde(default, skip_serializing_if = "Vec::is_empty")]
402    pub outputs: Vec<VideoOutput>,
403    /// The tokens the provider counted, for providers that bill video by the token.
404    #[serde(default, skip_serializing_if = "Option::is_none")]
405    pub usage: Option<Usage>,
406    #[serde(default, skip_serializing_if = "Extras::is_empty")]
407    pub extras: Extras,
408}
409
410impl VideoJob {
411    pub fn new(id: impl Into<String>, status: VideoStatus) -> Self {
412        VideoJob {
413            id: id.into(),
414            status,
415            ..VideoJob::default()
416        }
417    }
418
419    /// The first output of `variant`.
420    pub fn output(&self, variant: VideoVariant) -> Option<&VideoOutput> {
421        self.outputs.iter().find(|o| o.variant == variant)
422    }
423}
424
425/// The order of a video listing.
426#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
427#[serde(rename_all = "snake_case")]
428#[non_exhaustive]
429pub enum ListOrder {
430    Asc,
431    /// Newest first, OpenAI's default.
432    #[default]
433    Desc,
434}
435
436/// What a video listing asks for: a page after an id, its length and its order.
437#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
438#[non_exhaustive]
439pub struct VideoListQuery {
440    /// The id of the last video of the previous page.
441    #[serde(default, skip_serializing_if = "Option::is_none")]
442    pub after: Option<String>,
443    /// How many videos to list, 0 to 100.
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub limit: Option<u32>,
446    #[serde(default)]
447    pub order: ListOrder,
448}
449
450impl VideoListQuery {
451    /// The page length OpenAI's Videos API lists when the query names none.
452    pub const DEFAULT_LIMIT: u32 = 20;
453    /// The longest page OpenAI's Videos API lists.
454    pub const MAX_LIMIT: u32 = 100;
455
456    /// The page length to list: the query's, or the default.
457    pub fn limit(&self) -> u32 {
458        self.limit
459            .unwrap_or(Self::DEFAULT_LIMIT)
460            .min(Self::MAX_LIMIT)
461    }
462}
463
464/// A page of a video listing.
465#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
466#[non_exhaustive]
467pub struct VideoList {
468    pub videos: Vec<VideoJob>,
469    #[serde(default)]
470    pub has_more: bool,
471}
472
473impl VideoList {
474    pub fn new(videos: Vec<VideoJob>, has_more: bool) -> Self {
475        VideoList { videos, has_more }
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    fn image(role: VideoImageRole) -> VideoImage {
484        VideoImage::new(Source::Url("https://example.com/a.png".into()), role)
485    }
486
487    #[test]
488    fn requests_need_a_model_a_prompt_or_an_image_and_one_frame_each() {
489        let ok = VideoRequest::new("m", VideoOperation::Generate).with_prompt("fox");
490        assert!(ok.validate().is_ok());
491        let param = |r: &VideoRequest| r.validate().unwrap_err().param;
492        assert_eq!(
493            param(&VideoRequest::new("", VideoOperation::Generate)).as_deref(),
494            Some("model")
495        );
496        assert_eq!(
497            param(&VideoRequest::new("m", VideoOperation::Generate)).as_deref(),
498            Some("prompt")
499        );
500        let from_image = VideoRequest::new("m", VideoOperation::Generate)
501            .with_image(image(VideoImageRole::FirstFrame));
502        assert!(from_image.validate().is_ok());
503        let two_first = from_image
504            .clone()
505            .with_image(image(VideoImageRole::FirstFrame));
506        assert_eq!(param(&two_first).as_deref(), Some("input_reference"));
507        let last_only = VideoRequest::new("m", VideoOperation::Generate)
508            .with_prompt("fox")
509            .with_image(image(VideoImageRole::LastFrame));
510        assert_eq!(param(&last_only).as_deref(), Some("input_reference"));
511        let mut seconds = ok.clone();
512        seconds.seconds = Some(0);
513        assert_eq!(param(&seconds).as_deref(), Some("seconds"));
514        let mut count = ok.clone();
515        count.count = Some(0);
516        assert_eq!(param(&count).as_deref(), Some("n"));
517    }
518
519    #[test]
520    fn a_remix_needs_a_prompt_and_its_video() {
521        let mut r = VideoRequest::new("m", VideoOperation::Remix).with_prompt("in snow");
522        assert_eq!(r.validate().unwrap_err().param.as_deref(), Some("video_id"));
523        r.remix_of = Some("job".into());
524        assert!(r.validate().is_ok());
525        r.prompt = None;
526        assert_eq!(r.validate().unwrap_err().param.as_deref(), Some("prompt"));
527        let caps = VideoRequest::new("m", VideoOperation::Generate)
528            .with_image(image(VideoImageRole::Reference))
529            .required_capabilities();
530        assert!(caps.video_output && caps.images && !caps.video_input);
531    }
532
533    #[test]
534    fn wire_names_round_trip() {
535        for s in [
536            VideoStatus::Queued,
537            VideoStatus::InProgress,
538            VideoStatus::Completed,
539            VideoStatus::Failed,
540        ] {
541            assert_eq!(VideoStatus::from_wire(s.as_str()), Some(s));
542        }
543        assert!(VideoStatus::Failed.is_done() && !VideoStatus::Queued.is_done());
544        for v in [
545            VideoVariant::Video,
546            VideoVariant::Thumbnail,
547            VideoVariant::Spritesheet,
548        ] {
549            assert_eq!(VideoVariant::from_wire(v.as_str()), Some(v));
550        }
551        assert_eq!(VideoVariant::from_wire("gif"), None);
552        assert_eq!(VideoStatus::from_wire("done"), None);
553        assert_eq!(VideoOperation::Remix.as_str(), "remix");
554        assert_eq!(VideoImageRole::Reference.as_str(), "reference");
555        let q = VideoListQuery {
556            limit: Some(500),
557            ..VideoListQuery::default()
558        };
559        assert_eq!(q.limit(), 100);
560        assert_eq!(VideoListQuery::default().limit(), 20);
561        let job = VideoJob::new("j", VideoStatus::Completed);
562        assert!(job.output(VideoVariant::Video).is_none());
563        let out = VideoOutput::new(VideoVariant::Video, Source::Url("u".into()))
564            .with_media_type("video/mp4");
565        assert_eq!(out.media_type.as_deref(), Some("video/mp4"));
566        assert_eq!(VideoList::new(vec![job], true).videos.len(), 1);
567    }
568}