Skip to main content

fit_encoder/encoder/
activity.rs

1//! An activity as timed calls: the encoder writes the summaries, numbers and counts.
2
3use super::{
4    check, definition_len, next_index, Error, Extras, Planned, Writer, DISTANCE_CM_MAX,
5    DURATION_SECONDS_MAX, LAPS_MAX, LENGTHS_MAX, SENSORS_MAX, SESSIONS_MAX, SETS_MAX,
6};
7#[allow(unused_imports, reason = "for the docs")]
8use crate::developer::RecordField;
9use crate::developer::{Extra, KindId, DEVELOPER_FIELDS_MAX, SUMMARY_BYTES_MAX};
10use crate::messages::{
11    lap_trigger, trigger, Activity, Altitude, Device, Distance, Event, FieldDef, FileId, Hrv, Lap,
12    LapTrigger, Leg, Length, LengthMsg, Message, Pool, Record, Session, Set, SetMsg, Span,
13    SportMsg, Totals, HRV_BEATS,
14};
15use crate::types::{FileType, Position, Sport, SubSport, SwimStroke, Timestamp};
16#[allow(unused_imports, reason = "for the docs")]
17use crate::{raw::RawField, raw::RAW_FIELDS_MAX};
18
19/// The most bytes the end writes: what ending a session writes, any beat intervals waiting, a
20/// stop event and the activity.
21const END: u32 = CLOSE
22    .saturating_add(most(Hrv::FIELDS))
23    .saturating_add(most(Event::FIELDS))
24    .saturating_add(most(Activity::FIELDS));
25
26/// The most bytes a session ending another writes: what ends that one, and its own sport.
27const SWITCH: u32 = CLOSE.saturating_add(most(SportMsg::FIELDS));
28
29/// The most bytes ending a session writes: what ends its rest, its last lap and itself, and
30/// their developer fields.
31const CLOSE: u32 = REST
32    .saturating_add(most(Lap::FIELDS))
33    .saturating_add(most(Session::FIELDS))
34    .saturating_add(DEV);
35
36/// The most bytes developer fields add to a lap and a session: the file's fields split between
37/// their definitions, each with its count of them, and every byte their values may take.
38#[allow(clippy::cast_possible_truncation, reason = "both are small")]
39const DEV: u32 = {
40    let none = definition_len(0, 0);
41    let split = definition_len(0, (DEVELOPER_FIELDS_MAX as u32).saturating_sub(1))
42        .saturating_add(definition_len(0, 1))
43        .saturating_sub(none)
44        .saturating_sub(none);
45    split.saturating_add(SUMMARY_BYTES_MAX as u32)
46};
47
48/// The most bytes ending a rest writes: an idle length or a rest set.
49const REST: u32 = {
50    let length = most_without(LengthMsg::FIELDS, LengthMsg::SWUM);
51    let set = most_without(SetMsg::FIELDS, SetMsg::ACTIVE);
52    // The larger of the two; `Ord::max` is not const.
53    length.saturating_add(set.saturating_sub(length))
54};
55
56/// The most bytes a message of `fields` takes: its definition, its header and every field.
57const fn most(fields: &[FieldDef]) -> u32 {
58    most_without(fields, &[])
59}
60
61/// [`most`], leaving out the fields numbered in `without`.
62const fn most_without(fields: &[FieldDef], without: &[u8]) -> u32 {
63    let (count, data) = kept_sizes(fields, without);
64    definition_len(count, 0).saturating_add(1).saturating_add(data)
65}
66
67/// How many of `fields` are not numbered in `without`, and their bytes.
68#[allow(clippy::cast_lossless, reason = "u32::from is not const")]
69const fn kept_sizes(fields: &[FieldDef], without: &[u8]) -> (u32, u32) {
70    match fields {
71        [] => (0, 0),
72        [f, rest @ ..] => {
73            let (count, data) = kept_sizes(rest, without);
74            if listed(f.num, without) {
75                (count, data)
76            } else {
77                (count.saturating_add(1), data.saturating_add(f.size as u32))
78            }
79        }
80    }
81}
82
83const fn listed(num: u8, list: &[u8]) -> bool {
84    match list {
85        [] => false,
86        [n, rest @ ..] => *n == num || listed(num, rest),
87    }
88}
89
90/// A length or set, ready to write.
91#[derive(Clone, Copy, Debug)]
92enum Piece {
93    Length { msg: LengthMsg, index: u16, distance: u32, pool: Pool },
94    Set { msg: SetMsg, index: u16 },
95}
96
97impl Piece {
98    fn cost(&self, w: &Writer<'_>) -> Result<Planned, Error> {
99        match self {
100            Self::Length { msg, .. } => w.cost(msg),
101            Self::Set { msg, .. } => w.cost(msg),
102        }
103    }
104
105    /// Adds a length to what `session` and its lap have seen.
106    fn add_to(&self, session: &mut OpenSession) {
107        if let Self::Length { msg, index, distance, pool } = *self {
108            let swum = msg.swum.map(|l| (l, pool.centimetres));
109            session.span.seen.add_length(index, swum, distance, &msg);
110            session.lap.seen.add_length(index, swum, distance, &msg);
111        }
112    }
113}
114
115/// Samples of one unsigned field.
116#[derive(Clone, Copy, Debug, Default)]
117struct Stat {
118    sum: u64,
119    count: u32,
120    max: u32,
121}
122
123impl Stat {
124    fn add(&mut self, v: u32) {
125        self.sum = self.sum.saturating_add(u64::from(v));
126        self.count = self.count.saturating_add(1);
127        self.max = self.max.max(v);
128    }
129
130    /// The average, rounded half up, and the maximum; `None` without a sample.
131    fn summary(self) -> Option<(u32, u32)> {
132        let avg = per(self.sum, self.count)?;
133        Some((u32::try_from(avg).unwrap_or(u32::MAX), self.max))
134    }
135
136    fn summary_u8(self) -> (Option<u8>, Option<u8>) {
137        let s = self.summary();
138        (s.and_then(|(a, _)| u8::try_from(a).ok()), s.and_then(|(_, m)| u8::try_from(m).ok()))
139    }
140
141    fn summary_u16(self) -> (Option<u16>, Option<u16>) {
142        let s = self.summary();
143        (s.and_then(|(a, _)| u16::try_from(a).ok()), s.and_then(|(_, m)| u16::try_from(m).ok()))
144    }
145}
146
147/// Temperatures: their average, rounded half away from zero, and maximum.
148#[derive(Clone, Copy, Debug, Default)]
149struct Temperatures {
150    sum: i64,
151    count: u32,
152    max: Option<i8>,
153}
154
155impl Temperatures {
156    fn add(&mut self, v: i8) {
157        self.sum = self.sum.saturating_add(i64::from(v));
158        self.count = self.count.saturating_add(1);
159        self.max = Some(self.max.map_or(v, |m| m.max(v)));
160    }
161
162    fn average(self) -> Option<i8> {
163        let count = i64::from(self.count);
164        let half = count / 2;
165        let sum = if self.sum.is_negative() {
166            self.sum.saturating_sub(half)
167        } else {
168            self.sum.saturating_add(half)
169        };
170        i8::try_from(sum.checked_div(count)?).ok()
171    }
172}
173
174/// Which way altitude was last going, for the ascent filter.
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176enum Heading {
177    Level,
178    Up,
179    Down,
180}
181
182/// The most records the ascent filter averages.
183const SMOOTHING: usize = crate::messages::SMOOTHING as usize;
184
185/// The ascent filter: altitude averaged over the last few records, and a change of that
186/// average counted once it passes the source's threshold from the extreme it left, the highest
187/// since climbing or the lowest since descending, or before either, the lowest or highest so
188/// far; and then counted in full.
189#[derive(Clone, Copy, Debug)]
190struct Climb {
191    threshold: i64,
192    /// The records averaged, and the latest of them, newest last.
193    window: usize,
194    recent: [i64; SMOOTHING],
195    heading: Heading,
196    low: i64,
197    high: i64,
198    /// The last altitude, and what is added to each after it, so a jump across a pause counts
199    /// nothing; and whether the next comes after a pause.
200    last: i64,
201    shift: i64,
202    paused: bool,
203}
204
205/// How many records an altitude's `window` averages over.
206fn span(window: u8) -> usize {
207    usize::from(window).clamp(1, SMOOTHING)
208}
209
210impl Climb {
211    fn new(fifths: u32, threshold: u32, window: u8) -> Self {
212        let at = i64::from(fifths);
213        let (low, high, last) = (at, at, at);
214        let threshold = i64::from(threshold);
215        let window = span(window);
216        let recent = [at; SMOOTHING];
217        Self {
218            threshold,
219            window,
220            recent,
221            heading: Heading::Level,
222            low,
223            high,
224            last,
225            shift: 0,
226            paused: false,
227        }
228    }
229
230    /// The average of the latest records with `at`, which joins them, to the nearest fifth.
231    fn average(&mut self, at: i64) -> i64 {
232        self.recent.rotate_left(1);
233        if let Some(newest) = self.recent.last_mut() {
234            *newest = at;
235        }
236        let latest = self.recent.iter().rev().take(self.window);
237        let sum = latest.fold(0i64, |sum, &a| sum.saturating_add(a));
238        let n = i64::try_from(self.window).unwrap_or(1);
239        sum.saturating_add(n / 2).checked_div_euclid(n).unwrap_or(at)
240    }
241
242    /// The fifths of a metre `fifths` climbs and descends from where the filter was.
243    fn step(&mut self, fifths: u32) -> (u32, u32) {
244        let mut at = i64::from(fifths).saturating_add(self.shift);
245        if self.paused {
246            self.shift = self.shift.saturating_add(self.last.saturating_sub(at));
247            (at, self.paused) = (self.last, false);
248        }
249        self.last = at;
250        let at = self.average(at);
251        let (low, high, th) = (self.low, self.high, self.threshold);
252        let fifths = |d: i64| u32::try_from(d).unwrap_or(u32::MAX);
253        match self.heading {
254            Heading::Up if at > high => {
255                self.high = at;
256                (fifths(at.saturating_sub(high)), 0)
257            }
258            Heading::Down if at < low => {
259                self.low = at;
260                (0, fifths(low.saturating_sub(at)))
261            }
262            Heading::Level | Heading::Down if at >= low.saturating_add(th) => {
263                (self.heading, self.high) = (Heading::Up, at);
264                (fifths(at.saturating_sub(low)), 0)
265            }
266            Heading::Level | Heading::Up if at.saturating_add(th) <= high => {
267                (self.heading, self.low) = (Heading::Down, at);
268                (0, fifths(high.saturating_sub(at)))
269            }
270            Heading::Level => {
271                (self.low, self.high) = (low.min(at), high.max(at));
272                (0, 0)
273            }
274            Heading::Up | Heading::Down => (0, 0),
275        }
276    }
277}
278
279/// Longitudes seen, both as signed semicircles and as unsigned ones, which run from 0° east
280/// round to 360°, so a track across ±180° has a narrow box in one of the two.
281#[derive(Clone, Copy, Debug)]
282struct Longitudes {
283    signed: (i32, i32),
284    unsigned: (u32, u32),
285}
286
287impl Longitudes {
288    #[allow(clippy::cast_sign_loss)]
289    const fn new(long: i32) -> Self {
290        Self { signed: (long, long), unsigned: (long as u32, long as u32) }
291    }
292
293    #[allow(clippy::cast_sign_loss)]
294    fn add(&mut self, long: i32) {
295        self.signed = (self.signed.0.min(long), self.signed.1.max(long));
296        let u = long as u32;
297        self.unsigned = (self.unsigned.0.min(u), self.unsigned.1.max(u));
298    }
299
300    /// West and east: east is less than west when the box crosses ±180°.
301    #[allow(clippy::cast_possible_wrap)]
302    fn west_east(self) -> (i32, i32) {
303        let signed = self.signed.1.abs_diff(self.signed.0);
304        let unsigned = self.unsigned.1.abs_diff(self.unsigned.0);
305        if unsigned < signed {
306            (self.unsigned.0 as i32, self.unsigned.1 as i32)
307        } else {
308            self.signed
309        }
310    }
311}
312
313/// What a lap or session has seen of its records.
314#[derive(Clone, Copy, Debug, Default)]
315struct Seen {
316    heart_rate: Stat,
317    cadence: Stat,
318    power: Stat,
319    max_speed: Option<u16>,
320    temperature: Temperatures,
321    /// The activity's distance at the start, and the last a record in it gave.
322    distance_base: u32,
323    distance: Option<u32>,
324    /// Climbed and descended, in fifths of a metre, and whether a record gave an altitude.
325    ascent: u32,
326    descent: u32,
327    climbed: bool,
328    /// The session's climb and descent before a lap, which its metres count from.
329    climb_base: (u32, u32),
330    start: Option<Position>,
331    end: Option<Position>,
332    latitudes: Option<(i32, i32)>,
333    longitudes: Option<Longitudes>,
334    /// Pool lengths, idle and active, the first one's index, and the strokes of those swum
335    /// with a stroke count, with the distance they covered in centimetres.
336    lengths: u16,
337    active_lengths: u16,
338    first_length: Option<u16>,
339    strokes: u32,
340    stroked_cm: u32,
341    swim_stroke: Option<SwimStroke>,
342    /// Repetitions of strength sets, kept for the session alone.
343    repetitions: Option<u32>,
344}
345
346impl Seen {
347    fn new(distance_base: u32) -> Self {
348        Self { distance_base, ..Self::default() }
349    }
350
351    fn add(&mut self, r: &Record, climb: Option<(u32, u32)>) {
352        if let Some(p) = r.position {
353            let (lat, long) = p.semicircles();
354            self.start.get_or_insert(p);
355            self.end = Some(p);
356            let (south, north) = self.latitudes.unwrap_or((lat, lat));
357            self.latitudes = Some((south.min(lat), north.max(lat)));
358            self.longitudes.get_or_insert(Longitudes::new(long)).add(long);
359        }
360        if r.distance.is_some() {
361            self.distance = r.distance;
362        }
363        if let Some((up, down)) = climb {
364            self.ascent = self.ascent.saturating_add(up);
365            self.descent = self.descent.saturating_add(down);
366            self.climbed = true;
367        }
368        if let Some(v) = r.heart_rate {
369            self.heart_rate.add(u32::from(v));
370        }
371        if let Some(v) = r.cadence {
372            self.cadence.add(u32::from(v));
373        }
374        if let Some(v) = r.power {
375            self.power.add(u32::from(v));
376        }
377        if let Some(v) = r.speed {
378            self.max_speed = Some(self.max_speed.map_or(v, |m| m.max(v)));
379        }
380        if let Some(v) = r.temperature {
381            self.temperature.add(v);
382        }
383    }
384
385    /// A pool length with its index, the activity's distance after it, and for one swum, the
386    /// pool, its speed and cadence.
387    fn add_length(
388        &mut self,
389        index: u16,
390        swum: Option<(Length, u16)>,
391        distance: u32,
392        msg: &LengthMsg,
393    ) {
394        self.lengths = self.lengths.saturating_add(1);
395        self.first_length.get_or_insert(index);
396        self.distance = Some(distance);
397        let Some((length, pool_cm)) = swum else { return };
398        self.active_lengths = self.active_lengths.saturating_add(1);
399        let stroke = length.stroke;
400        self.swim_stroke = Some(match self.swim_stroke {
401            Some(s) if s != stroke => SwimStroke::MIXED,
402            _ => stroke,
403        });
404        if let Some(n) = length.strokes {
405            self.strokes = self.strokes.saturating_add(u32::from(n));
406            self.stroked_cm = self.stroked_cm.saturating_add(u32::from(pool_cm));
407        }
408        if let Some(v) = msg.cadence {
409            self.cadence.add(u32::from(v));
410        }
411        if let Some(v) = msg.avg_speed {
412            self.max_speed = Some(self.max_speed.map_or(v, |m| m.max(v)));
413        }
414    }
415
416    fn add_repetitions(&mut self, set: &Set) {
417        if let Some(n) = set.repetitions {
418            self.repetitions = Some(self.repetitions.unwrap_or(0).saturating_add(u32::from(n)));
419        }
420    }
421
422    /// The totals over `timer` seconds, with a value its field cannot hold left as none.
423    fn totals(&self, timer: u32) -> Totals {
424        let distance = self.distance.map(|last| last.saturating_sub(self.distance_base));
425        let avg_speed = distance.and_then(|d| {
426            let mm_per_s = per(u64::from(d) * 10, timer)?;
427            u16::try_from(mm_per_s).ok().filter(|&v| v != u16::MAX)
428        });
429        // A maximum below the average is a sampling gap, not a speed: leave it out.
430        let max_speed = self.max_speed.filter(|&m| avg_speed.is_none_or(|avg| m >= avg));
431        let metres =
432            |fifths: u32| u16::try_from(per(fifths, 5u32)?).ok().filter(|&v| v != u16::MAX);
433        let since = |base: u32, fifths: u32| {
434            metres(base.saturating_add(fifths))?.checked_sub(metres(base)?)
435        };
436        let swam = self.lengths > 0;
437        let (avg_cadence, max_cadence) = self.cadence.summary_u8();
438        let (avg_power, max_power) = self.power.summary_u16();
439        let corners = self.latitudes.zip(self.longitudes).map(|((south, north), longs)| {
440            let (west, east) = longs.west_east();
441            (Position::from_semicircles(north, east), Position::from_semicircles(south, west))
442        });
443        Totals {
444            start: self.start,
445            end: self.end,
446            north_east: corners.and_then(|c| c.0),
447            south_west: corners.and_then(|c| c.1),
448            distance,
449            avg_speed,
450            max_speed,
451            avg_cadence,
452            max_cadence,
453            avg_power,
454            max_power,
455            ascent: self.climbed.then(|| since(self.climb_base.0, self.ascent)).flatten(),
456            descent: self.climbed.then(|| since(self.climb_base.1, self.descent)).flatten(),
457            avg_temperature: self.temperature.average(),
458            max_temperature: self.temperature.max,
459            cycles: swam.then_some(self.strokes),
460            lengths: swam.then_some(self.lengths),
461            active_lengths: swam.then_some(self.active_lengths),
462            stroke_distance: per(self.stroked_cm, self.strokes)
463                .and_then(|cm| u16::try_from(cm).ok())
464                .filter(|&cm| cm != u16::MAX),
465            swim_stroke: self.swim_stroke,
466        }
467    }
468}
469
470/// A lap or session that has started and not yet ended.
471#[derive(Clone, Copy, Debug)]
472struct Open {
473    start: Timestamp,
474    /// The timer's seconds at `start`.
475    timer: u32,
476    seen: Seen,
477}
478
479impl Open {
480    fn new(start: Timestamp, timer: u32, distance: u32) -> Self {
481        Self { start, timer, seen: Seen::new(distance) }
482    }
483}
484
485#[derive(Clone, Copy, Debug)]
486struct OpenSession {
487    span: Open,
488    sport: Sport,
489    sub_sport: SubSport,
490    pool: Option<Pool>,
491    first_lap: u16,
492    lap: Open,
493    /// Where the next length or set starts, with the timer's seconds there, and whether a
494    /// rest started there.
495    mark: (Timestamp, u32),
496    resting: bool,
497}
498
499impl OpenSession {
500    /// Whether it takes strength sets and rests between them: training, of any sub-sport, and
501    /// HIIT.
502    fn takes_sets(&self) -> bool {
503        self.sport == Sport::TRAINING || self.sport == Sport::HIIT
504    }
505}
506
507#[derive(Clone, Copy, Debug, PartialEq, Eq)]
508enum Phase {
509    NotStarted,
510    Started,
511    /// Writing the end into the bytes kept for it.
512    Ending,
513    Ended,
514}
515
516/// Where the activity is.
517#[derive(Clone, Copy, Debug)]
518pub(super) struct Act {
519    phase: Phase,
520    /// The latest time written.
521    now: Timestamp,
522    /// The timer's seconds up to `since`, and whether it has run since then.
523    timer: u32,
524    since: Timestamp,
525    running: bool,
526    session: Option<OpenSession>,
527    devices: u8,
528    /// The distance covered, in centimetres, and the ascent filter.
529    distance: u32,
530    micrometres: u64,
531    climb: Option<Climb>,
532    lengths: u16,
533    sets: u16,
534    /// Beat intervals not yet written, in milliseconds.
535    beats: [u16; HRV_BEATS],
536    beat_count: usize,
537}
538
539impl Act {
540    pub(super) const fn new() -> Self {
541        let zero = Timestamp::from_fit(0);
542        Self {
543            phase: Phase::NotStarted,
544            now: zero,
545            timer: 0,
546            since: zero,
547            running: false,
548            session: None,
549            devices: 0,
550            distance: 0,
551            micrometres: 0,
552            climb: None,
553            lengths: 0,
554            sets: 0,
555            beats: [0; HRV_BEATS],
556            beat_count: 0,
557        }
558    }
559
560    pub(super) fn ended(&self) -> bool {
561        self.phase == Phase::Ended
562    }
563
564    /// The bytes every write must leave free so the activity can still end.
565    pub(super) fn kept_for_end(&self) -> u32 {
566        if self.phase == Phase::Started {
567            END
568        } else {
569            0
570        }
571    }
572
573    /// Refuses a call outside the activity.
574    pub(super) fn open(&self) -> Result<(), Error> {
575        self.started(self.now)
576    }
577
578    /// Refuses a call outside a session.
579    pub(super) fn in_session(&self) -> Result<(), Error> {
580        self.open()?;
581        self.session.map(|_| ()).ok_or(Error::OutOfOrder)
582    }
583
584    /// The timer's seconds at `t`, which is no earlier than `since`.
585    fn timer_at(&self, t: Timestamp) -> u32 {
586        let running = if self.running { t.fit().saturating_sub(self.since.fit()) } else { 0 };
587        self.timer.saturating_add(running)
588    }
589
590    /// The activity's distance after `input`, which may not take it back, in centimetres and
591    /// the micrometres past them.
592    fn distance_after(&self, input: Distance) -> Result<(u32, u64), Error> {
593        let next = match input {
594            Distance::Advanced(um) => {
595                let total = u64::from(self.distance)
596                    .saturating_mul(10_000)
597                    .saturating_add(self.micrometres);
598                total
599                    .checked_add(um)
600                    .and_then(|t| Some((u32::try_from(t / 10_000).ok()?, t % 10_000)))
601            }
602            Distance::Total(cm) if cm < self.distance => return Err(Error::DistanceWentBack),
603            Distance::Total(cm) => Some((cm, 0)),
604        };
605        next.filter(|&(d, _)| d <= DISTANCE_CM_MAX).ok_or(Error::OutOfRange)
606    }
607
608    /// Moves the ascent filter to `altitude`, returning what it climbed and descended; a
609    /// different threshold or smoothing starts the filter afresh.
610    fn climb_to(&mut self, altitude: Altitude) -> (u32, u32) {
611        let (fifths, threshold) = (u32::from(altitude.fifths), u32::from(altitude.threshold));
612        let window = altitude.window;
613        match self.climb.as_mut() {
614            Some(c) if c.threshold == i64::from(threshold) && c.window == span(window) => {
615                c.step(fifths)
616            }
617            _ => {
618                self.climb = Some(Climb::new(fifths, threshold, window));
619                (0, 0)
620            }
621        }
622    }
623
624    /// The latest time written.
625    pub(super) const fn now(&self) -> Timestamp {
626        self.now
627    }
628
629    /// Moves the activity on to `t`, no earlier than its time.
630    pub(super) fn move_to(&mut self, t: Timestamp) {
631        self.now = t;
632    }
633
634    pub(super) fn started(&self, t: Timestamp) -> Result<(), Error> {
635        if self.phase != Phase::Started {
636            return Err(Error::OutOfOrder);
637        }
638        if t < self.now {
639            return Err(Error::TimeWentBack);
640        }
641        Ok(())
642    }
643}
644
645impl Leg<'_> {
646    /// Refuses a leg that [`Writer::leg`] could never start, whatever the activity: one of
647    /// `lap_swimming` without a pool, a pool of no length or too long, a sport or sub-sport of
648    /// FIT's "none", or a name too long or holding a NUL. What it refuses, `leg` refuses the
649    /// same way whenever it could otherwise start one, so a recorder that writes an activity
650    /// later can refuse a leg when it is chosen.
651    ///
652    /// ```
653    /// use fit_encoder::{Error, Leg, Sport, SubSport};
654    ///
655    /// assert_eq!(Leg::new(Sport::RUNNING, SubSport::TRAIL).check(), Ok(()));
656    /// let pool_swim = Leg::new(Sport::SWIMMING, SubSport::LAP_SWIMMING);
657    /// assert_eq!(pool_swim.check(), Err(Error::OutOfRange));
658    /// ```
659    ///
660    /// # Errors
661    ///
662    /// [`Error::OutOfRange`] or [`Error::StringTooLong`].
663    pub fn check(&self) -> Result<(), Error> {
664        let no_pool = self.pool.is_none() && self.sport.sub_sport == SubSport::LAP_SWIMMING;
665        if no_pool || self.pool.is_some_and(|p| p.centimetres == 0 || p.centimetres == u16::MAX) {
666            return Err(Error::OutOfRange);
667        }
668        check(&self.sport)
669    }
670}
671
672/// `n` over `d`, rounded half up; `None` over nothing.
673fn per(n: impl Into<u64>, d: impl Into<u64>) -> Option<u64> {
674    let (n, d) = (n.into(), d.into());
675    n.saturating_add(d / 2).checked_div(d)
676}
677
678/// Seconds as FIT's milliseconds; too many is FIT's "none", which writing refuses.
679fn ms(seconds: u32) -> u32 {
680    if seconds > DURATION_SECONDS_MAX {
681        u32::MAX
682    } else {
683        seconds.saturating_mul(1000)
684    }
685}
686
687fn lap_message(lap: &Open, end: Timestamp, timer: u32, session: &OpenSession) -> Lap {
688    let elapsed = end.fit().saturating_sub(lap.start.fit());
689    let timer = timer.saturating_sub(lap.timer);
690    let mut msg = Lap::new(lap.start, end, ms(elapsed), ms(timer))
691        .sport(session.sport, session.sub_sport)
692        .totals(lap.seen.totals(timer));
693    if let Some(i) = lap.seen.first_length {
694        msg = msg.first_length(i);
695    }
696    if let (Some(avg), Some(max)) = lap.seen.heart_rate.summary_u8() {
697        msg = msg.heart_rate(avg, max);
698    }
699    msg
700}
701
702impl Writer<'_> {
703    /// Starts the activity at `t`, recorded by `creator`. The timer starts with the first
704    /// session.
705    ///
706    /// # Errors
707    ///
708    /// [`Error::OutOfOrder`] if it has started already; see [`Error`].
709    pub fn start(&mut self, t: Timestamp, creator: &Device<'_>) -> Result<(), Error> {
710        if self.st.act.phase != Phase::NotStarted {
711            return Err(Error::OutOfOrder);
712        }
713        let mut id = FileId::new(FileType::ACTIVITY, creator.manufacturer, creator.product, t);
714        if let Some(serial) = creator.serial_number {
715            id = id.serial_number(serial);
716        }
717        let info = creator.info(t, 0);
718        let first = self.cost(&id)?;
719        self.endable(t, 0, 0)?;
720        self.room(first.size().saturating_add(self.cost(&info)?.after(&first)))?;
721        self.raw_file_id(&id)?;
722        self.raw_device_info(&info)?;
723        let act = &mut self.st.act;
724        act.phase = Phase::Started;
725        (act.now, act.since, act.running, act.timer) = (t, t, false, 0);
726        Ok(())
727    }
728
729    /// Writes a sensor the activity used, as the next `device_index` after the creator's.
730    ///
731    /// # Errors
732    ///
733    /// [`Error::OutOfOrder`] outside the activity, [`Error::IndexFull`] after
734    /// [`SENSORS_MAX`]; see [`Error`].
735    pub fn device(&mut self, device: &Device<'_>) -> Result<(), Error> {
736        let now = self.st.act.now;
737        self.st.act.started(now)?;
738        let index = self.st.act.devices.checked_add(1).filter(|&i| i <= SENSORS_MAX);
739        let index = index.ok_or(Error::IndexFull)?;
740        self.raw_device_info(&device.info(now, index))?;
741        self.st.act.devices = index;
742        Ok(())
743    }
744
745    /// Starts a session of `sport` at `t`, ending the one before it there: the next leg of a
746    /// multisport activity, or a transition between legs. [`Writer::leg`] starts one with a
747    /// name, or moved to by hand.
748    ///
749    /// # Errors
750    ///
751    /// [`Error::OutOfRange`] for `lap_swimming`, as a pool swim starts with
752    /// [`Writer::pool_swim`], or for FIT's "none", as [`Leg::check`] refuses them; see
753    /// [`Error`].
754    pub fn session(
755        &mut self,
756        t: Timestamp,
757        sport: Sport,
758        sub_sport: SubSport,
759    ) -> Result<(), Error> {
760        self.leg(t, &Leg::new(sport, sub_sport))
761    }
762
763    /// Starts a pool swim at `t` in `pool`, as [`Writer::session`] starts any other: its
764    /// distance is the pool's length for each length swum, from [`Writer::length`].
765    ///
766    /// # Errors
767    ///
768    /// [`Error::OutOfRange`] for a pool of no length or too long; see [`Error`].
769    pub fn pool_swim(&mut self, t: Timestamp, pool: Pool) -> Result<(), Error> {
770        self.leg(t, &Leg::pool_swim(pool))
771    }
772
773    /// Starts the session `leg` describes at `t`, ending the one before it there, as
774    /// [`Writer::session`] and [`Writer::pool_swim`] do.
775    ///
776    /// # Errors
777    ///
778    /// Those of [`Leg::check`], [`Error::OutOfOrder`] for a first leg moved to by hand; see
779    /// [`Error`].
780    pub fn leg(&mut self, t: Timestamp, leg: &Leg<'_>) -> Result<(), Error> {
781        let Leg { sport, pool, by_hand } = *leg;
782        self.st.act.started(t)?;
783        leg.check()?;
784        let first = self.st.act.session.is_none();
785        if first && by_hand {
786            return Err(Error::OutOfOrder);
787        }
788        let closed = u16::from(!first);
789        let (laps, sessions) = (self.st.laps, self.st.sessions);
790        self.endable(t, laps.saturating_add(closed), sessions.saturating_add(closed))?;
791        let cost = self.cost(&sport)?;
792        if first {
793            let start = Event::timer_start(t);
794            let event = self.cost(&start)?;
795            self.room(event.size().saturating_add(cost.after(&event)))?;
796            self.raw_event(start)?;
797            let act = &mut self.st.act;
798            (act.since, act.running) = (t, true);
799        } else {
800            self.room(SWITCH)?;
801            if let Some(piece) = self.rest_piece(t)? {
802                self.put_piece(t, piece)?;
803            }
804            let trigger = if self.st.options.auto_multisport && !by_hand {
805                trigger::AUTO_MULTI_SPORT
806            } else {
807                trigger::MANUAL
808            };
809            self.close_session(t, trigger)?;
810        }
811        self.fixed(&sport, 0)?;
812        let SportMsg { sport, sub_sport, .. } = sport;
813        let (timer, distance) = (self.st.act.timer_at(t), self.st.act.distance);
814        self.st.act.session = Some(OpenSession {
815            span: Open::new(t, timer, distance),
816            sport,
817            sub_sport,
818            pool,
819            first_lap: self.st.laps,
820            lap: Open::new(t, timer, distance),
821            mark: (t, timer),
822            resting: false,
823        });
824        // Each leg climbs from where it starts.
825        self.st.act.climb = None;
826        self.st.act.now = t;
827        Ok(())
828    }
829
830    /// Writes a record in the current session.
831    ///
832    /// # Errors
833    ///
834    /// [`Error::OutOfOrder`] outside a session, [`Error::Paused`] while the timer is paused,
835    /// [`Error::DistanceWentBack`] for a total distance below one already written; see
836    /// [`Error`].
837    pub fn record(&mut self, record: &Record) -> Result<(), Error> {
838        self.record_with(record, &[])
839    }
840
841    /// Writes a record with fields besides those [`Record`] models: developer fields, from
842    /// [`RecordField::value`], and raw fields, from [`RawField`]. A raw field may not be one
843    /// the encoder writes: those [`Record`] sets, the `timestamp`, or another form of one,
844    /// `compressed_speed_distance` (8), `enhanced_speed` (73) and `enhanced_altitude` (78).
845    ///
846    /// # Errors
847    ///
848    /// Those of [`Writer::record`]; [`Error::Undeclared`] for a field this file did not
849    /// declare, [`Error::Duplicate`] for one given twice, [`Error::Reserved`] for a raw field
850    /// the encoder writes, [`Error::TooMany`] past [`RAW_FIELDS_MAX`] raw fields.
851    pub fn record_with(&mut self, record: &Record, extras: &[Extra<'_>]) -> Result<(), Error> {
852        let t = record.timestamp;
853        self.st.act.started(t)?;
854        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
855        if !self.st.act.running {
856            return Err(Error::Paused);
857        }
858        let from_lengths =
859            record.distance_input.is_some() || record.speed.is_some() || record.cadence.is_some();
860        if session.pool.is_some() && from_lengths {
861            return Err(Error::GivenByLengths);
862        }
863        let mut record = *record;
864        let distance = match record.distance_input {
865            None => None,
866            Some(input) => Some(self.st.act.distance_after(input)?),
867        };
868        record.distance = distance.map(|(cm, _)| cm);
869        self.endable(t, self.st.laps, self.st.sessions)?;
870        let size = self.record_cost(&record, extras)?;
871        self.room(self.beats_cost()?.saturating_add(size))?;
872        // Beats follow the record before them, which readers count their times from.
873        self.write_beats()?;
874        self.raw_record_with(record, extras)?;
875        let act = &mut self.st.act;
876        act.now = t;
877        if let Some((cm, um)) = distance {
878            (act.distance, act.micrometres) = (cm, um);
879        }
880        let climb = record.altitude.map(|a| act.climb_to(a));
881        if let Some(s) = act.session.as_mut() {
882            s.span.seen.add(&record, climb);
883            s.lap.seen.add(&record, climb);
884        }
885        Ok(())
886    }
887
888    /// Ends the current lap at `t`, by hand, and starts the next.
889    ///
890    /// # Errors
891    ///
892    /// [`Error::OutOfOrder`] outside a session or during a rest in a pool swim; see [`Error`].
893    pub fn lap(&mut self, t: Timestamp) -> Result<(), Error> {
894        self.lap_by(t, LapTrigger::Manual)
895    }
896
897    /// [`Writer::lap`], for a lap that `trigger` ended, such as the device's automatic lap
898    /// every kilometre.
899    ///
900    /// # Errors
901    ///
902    /// As [`Writer::lap`].
903    pub fn lap_by(&mut self, t: Timestamp, trigger: LapTrigger) -> Result<(), Error> {
904        self.st.act.started(t)?;
905        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
906        if session.resting && session.pool.is_some() {
907            return Err(Error::OutOfOrder);
908        }
909        self.end_lap(t, &session, trigger)
910    }
911
912    /// Ends the open session's current lap at `t` and starts the next there.
913    fn end_lap(
914        &mut self,
915        t: Timestamp,
916        session: &OpenSession,
917        trigger: LapTrigger,
918    ) -> Result<(), Error> {
919        let timer = self.st.act.timer_at(t);
920        let lap = lap_message(&session.lap, t, timer, session).trigger(trigger.get());
921        check(&lap)?;
922        self.endable(t, self.st.laps.saturating_add(1), self.st.sessions)?;
923        self.raw_lap(&lap)?;
924        let act = &mut self.st.act;
925        act.now = t;
926        if let Some(s) = act.session.as_mut() {
927            s.lap = Open::new(t, timer, act.distance);
928            s.lap.seen.climb_base = (s.span.seen.ascent, s.span.seen.descent);
929            if !s.resting {
930                s.mark = (t, timer);
931            }
932        }
933        Ok(())
934    }
935
936    /// Pauses the timer at `t`.
937    ///
938    /// # Errors
939    ///
940    /// [`Error::OutOfOrder`] before the first session or if it is paused already; see
941    /// [`Error`].
942    pub fn pause(&mut self, t: Timestamp) -> Result<(), Error> {
943        self.st.act.started(t)?;
944        if !self.st.act.running {
945            return Err(Error::OutOfOrder);
946        }
947        self.endable(t, self.st.laps, self.st.sessions)?;
948        self.raw_event(Event::timer_stop(t))?;
949        let act = &mut self.st.act;
950        (act.timer, act.since, act.running, act.now) = (act.timer_at(t), t, false, t);
951        if let Some(c) = act.climb.as_mut() {
952            c.paused = true;
953        }
954        Ok(())
955    }
956
957    /// Resumes the timer at `t`.
958    ///
959    /// # Errors
960    ///
961    /// [`Error::OutOfOrder`] before the first session or if it is running; see [`Error`].
962    pub fn resume(&mut self, t: Timestamp) -> Result<(), Error> {
963        self.st.act.started(t)?;
964        if self.st.act.running || self.st.act.session.is_none() {
965            return Err(Error::OutOfOrder);
966        }
967        self.endable(t, self.st.laps, self.st.sessions)?;
968        self.raw_event(Event::timer_start(t))?;
969        let act = &mut self.st.act;
970        (act.since, act.running, act.now) = (t, true, t);
971        Ok(())
972    }
973
974    /// Ends a length of the pool at `t`, swum since the last length, rest or lap ended, or the
975    /// pool swim started.
976    ///
977    /// # Errors
978    ///
979    /// [`Error::OutOfOrder`] outside a pool swim or during a rest, [`Error::Paused`] while the
980    /// timer is paused, [`Error::IndexFull`] after [`LENGTHS_MAX`]; see [`Error`].
981    pub fn length(&mut self, t: Timestamp, length: &Length) -> Result<(), Error> {
982        self.st.act.started(t)?;
983        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
984        if session.pool.is_none() || session.resting {
985            return Err(Error::OutOfOrder);
986        }
987        if !self.st.act.running {
988            return Err(Error::Paused);
989        }
990        let piece = self.length_at(t, &session, Some(*length))?;
991        self.put_piece(t, piece)
992    }
993
994    /// Writes a strength set that ends at `t`, done since the last set, rest or lap ended, or
995    /// the session started.
996    ///
997    /// # Errors
998    ///
999    /// [`Error::OutOfOrder`] outside a training or HIIT session or during a rest,
1000    /// [`Error::Paused`] while the timer is paused, [`Error::IndexFull`] after [`SETS_MAX`];
1001    /// see [`Error`].
1002    pub fn set(&mut self, t: Timestamp, set: &Set) -> Result<(), Error> {
1003        self.st.act.started(t)?;
1004        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
1005        if !session.takes_sets() || session.resting {
1006            return Err(Error::OutOfOrder);
1007        }
1008        if !self.st.act.running {
1009            return Err(Error::Paused);
1010        }
1011        let piece = self.set_at(t, &session, Some(*set))?;
1012        self.put_piece(t, piece)
1013    }
1014
1015    /// Starts a rest at `t`, which [`Writer::end_rest`] ends. In a pool swim the lap of lengths
1016    /// before it ends here, and the rest is an idle length in a lap of its own; in a training
1017    /// or HIIT session it is a rest between strength sets.
1018    ///
1019    /// # Errors
1020    ///
1021    /// [`Error::OutOfOrder`] outside a pool swim or a training or HIIT session, or during a
1022    /// rest; see [`Error`].
1023    pub fn rest(&mut self, t: Timestamp) -> Result<(), Error> {
1024        self.st.act.started(t)?;
1025        let Some(session) = self.st.act.session else { return Err(Error::OutOfOrder) };
1026        if session.resting || (session.pool.is_none() && !session.takes_sets()) {
1027            return Err(Error::OutOfOrder);
1028        }
1029        // Whatever ends the rest writes a length or set, which must have an index left.
1030        match session.pool {
1031            Some(_) => next_index(self.st.act.lengths, LENGTHS_MAX)?,
1032            None => next_index(self.st.act.sets, SETS_MAX)?,
1033        };
1034        if session.pool.is_some() && session.lap.seen.lengths > 0 {
1035            self.end_lap(t, &session, LapTrigger::Manual)?;
1036        } else {
1037            self.endable(t, self.st.laps, self.st.sessions)?;
1038        }
1039        let act = &mut self.st.act;
1040        let timer = act.timer_at(t);
1041        act.now = t;
1042        if let Some(s) = act.session.as_mut() {
1043            (s.mark, s.resting) = ((t, timer), true);
1044        }
1045        Ok(())
1046    }
1047
1048    /// Ends the rest at `t`.
1049    ///
1050    /// # Errors
1051    ///
1052    /// [`Error::OutOfOrder`] outside a rest, [`Error::IndexFull`] after [`LENGTHS_MAX`] or
1053    /// [`SETS_MAX`]; see [`Error`].
1054    pub fn end_rest(&mut self, t: Timestamp) -> Result<(), Error> {
1055        self.st.act.started(t)?;
1056        let Some(session) = self.st.act.session.filter(|s| s.resting) else {
1057            return Err(Error::OutOfOrder);
1058        };
1059        if session.pool.is_none() {
1060            let piece = self.set_at(t, &session, None)?;
1061            return self.put_piece(t, piece);
1062        }
1063        let piece = self.length_at(t, &session, None)?;
1064        self.endable(t, self.st.laps.saturating_add(1), self.st.sessions)?;
1065        let mut after = session;
1066        piece.add_to(&mut after);
1067        let lap = lap_message(&after.lap, t, self.st.act.timer_at(t), &after);
1068        check(&lap)?;
1069        let lap = self.cost_with(&lap, Extras::Staged(KindId::Lap))?;
1070        let length = piece.cost(self)?;
1071        self.room(length.size().saturating_add(lap.after(&length)))?;
1072        self.put_piece(t, piece)?;
1073        let session = self.st.act.session.ok_or(Error::OutOfOrder)?;
1074        self.end_lap(t, &session, LapTrigger::Manual)
1075    }
1076
1077    /// Adds the intervals between heartbeats, in milliseconds, as they arrive; a beat's
1078    /// interval ends it. They are written five to a `hrv` message, and before the next record,
1079    /// so each follows the record it came after; they are kept while the timer is paused, as
1080    /// their sum is their only clock.
1081    ///
1082    /// # Errors
1083    ///
1084    /// [`Error::OutOfOrder`] outside the activity, [`Error::OutOfRange`] for 65,535; see
1085    /// [`Error`].
1086    pub fn beat_intervals_ms(&mut self, intervals: &[u16]) -> Result<(), Error> {
1087        self.beats_fit(intervals, true)?;
1088        self.beats(intervals.iter().copied())
1089    }
1090
1091    /// [`Writer::beat_intervals_ms`], from intervals in 1/1024 s, as a Bluetooth heart rate
1092    /// sensor gives them; each is rounded to the millisecond.
1093    ///
1094    /// # Errors
1095    ///
1096    /// [`Error::OutOfOrder`] outside the activity; see [`Error`].
1097    pub fn beat_intervals_1024ths(&mut self, intervals: &[u16]) -> Result<(), Error> {
1098        self.beats_fit(intervals, false)?;
1099        self.beats(intervals.iter().map(|&n| {
1100            let ms = per(u32::from(n).saturating_mul(1000), 1024u32);
1101            ms.and_then(|ms| u16::try_from(ms).ok()).unwrap_or(u16::MAX)
1102        }))
1103    }
1104
1105    /// Refuses `intervals`, in milliseconds or else 1/1024 s, unless every message they fill
1106    /// can be written.
1107    pub(super) fn beats_fit(&mut self, intervals: &[u16], ms: bool) -> Result<(), Error> {
1108        self.st.act.started(self.st.act.now)?;
1109        if ms && intervals.contains(&u16::MAX) {
1110            return Err(Error::OutOfRange);
1111        }
1112        let count = self.st.act.beat_count.saturating_add(intervals.len());
1113        if let Some(more) = (count / HRV_BEATS).checked_sub(1) {
1114            let first = self.cost(&Hrv(&[0; HRV_BEATS]))?;
1115            let more = u32::try_from(more).unwrap_or(u32::MAX).saturating_mul(first.body);
1116            self.room(first.size().saturating_add(more))?;
1117        }
1118        Ok(())
1119    }
1120
1121    /// Keeps `intervals`, which [`Writer::beats_fit`] allowed, writing each five as they fill.
1122    fn beats(&mut self, intervals: impl Iterator<Item = u16>) -> Result<(), Error> {
1123        for ms in intervals {
1124            let act = &mut self.st.act;
1125            if let Some(slot) = act.beats.get_mut(act.beat_count) {
1126                *slot = ms;
1127                act.beat_count = act.beat_count.saturating_add(1);
1128            }
1129            if act.beat_count == HRV_BEATS {
1130                self.write_beats()?;
1131            }
1132        }
1133        Ok(())
1134    }
1135
1136    /// The bytes the beat intervals not yet written take.
1137    fn beats_cost(&self) -> Result<u32, Error> {
1138        let act = &self.st.act;
1139        match act.beats.get(..act.beat_count).filter(|b| !b.is_empty()) {
1140            Some(beats) => Ok(self.cost(&Hrv(beats))?.size()),
1141            None => Ok(0),
1142        }
1143    }
1144
1145    /// Writes the beat intervals not yet written.
1146    fn write_beats(&mut self) -> Result<(), Error> {
1147        let act = self.st.act;
1148        let Some(beats) = act.beats.get(..act.beat_count).filter(|b| !b.is_empty()) else {
1149            return Ok(());
1150        };
1151        self.fixed(&Hrv(beats), 0)?;
1152        self.st.act.beat_count = 0;
1153        Ok(())
1154    }
1155
1156    /// What ends the open session's rest at `t`, if it has one: an idle length or a rest set.
1157    fn rest_piece(&self, t: Timestamp) -> Result<Option<Piece>, Error> {
1158        let Some(session) = self.st.act.session.filter(|s| s.resting) else { return Ok(None) };
1159        let piece = if session.pool.is_some() {
1160            self.length_at(t, &session, None)?
1161        } else {
1162            self.set_at(t, &session, None)?
1163        };
1164        Ok(Some(piece))
1165    }
1166
1167    /// A length ending at `t`, swum or, without one, idle.
1168    fn length_at(
1169        &self,
1170        t: Timestamp,
1171        session: &OpenSession,
1172        swum: Option<Length>,
1173    ) -> Result<Piece, Error> {
1174        let pool = session.pool.ok_or(Error::OutOfOrder)?;
1175        let index = next_index(self.st.act.lengths, LENGTHS_MAX)?;
1176        let (start, since) = session.mark;
1177        let seconds = self.st.act.timer_at(t).saturating_sub(since);
1178        let cm = u32::from(pool.centimetres);
1179        let msg = LengthMsg {
1180            span: Span {
1181                start_time: start,
1182                timestamp: t,
1183                total_elapsed_ms: ms(t.fit().saturating_sub(start.fit())),
1184                total_timer_ms: ms(seconds),
1185            },
1186            swum,
1187            avg_speed: swum
1188                .and_then(|_| per(cm.saturating_mul(10), seconds))
1189                .and_then(|v| u16::try_from(v).ok())
1190                .filter(|&v| v != u16::MAX),
1191            cadence: swum
1192                .and_then(|l| per(u32::from(l.strokes?).saturating_mul(60), seconds))
1193                .and_then(|v| u8::try_from(v).ok())
1194                .filter(|&v| v != u8::MAX),
1195        };
1196        check(&msg)?;
1197        let distance = match swum {
1198            Some(_) => self.st.act.distance.checked_add(cm).filter(|&d| d <= DISTANCE_CM_MAX),
1199            None => Some(self.st.act.distance),
1200        };
1201        let distance = distance.ok_or(Error::OutOfRange)?;
1202        self.endable(t, self.st.laps, self.st.sessions)?;
1203        Ok(Piece::Length { msg, index, distance, pool })
1204    }
1205
1206    /// A set ending at `t`, or without one, a rest.
1207    fn set_at(
1208        &self,
1209        t: Timestamp,
1210        session: &OpenSession,
1211        set: Option<Set>,
1212    ) -> Result<Piece, Error> {
1213        let index = next_index(self.st.act.sets, SETS_MAX)?;
1214        let (start, since) = session.mark;
1215        let msg = SetMsg {
1216            start_time: start,
1217            timestamp: t,
1218            duration_ms: ms(self.st.act.timer_at(t).saturating_sub(since)),
1219            set,
1220        };
1221        check(&msg)?;
1222        self.endable(t, self.st.laps, self.st.sessions)?;
1223        Ok(Piece::Set { msg, index })
1224    }
1225
1226    /// Writes a length or set ending at `t`, which ends any rest.
1227    fn put_piece(&mut self, t: Timestamp, piece: Piece) -> Result<(), Error> {
1228        let timer = self.st.act.timer_at(t);
1229        match piece {
1230            Piece::Length { msg, index, distance, .. } => {
1231                self.fixed(&msg, index)?;
1232                let act = &mut self.st.act;
1233                (act.lengths, act.now, act.distance) = (index.saturating_add(1), t, distance);
1234                if let Some(s) = act.session.as_mut() {
1235                    piece.add_to(s);
1236                }
1237            }
1238            Piece::Set { msg, index } => {
1239                self.fixed(&msg, index)?;
1240                let act = &mut self.st.act;
1241                (act.sets, act.now) = (index.saturating_add(1), t);
1242                if let (Some(s), Some(set)) = (act.session.as_mut(), &msg.set) {
1243                    s.span.seen.add_repetitions(set);
1244                }
1245            }
1246        }
1247        if let Some(s) = self.st.act.session.as_mut() {
1248            (s.mark, s.resting) = ((t, timer), false);
1249        }
1250        Ok(())
1251    }
1252
1253    /// Ends the activity at `t`: the timer stops, and the last lap, the last session and the
1254    /// activity are written.
1255    ///
1256    /// # Errors
1257    ///
1258    /// [`Error::OutOfOrder`] if no session has started; see [`Error`].
1259    pub fn end(&mut self, t: Timestamp) -> Result<(), Error> {
1260        self.st.act.started(t)?;
1261        if self.st.act.session.is_none() {
1262            return Err(Error::OutOfOrder);
1263        }
1264        self.endable(t, self.st.laps, self.st.sessions)?;
1265        let rest = self.rest_piece(t)?;
1266        let timer = self.st.act.timer_at(t);
1267        let activity = self.activity(t);
1268        self.ahead(END)?;
1269        self.st.act.phase = Phase::Ending;
1270        if let Some(piece) = rest {
1271            self.put_piece(t, piece)?;
1272        }
1273        self.write_beats()?;
1274        self.raw_event(Event::timer_stop_all(t))?;
1275        self.close_session(t, trigger::ACTIVITY_END)?;
1276        self.raw_activity(&activity)?;
1277        let act = &mut self.st.act;
1278        (act.timer, act.since, act.running, act.now, act.phase) =
1279            (timer, t, false, t, Phase::Ended);
1280        Ok(())
1281    }
1282
1283    /// The open session's last lap and the session itself as they would end at `t`.
1284    fn closing(&self, t: Timestamp, trigger: u8) -> Option<(Lap, Session)> {
1285        let s = self.st.act.session?;
1286        let timer = self.st.act.timer_at(t);
1287        let lap = lap_message(&s.lap, t, timer, &s).trigger(lap_trigger::SESSION_END);
1288        let elapsed = t.fit().saturating_sub(s.span.start.fit());
1289        let laps = self.st.laps.saturating_add(1).saturating_sub(s.first_lap);
1290        let running = timer.saturating_sub(s.span.timer);
1291        let mut totals = s.span.seen.totals(running);
1292        if s.takes_sets() {
1293            totals.cycles = s.span.seen.repetitions;
1294        }
1295        let mut session = Session::new(s.span.start, t, ms(elapsed), ms(running))
1296            .sport(s.sport, s.sub_sport)
1297            .laps(s.first_lap, laps)
1298            .totals(totals)
1299            .trigger(trigger);
1300        if let Some(pool) = s.pool {
1301            session = session.pool(pool);
1302        }
1303        if let (Some(avg), Some(max)) = s.span.seen.heart_rate.summary_u8() {
1304            session = session.heart_rate(avg, max);
1305        }
1306        Some((lap, session))
1307    }
1308
1309    /// The activity message as it would end at `t`.
1310    fn activity(&self, t: Timestamp) -> Activity {
1311        let timer = ms(self.st.act.timer_at(t));
1312        let activity = Activity::new(t, timer)
1313            .sessions(self.st.sessions.saturating_add(1))
1314            .auto_multisport(self.st.options.auto_multisport);
1315        match self.st.options.utc_offset {
1316            Some(offset) => activity.utc_offset(offset),
1317            None => activity,
1318        }
1319    }
1320
1321    /// Refuses a call after which, with `laps` laps and `sessions` sessions written, the
1322    /// activity could not end at `t`.
1323    pub(super) fn endable(&self, t: Timestamp, laps: u16, sessions: u16) -> Result<(), Error> {
1324        next_index(laps, LAPS_MAX)?;
1325        next_index(sessions, SESSIONS_MAX)?;
1326        check(&self.activity(t))?;
1327        if let Some((lap, session)) = self.closing(t, trigger::ACTIVITY_END) {
1328            check(&lap)?;
1329            check(&session)?;
1330        }
1331        Ok(())
1332    }
1333
1334    /// Ends the open session, if any, at `t`, by `trigger`.
1335    fn close_session(&mut self, t: Timestamp, trigger: u8) -> Result<(), Error> {
1336        let Some((lap, session)) = self.closing(t, trigger) else { return Ok(()) };
1337        check(&lap)?;
1338        check(&session)?;
1339        self.raw_lap(&lap)?;
1340        self.raw_session(&session)?;
1341        self.st.act.session = None;
1342        Ok(())
1343    }
1344}
1345
1346#[cfg(test)]
1347mod tests;