redseat-api 0.19.1

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! Video conversions: the server makes a new video from a media's, trimmed, framed,
//! resized, re-encoded, with a watermark or timed texts over it, and adds it to the
//! library. The web app's `DialogEditVideo.svelte` (the editor), `MediasList.svelte`
//! (the grid's Convert menu) and `LibraryConvertStore.ts` (the conversions under
//! way).
//!
//! - [`ConvertForm`]: the editor's fields as the user types them, what is wrong with
//!   them ([`ConvertForm::errors`], the web app's wording), the request they make
//!   ([`ConvertForm::request`]) and the frame the output keeps
//!   ([`ConvertForm::frame`]), for a preview.
//! - [`Quality`] and [`crf_request`]: the grid's one-click conversions.
//! - [`ConvertPreset`]: settings saved under a name, in the web app's JSON.
//! - [`Conversions`] (feature `mirror`): the server's conversions as its events tell
//!   them, started from here or elsewhere, with their progress.

use base64::Engine as _;
use serde::{Deserialize, Serialize};

use crate::types::media::Media;
use rs_plugin_common_interfaces::video::{
    RsVideoCodec, RsVideoFormat, VideoAlignment, VideoConvertInterval, VideoConvertRequest,
    VideoOverlay, VideoOverlayPosition, VideoOverlayType, VideoTextOverlay,
};

#[cfg(feature = "mirror")]
mod conversions;
#[cfg(test)]
mod tests;

#[cfg(feature = "mirror")]
pub use conversions::{Conversion, ConversionStatus, Conversions};

/// The largest width, height or crop side the editor accepts, in pixels.
pub const MAX_SIDE: u32 = 16384;
/// The highest frame rate the editor accepts.
pub const MAX_FRAMERATE: u32 = 240;
/// The highest CRF (lower is better quality).
pub const MAX_CRF: u32 = 63;
/// The largest text overlay font size, in output pixels.
pub const MAX_FONT_SIZE: u32 = 512;
/// The aspect ratios the editor offers, besides the original.
pub const RATIOS: [&str; 4] = ["1/1", "16/9", "9/16", "4/5"];
/// The formats the editor offers.
pub const FORMATS: [RsVideoFormat; 3] =
    [RsVideoFormat::Mp4, RsVideoFormat::WebM, RsVideoFormat::Mkv];
/// The codecs the editor offers; `None` copies the source's.
pub const CODECS: [Option<RsVideoCodec>; 4] = [
    None,
    Some(RsVideoCodec::H264),
    Some(RsVideoCodec::H265),
    Some(RsVideoCodec::AV1),
];
/// Where a watermark can go.
pub const WATERMARK_POSITIONS: [VideoOverlayPosition; 4] = [
    VideoOverlayPosition::TopLeft,
    VideoOverlayPosition::TopRight,
    VideoOverlayPosition::BottomLeft,
    VideoOverlayPosition::BottomRight,
];
/// Where a text can go.
pub const TEXT_POSITIONS: [VideoOverlayPosition; 7] = [
    VideoOverlayPosition::TopLeft,
    VideoOverlayPosition::TopCenter,
    VideoOverlayPosition::TopRight,
    VideoOverlayPosition::Center,
    VideoOverlayPosition::BottomLeft,
    VideoOverlayPosition::BottomCenter,
    VideoOverlayPosition::BottomRight,
];
/// The alignments of an aspect ratio's crop.
pub const ALIGNMENTS: [VideoAlignment; 3] = [
    VideoAlignment::Left,
    VideoAlignment::Center,
    VideoAlignment::Right,
];

/// A new conversion id, as the web app's `nanoid()`: 22 URL-safe characters.
pub fn new_id() -> String {
    let bytes = redseat_crypto::random_iv().unwrap_or_else(|_| {
        // No random source: the clock still tells two conversions apart.
        let mut bytes = [0u8; 16];
        bytes[..8].copy_from_slice(&crate::client::now_ms().to_le_bytes());
        bytes
    });
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
}

/// A format's name: "MP4", "WebM", "MKV".
pub fn format_label(format: &RsVideoFormat) -> String {
    match format {
        RsVideoFormat::WebM => "WebM".to_owned(),
        other => other.to_string().to_uppercase(),
    }
}

/// A codec's name: "Copy source", "H.264", "HEVC", "AV1".
pub fn codec_label(codec: Option<&RsVideoCodec>) -> String {
    match codec {
        None => "Copy source".to_owned(),
        Some(RsVideoCodec::H264) => "H.264".to_owned(),
        Some(RsVideoCodec::H265) => "HEVC".to_owned(),
        Some(RsVideoCodec::AV1) => "AV1".to_owned(),
        Some(other) => other.to_string(),
    }
}

/// A position's name: "Top left", "Center"...
pub fn position_label(position: &VideoOverlayPosition) -> &'static str {
    match position {
        VideoOverlayPosition::TopLeft => "Top left",
        VideoOverlayPosition::TopRight => "Top right",
        VideoOverlayPosition::TopCenter => "Top center",
        VideoOverlayPosition::BottomLeft => "Bottom left",
        VideoOverlayPosition::BottomRight => "Bottom right",
        VideoOverlayPosition::BottomCenter => "Bottom center",
        VideoOverlayPosition::Center => "Center",
    }
}

/// An alignment's name: "Left", "Center", "Right".
pub fn alignment_label(alignment: &VideoAlignment) -> &'static str {
    match alignment {
        VideoAlignment::Left => "Left",
        VideoAlignment::Center => "Center",
        VideoAlignment::Right => "Right",
    }
}

/// A time as the editor shows it: `m:ss` or `h:mm:ss`, with tenths when there are.
pub fn format_time(seconds: f64) -> String {
    let seconds = seconds.max(0.0);
    let tenths = (seconds * 10.0).round() as u64;
    let whole = super::text::duration(tenths / 10);
    match tenths % 10 {
        0 => whole,
        tenth => format!("{whole}.{tenth}"),
    }
}

/// A time as typed: seconds (`90`, `12.5`), `m:ss` or `h:mm:ss`, with decimals on the
/// seconds. `None` when it is not one.
pub fn parse_time(text: &str) -> Option<f64> {
    let text = text.trim();
    if text.is_empty() {
        return None;
    }
    let parts: Vec<&str> = text.split(':').collect();
    if parts.len() > 3 {
        return None;
    }
    let (last, units) = parts.split_last()?;
    let seconds: f64 = last.trim().parse().ok()?;
    if !seconds.is_finite() || seconds < 0.0 || (!units.is_empty() && seconds >= 60.0) {
        return None;
    }
    let mut total = 0.0;
    for (index, unit) in units.iter().enumerate() {
        let value: u32 = unit.trim().parse().ok()?;
        // The minutes of h:mm:ss stay under an hour.
        if index > 0 && value >= 60 {
            return None;
        }
        total = total * 60.0 + f64::from(value);
    }
    Some(total * 60.0 + seconds)
}

/// An aspect ratio as typed, `16/9` or `16:9`: its width over its height, each a whole
/// number from 1 to 65535.
pub fn parse_ratio(text: &str) -> Option<f64> {
    let (width, height) = text.trim().split_once(['/', ':'])?;
    let width: u32 = width.trim().parse().ok()?;
    let height: u32 = height.trim().parse().ok()?;
    let range = 1..=65535;
    (range.contains(&width) && range.contains(&height))
        .then(|| f64::from(width) / f64::from(height))
}

/// A whole number field: `Ok(None)` when empty, `Err(())` when not a whole number in
/// `range`.
fn whole(text: &str, range: std::ops::RangeInclusive<u32>) -> Result<Option<u32>, ()> {
    let text = text.trim();
    if text.is_empty() {
        return Ok(None);
    }
    match text.parse::<u32>() {
        Ok(value) if range.contains(&value) => Ok(Some(value)),
        _ => Err(()),
    }
}

/// A color as typed (`FFFFFF`, `#ff8800`): its six hex digits, upper case.
pub fn parse_color(text: &str) -> Option<String> {
    let hex = text.trim().trim_start_matches('#');
    (hex.len() == 6 && hex.chars().all(|c| c.is_ascii_hexdigit())).then(|| hex.to_uppercase())
}

/// A media's duration in seconds, when known.
pub fn media_duration(media: &Media) -> Option<f64> {
    media.duration.filter(|d| *d > 0).map(|d| d as f64)
}

// --- One-click conversions

/// The grid's one-click conversions: HEVC in MP4 at a CRF for the video's size.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Quality {
    High,
    Medium,
    Low,
    /// Small files, for phones.
    VeryLow,
}

impl Quality {
    pub const ALL: [Quality; 4] = [
        Quality::High,
        Quality::Medium,
        Quality::Low,
        Quality::VeryLow,
    ];

    pub fn label(self) -> &'static str {
        match self {
            Quality::High => "High Quality",
            Quality::Medium => "Medium Quality",
            Quality::Low => "Low Quality",
            Quality::VeryLow => "Very Low (Mobile)",
        }
    }

    /// The CRF for a video of `media`'s size (the web app's table): larger videos
    /// take a higher one.
    pub fn crf(self, media: &Media) -> u16 {
        let side = media.width.unwrap_or(0).max(media.height.unwrap_or(0));
        // 4K, 2K, Full HD and smaller.
        let size = match side {
            s if s >= 3840 => 0,
            s if s >= 2560 => 1,
            _ => 2,
        };
        let table: [u16; 3] = match self {
            Quality::High => [26, 25, 24],
            Quality::Medium => [30, 27, 26],
            Quality::Low => [34, 29, 28],
            Quality::VeryLow => [36, 34, 32],
        };
        table[size]
    }

    /// The request converting `media`: medium and low ones above 30 fps go down to 30.
    pub fn request(self, media: &Media) -> VideoConvertRequest {
        let fast = media.fps.is_some_and(|fps| fps > 30.0);
        let framerate = (matches!(self, Quality::Medium | Quality::Low) && fast).then_some(30);
        VideoConvertRequest {
            framerate,
            ..crf_request(self.crf(media))
        }
    }
}

/// A one-click conversion at the CRF the user gave: HEVC in MP4.
pub fn crf_request(crf: u16) -> VideoConvertRequest {
    VideoConvertRequest {
        id: new_id(),
        format: RsVideoFormat::Mp4,
        codec: Some(RsVideoCodec::H265),
        crf: Some(crf),
        ..Default::default()
    }
}

/// The settings of a conversion saved under a name, as the web app keeps them
/// (`convert_presets_<library>`): the app stores them, per library.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConvertPreset {
    pub name: String,
    pub preset: VideoConvertRequest,
    /// The video convert plugin that runs it, `None` for the server's converter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin: Option<String>,
}

impl ConvertPreset {
    /// The request for one more conversion with these settings: a new id.
    pub fn request(&self) -> VideoConvertRequest {
        VideoConvertRequest {
            id: new_id(),
            ..self.preset.clone()
        }
    }
}

// --- The editor

/// A watermark over the video: one of the library's images.
#[derive(Debug, Clone, PartialEq)]
pub struct WatermarkForm {
    /// Its name ([`crate::LibraryApi::watermarks`]).
    pub name: String,
    pub position: VideoOverlayPosition,
    /// Its width, in percent of the video's.
    pub size: u8,
    /// In percent.
    pub opacity: u8,
}

impl WatermarkForm {
    pub fn new(name: &str) -> Self {
        WatermarkForm {
            name: name.to_owned(),
            position: VideoOverlayPosition::TopRight,
            size: 30,
            opacity: 40,
        }
    }
}

/// A text shown over the video for a while, its fields as typed.
#[derive(Debug, Clone, PartialEq)]
pub struct TextForm {
    pub text: String,
    pub position: VideoOverlayPosition,
    /// In output pixels.
    pub font_size: String,
    /// In percent.
    pub opacity: String,
    /// From the edges, in output pixels.
    pub margin: String,
    /// Six hex digits.
    pub color: String,
    pub shadow: String,
    /// Times in the source ([`parse_time`]).
    pub start: String,
    pub end: String,
}

impl TextForm {
    /// A new text, from `start` to `end` seconds.
    pub fn new(start: f64, end: f64) -> Self {
        TextForm {
            text: "Overlay".to_owned(),
            position: VideoOverlayPosition::BottomLeft,
            font_size: "36".to_owned(),
            opacity: "80".to_owned(),
            margin: "0".to_owned(),
            color: "FFFFFF".to_owned(),
            shadow: "000000".to_owned(),
            start: format_time(start),
            end: format_time(end),
        }
    }

    /// Its font size, when valid.
    pub fn font_size(&self) -> Option<u32> {
        whole(&self.font_size, 1..=MAX_FONT_SIZE).ok().flatten()
    }

    /// Its opacity from 0 to 1, when valid.
    pub fn opacity(&self) -> Option<f32> {
        whole(&self.opacity, 0..=100)
            .ok()
            .flatten()
            .map(|o| o as f32 / 100.0)
    }

    /// Its margin, when valid.
    pub fn margin(&self) -> Option<u32> {
        whole(&self.margin, 0..=MAX_SIDE).ok().flatten()
    }

    /// Whether it shows at `seconds` of the source.
    pub fn shows_at(&self, seconds: f64) -> bool {
        match (parse_time(&self.start), parse_time(&self.end)) {
            (Some(start), Some(end)) => (start..end).contains(&seconds),
            _ => true,
        }
    }

    /// What is wrong with it, the first thing only. `number` counts from 1.
    fn error(&self, number: usize, duration: Option<f64>) -> Option<String> {
        let name = format!("Text overlay {number}");
        if self.text.trim().is_empty() {
            return Some(format!("{name} needs text."));
        }
        if self.font_size().is_none() {
            return Some(format!(
                "{name} needs a font size between 1 and {MAX_FONT_SIZE}."
            ));
        }
        if self.opacity().is_none() {
            return Some(format!("{name} opacity must be between 0% and 100%."));
        }
        if self.margin().is_none() {
            return Some(format!("{name} margin must be a non-negative number."));
        }
        if parse_color(&self.color).is_none() || parse_color(&self.shadow).is_none() {
            return Some(format!(
                "{name} colors must be six hex digits, like FFFFFF."
            ));
        }
        let (Some(start), Some(end)) = (parse_time(&self.start), parse_time(&self.end)) else {
            return Some(format!("{name} needs a valid start and end time."));
        };
        if end <= start {
            return Some(format!("{name} must end after it starts."));
        }
        if duration.is_some_and(|d| end > d.ceil()) {
            return Some(format!("{name} must end within the video duration."));
        }
        None
    }

    fn overlay(&self) -> VideoTextOverlay {
        let margin = self.margin().map(|m| m as i32);
        VideoTextOverlay {
            text: self.text.clone(),
            font_color: parse_color(&self.color),
            position: self.position.clone(),
            margin_vertical: margin,
            margin_horizontal: margin,
            font_size: self.font_size().unwrap_or(36) as i32,
            opacity: self.opacity(),
            shadow_color: parse_color(&self.shadow),
            start: parse_time(&self.start).map(|s| s.round() as u32),
            end: parse_time(&self.end).map(|s| s.round() as u32),
            ..Default::default()
        }
    }

    fn from_overlay(overlay: &VideoTextOverlay, duration: Option<f64>) -> Self {
        let margin = overlay.margin_horizontal.or(overlay.margin_vertical);
        TextForm {
            text: overlay.text.clone(),
            position: overlay.position.clone(),
            font_size: overlay.font_size.to_string(),
            opacity: ((overlay.opacity.unwrap_or(0.8) * 100.0).round() as u32).to_string(),
            margin: margin.unwrap_or(0).max(0).to_string(),
            color: overlay
                .font_color
                .clone()
                .unwrap_or_else(|| "FFFFFF".to_owned()),
            shadow: (overlay.shadow_color.clone()).unwrap_or_else(|| "000000".to_owned()),
            start: format_time(f64::from(overlay.start.unwrap_or(0))),
            end: format_time(
                (overlay.end.map(f64::from))
                    .or(duration)
                    .unwrap_or_default(),
            ),
        }
    }
}

/// The part of the (resized) source the output keeps, for a preview: fractions of
/// the source's frame, and the output's size in pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Frame {
    pub left: f64,
    pub top: f64,
    pub width: f64,
    pub height: f64,
    /// The output's size, in pixels.
    pub output: (f64, f64),
}

/// The editor's fields as the user types them. Empty fields keep the source's value.
#[derive(Debug, Clone, PartialEq)]
pub struct ConvertForm {
    /// The trim, as times in the source ([`parse_time`]).
    pub start: String,
    pub end: String,
    /// An aspect ratio to crop to (`16/9`), empty for the source's.
    pub ratio: String,
    pub alignment: VideoAlignment,
    /// The output size, in pixels.
    pub width: String,
    pub height: String,
    /// A centered crop after resizing, in pixels.
    pub crop_width: String,
    pub crop_height: String,
    pub watermark: Option<WatermarkForm>,
    pub texts: Vec<TextForm>,
    pub format: RsVideoFormat,
    /// `None` copies the source's.
    pub codec: Option<RsVideoCodec>,
    pub crf: String,
    pub framerate: String,
    pub no_audio: bool,
    /// The video convert plugin that runs it, `None` for the server's converter.
    pub plugin: Option<String>,
}

impl Default for ConvertForm {
    fn default() -> Self {
        ConvertForm {
            start: String::new(),
            end: String::new(),
            ratio: String::new(),
            alignment: VideoAlignment::Center,
            width: String::new(),
            height: String::new(),
            crop_width: String::new(),
            crop_height: String::new(),
            watermark: None,
            texts: Vec::new(),
            format: RsVideoFormat::Mp4,
            codec: None,
            crf: String::new(),
            framerate: String::new(),
            no_audio: false,
            plugin: None,
        }
    }
}

impl ConvertForm {
    /// The form a preset fills (the web app's `restorePreset`).
    pub fn from_preset(preset: &ConvertPreset, duration: Option<f64>) -> Self {
        let request = &preset.preset;
        let interval = request.intervals.first();
        let format = if FORMATS.contains(&request.format) {
            request.format.clone()
        } else {
            RsVideoFormat::Mp4
        };
        let codec = request
            .codec
            .clone()
            .filter(|c| CODECS.contains(&Some(c.clone())));
        let text = |value: Option<String>| value.unwrap_or_default();
        let number = |value: Option<u16>| value.map(|v| v.to_string()).unwrap_or_default();
        ConvertForm {
            start: interval.map(|i| format_time(i.start)).unwrap_or_default(),
            end: interval
                .and_then(|i| i.duration.map(|d| i.start + d))
                .map(format_time)
                .unwrap_or_default(),
            ratio: text(request.aspect_ratio.clone()),
            alignment: (request.aspect_ratio_alignment.clone()).unwrap_or(VideoAlignment::Center),
            width: text(request.width.clone()),
            height: text(request.height.clone()),
            crop_width: number(request.crop_width),
            crop_height: number(request.crop_height),
            watermark: request.overlay.as_ref().map(|overlay| WatermarkForm {
                name: overlay.path.clone(),
                position: overlay.position.clone(),
                size: (overlay.ratio * 100.0).round().clamp(1.0, 100.0) as u8,
                opacity: (overlay.opacity * 100.0).round().clamp(0.0, 100.0) as u8,
            }),
            texts: (request.texts.iter().flatten())
                .map(|t| TextForm::from_overlay(t, duration))
                .collect(),
            format,
            codec,
            crf: number(request.crf),
            framerate: number(request.framerate),
            no_audio: request.no_audio,
            plugin: preset.plugin.clone(),
        }
    }

    /// Turns the watermark on with `name` (the first of the library's), or off. A
    /// watermark needs a codec: HEVC when it copied the source's.
    pub fn set_watermark(&mut self, name: Option<&str>) {
        self.watermark = name.map(WatermarkForm::new);
        self.overlays_need_codec();
    }

    /// Adds a text after the others, to the end of the video. A text needs a codec:
    /// HEVC when it copied the source's.
    pub fn add_text(&mut self, duration: Option<f64>) {
        let start = (self.texts.iter())
            .filter_map(|t| parse_time(&t.end))
            .fold(0.0, f64::max);
        let end = duration.unwrap_or(start + 5.0).max(start);
        self.texts.push(TextForm::new(start, end));
        self.overlays_need_codec();
    }

    fn overlays_need_codec(&mut self) {
        if (self.watermark.is_some() || !self.texts.is_empty()) && self.codec.is_none() {
            self.codec = Some(RsVideoCodec::H265);
        }
    }

    /// Clears the framing: ratio, alignment, size and crop.
    pub fn reset_framing(&mut self) {
        self.ratio.clear();
        self.alignment = VideoAlignment::Center;
        self.width.clear();
        self.height.clear();
        self.crop_width.clear();
        self.crop_height.clear();
    }

    /// Whether the framing changes the source's frame.
    pub fn has_framing(&self) -> bool {
        [
            &self.ratio,
            &self.width,
            &self.height,
            &self.crop_width,
            &self.crop_height,
        ]
        .iter()
        .any(|field| !field.trim().is_empty())
    }

    /// What the framing does, in a few words: "16/9 crop", "Custom crop", "Resized
    /// output", "Source frame".
    pub fn framing_label(&self) -> String {
        if !self.ratio.trim().is_empty() {
            format!("{} crop", self.ratio.trim())
        } else if !self.crop_width.trim().is_empty() || !self.crop_height.trim().is_empty() {
            "Custom crop".to_owned()
        } else if !self.width.trim().is_empty() || !self.height.trim().is_empty() {
            "Resized output".to_owned()
        } else {
            "Source frame".to_owned()
        }
    }

    /// The trimmed output's length in seconds, when the trim is valid and the
    /// source's duration known.
    pub fn trim_length(&self, duration: Option<f64>) -> Option<f64> {
        let duration = duration?;
        let start = self.trim_point(&self.start)?.unwrap_or(0.0);
        let end = self.trim_point(&self.end)?.unwrap_or(duration);
        (end > start).then_some(end - start)
    }

    /// A trim field: `Some(None)` when empty, `None` when not a time.
    fn trim_point(&self, text: &str) -> Option<Option<f64>> {
        if text.trim().is_empty() {
            Some(None)
        } else {
            parse_time(text).map(Some)
        }
    }

    /// The part of a `source` frame (width, height) the output keeps (the web app's
    /// preview): resized, then the custom crop, then the aspect ratio's crop. Fields
    /// not valid are left out.
    pub fn frame(&self, source: (f64, f64)) -> Frame {
        let (source_width, source_height) = source;
        let full = Frame {
            left: 0.0,
            top: 0.0,
            width: 1.0,
            height: 1.0,
            output: source,
        };
        if source_width <= 0.0 || source_height <= 0.0 {
            return full;
        }
        let side = |text: &str| whole(text, 1..=MAX_SIDE).ok().flatten().map(f64::from);
        let (width, height) = (side(&self.width), side(&self.height));
        let scaled_width = width
            .or(height.map(|h| source_width * h / source_height))
            .unwrap_or(source_width);
        let scaled_height = height
            .or(width.map(|w| source_height * w / source_width))
            .unwrap_or(source_height);

        let (mut left, mut top) = (0.0, 0.0);
        let (mut kept_width, mut kept_height) = (scaled_width, scaled_height);
        if let (Some(crop_width), Some(crop_height)) =
            (side(&self.crop_width), side(&self.crop_height))
            && crop_width <= kept_width
            && crop_height <= kept_height
        {
            left += (kept_width - crop_width) / 2.0;
            top += (kept_height - crop_height) / 2.0;
            (kept_width, kept_height) = (crop_width, crop_height);
        }

        if let Some(ratio) = parse_ratio(&self.ratio) {
            let square = (ratio - 1.0).abs() < f64::EPSILON;
            let (ratio_width, ratio_height) = if square {
                let side = kept_width.min(kept_height);
                (side, side)
            } else if kept_width >= kept_height {
                (kept_height * ratio, kept_height)
            } else {
                (kept_width, kept_width / ratio)
            };
            if ratio_width <= kept_width && ratio_height <= kept_height {
                match (&self.alignment, square) {
                    (VideoAlignment::Center, _) | (_, true) => {
                        left += (kept_width - ratio_width) / 2.0;
                        top += (kept_height - ratio_height) / 2.0;
                    }
                    (VideoAlignment::Right, _) => left += kept_width - ratio_width,
                    (VideoAlignment::Left, _) => {}
                }
                (kept_width, kept_height) = (ratio_width, ratio_height);
            }
        }

        Frame {
            left: left / scaled_width,
            top: top / scaled_height,
            width: kept_width / scaled_width,
            height: kept_height / scaled_height,
            output: (kept_width, kept_height),
        }
    }

    /// What is wrong with the fields, in the web app's wording; empty when the form
    /// can be sent. `duration`: the source's, in seconds, when known.
    pub fn errors(&self, duration: Option<f64>) -> Vec<String> {
        let mut errors = Vec::new();
        let start = self.trim_point(&self.start);
        let end = self.trim_point(&self.end);
        if start.is_none() {
            errors.push("Trim start must be a time, like 1:05 or 65.".to_owned());
        }
        match end {
            None => errors.push("Trim end must be a time, like 1:05 or 65.".to_owned()),
            Some(Some(end)) if end <= 0.0 => {
                errors.push("Trim end time must be a positive number of seconds.".to_owned());
            }
            _ => {}
        }
        let (start, end) = (start.flatten(), end.flatten());
        if (start.is_some() || end.is_some()) && duration.is_none() {
            errors.push("Wait for the video duration before selecting a trim range.".to_owned());
        }
        if let Some(duration) = duration {
            // The server's duration is whole seconds: the last one counts.
            let duration = duration.ceil();
            if start.is_some_and(|s| s > duration) {
                errors.push("Trim start time must be within the source duration.".to_owned());
            }
            if end.is_some_and(|e| e > duration) {
                errors.push("Trim end time must be within the source duration.".to_owned());
            }
        }
        if let (Some(start), Some(end)) = (start, end)
            && end <= start
        {
            errors.push("Trim end time must be later than the start time.".to_owned());
        }

        for (label, value, maximum) in [
            ("Width", &self.width, MAX_SIDE),
            ("Height", &self.height, MAX_SIDE),
            ("Crop width", &self.crop_width, MAX_SIDE),
            ("Crop height", &self.crop_height, MAX_SIDE),
            ("Frame rate", &self.framerate, MAX_FRAMERATE),
        ] {
            if whole(value, 1..=maximum).is_err() {
                errors.push(format!(
                    "{label} must be a whole number between 1 and {maximum}."
                ));
            }
        }
        if whole(&self.crf, 0..=MAX_CRF).is_err() {
            errors.push(format!(
                "CRF must be a whole number between 0 and {MAX_CRF}."
            ));
        }
        if !self.ratio.trim().is_empty() && parse_ratio(&self.ratio).is_none() {
            errors
                .push("Aspect ratio must use whole numbers from 1 to 65535, like 16/9.".to_owned());
        }
        if let Some(watermark) = &self.watermark {
            if watermark.name.is_empty() {
                errors.push("Choose a watermark before converting.".to_owned());
            }
            if !(1..=100).contains(&watermark.size) {
                errors.push("Watermark size must be between 1% and 100%.".to_owned());
            }
            if watermark.opacity > 100 {
                errors.push("Watermark opacity must be between 0% and 100%.".to_owned());
            }
        }
        for (index, text) in self.texts.iter().enumerate() {
            errors.extend(text.error(index + 1, duration));
        }
        errors
    }

    /// The request the form makes, with a new id. Send it only when [`Self::errors`]
    /// is empty: fields not valid are left out.
    pub fn request(&self, duration: Option<f64>) -> VideoConvertRequest {
        let start = self.trim_point(&self.start).flatten();
        let end = self.trim_point(&self.end).flatten();
        let intervals = if start.is_some() || end.is_some() {
            let start = start.unwrap_or(0.0);
            let end = end.or(duration);
            vec![VideoConvertInterval {
                start,
                duration: end.map(|end| end - start),
                input: None,
            }]
        } else {
            Vec::new()
        };
        let small = |text: &str, max: u32| -> Option<u16> {
            whole(text, 0..=max)
                .ok()
                .flatten()
                .and_then(|v| u16::try_from(v).ok())
        };
        let text = |value: &str| Some(value.trim().to_owned()).filter(|v| !v.is_empty());
        VideoConvertRequest {
            id: new_id(),
            format: self.format.clone(),
            codec: self.codec.clone(),
            crf: self.codec.as_ref().and_then(|_| small(&self.crf, MAX_CRF)),
            no_audio: self.no_audio,
            width: text(&self.width),
            height: text(&self.height),
            framerate: small(&self.framerate, MAX_FRAMERATE),
            crop_width: small(&self.crop_width, MAX_SIDE),
            crop_height: small(&self.crop_height, MAX_SIDE),
            aspect_ratio: text(&self.ratio),
            aspect_ratio_alignment: Some(self.alignment.clone()),
            overlay: self.watermark.as_ref().map(|watermark| VideoOverlay {
                kind: VideoOverlayType::Watermark,
                path: watermark.name.clone(),
                position: watermark.position.clone(),
                margin: None,
                ratio: f32::from(watermark.size) / 100.0,
                opacity: f32::from(watermark.opacity) / 100.0,
            }),
            texts: (!self.texts.is_empty())
                .then(|| self.texts.iter().map(TextForm::overlay).collect()),
            intervals,
        }
    }

    /// The form saved as a preset named `name`.
    pub fn preset(&self, name: &str, duration: Option<f64>) -> ConvertPreset {
        ConvertPreset {
            name: name.trim().to_owned(),
            preset: self.request(duration),
            plugin: self.plugin.clone(),
        }
    }
}