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
use std::sync::{Arc, Mutex};

use crate::{FrameData, FrameSinkId};

/// A view of recent and slowest frames, used by GUI:s.
#[derive(Clone)]
pub struct FrameView {
    /// newest first
    recent_frames: std::collections::VecDeque<Arc<FrameData>>,
    max_recent: usize,

    slowest_frames: std::collections::BinaryHeap<OrderedData>,
    max_slow: usize,
}

impl Default for FrameView {
    fn default() -> Self {
        let max_recent = 128;
        let max_slow = 128;

        Self {
            recent_frames: std::collections::VecDeque::with_capacity(max_recent),
            max_recent,
            slowest_frames: std::collections::BinaryHeap::with_capacity(max_slow),
            max_slow,
        }
    }
}

impl FrameView {
    pub fn add_frame(&mut self, new_frame: Arc<FrameData>) {
        let add_to_slowest = if self.slowest_frames.len() < self.max_slow {
            true
        } else if let Some(fastest_of_the_slow) = self.slowest_frames.peek() {
            new_frame.duration_ns() > fastest_of_the_slow.0.duration_ns()
        } else {
            false
        };

        if add_to_slowest {
            self.slowest_frames.push(OrderedData(new_frame.clone()));
            while self.slowest_frames.len() > self.max_slow {
                self.slowest_frames.pop();
            }
        }

        if let Some(last) = self.recent_frames.back() {
            if new_frame.frame_index != last.frame_index + 1 {
                // Keep `recent_frames` consecutive.
                // Important when loading .puffin files which has both
                // the slowest frames and most recent frames in the same stream.
                self.recent_frames.clear();
            }
        }

        self.recent_frames.push_back(new_frame);
        while self.recent_frames.len() > self.max_recent {
            self.recent_frames.pop_front();
        }
    }

    /// The latest fully captured frame of data.
    pub fn latest_frame(&self) -> Option<Arc<FrameData>> {
        self.recent_frames.back().cloned()
    }

    /// Oldest first
    pub fn recent_frames(&self) -> impl Iterator<Item = &Arc<FrameData>> {
        self.recent_frames.iter()
    }

    /// The slowest frames so far (or since last call to [`Self::clear_slowest`])
    /// in chronological order.
    pub fn slowest_frames_chronological(&self) -> Vec<Arc<FrameData>> {
        let mut frames: Vec<_> = self.slowest_frames.iter().map(|f| f.0.clone()).collect();
        frames.sort_by_key(|frame| frame.frame_index);
        frames
    }

    /// Clean history of the slowest frames.
    pub fn clear_slowest(&mut self) {
        self.slowest_frames.clear();
    }

    /// How many frames of recent history to store.
    pub fn max_recent(&self) -> usize {
        self.max_recent
    }

    /// How many frames of recent history to store.
    pub fn set_max_history(&mut self, max_recent: usize) {
        self.max_recent = max_recent;
    }

    /// How many slow "spike" frames to store.
    pub fn max_slow(&self) -> usize {
        self.max_slow
    }

    /// How many slow "spike" frames to store.
    pub fn set_max_slow(&mut self, max_slow: usize) {
        self.max_slow = max_slow;
    }

    /// Export profile data as a `.puffin` file.
    #[cfg(feature = "serialization")]
    pub fn save_to_path(&self, path: &std::path::Path) -> anyhow::Result<()> {
        let mut file = std::fs::File::create(path)?;
        self.save_to_writer(&mut file)
    }

    /// Export profile data as a `.puffin` file.
    #[cfg(feature = "serialization")]
    pub fn save_to_writer(&self, write: &mut impl std::io::Write) -> anyhow::Result<()> {
        write.write_all(b"PUF0")?;

        let slowest_frames = self.slowest_frames.iter().map(|f| &f.0);
        let mut frames: Vec<_> = slowest_frames.chain(self.recent_frames.iter()).collect();
        frames.sort_by_key(|frame| frame.frame_index);
        frames.dedup_by_key(|frame| frame.frame_index);

        for frame in frames {
            frame.write_into(write)?;
        }
        Ok(())
    }

    /// Import profile data from a `.puffin` file.
    #[cfg(feature = "serialization")]
    pub fn load_path(path: &std::path::Path) -> anyhow::Result<Self> {
        let mut file = std::fs::File::open(path)?;
        Self::load_reader(&mut file)
    }

    /// Import profile data from a `.puffin` file.
    #[cfg(feature = "serialization")]
    pub fn load_reader(read: &mut impl std::io::Read) -> anyhow::Result<Self> {
        let mut magic = [0_u8; 4];
        read.read_exact(&mut magic)?;
        if &magic != b"PUF0" {
            anyhow::bail!("Expected .puffin magic header of 'PUF0', found {:?}", magic);
        }

        let mut slf = Self {
            max_recent: usize::MAX,
            ..Default::default()
        };
        while let Some(frame) = FrameData::read_next(read)? {
            slf.add_frame(frame.into());
        }

        Ok(slf)
    }
}

// ----------------------------------------------------------------------------

#[derive(Clone)]
struct OrderedData(Arc<FrameData>);

impl PartialEq for OrderedData {
    fn eq(&self, other: &Self) -> bool {
        self.0.duration_ns().eq(&other.0.duration_ns())
    }
}
impl Eq for OrderedData {}

impl PartialOrd for OrderedData {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for OrderedData {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.duration_ns().cmp(&other.0.duration_ns()).reverse()
    }
}

// ----------------------------------------------------------------------------

/// Automatically connects to [`crate::GlobalProfiler`].
pub struct GlobalFrameView {
    sink_id: FrameSinkId,
    view: Arc<Mutex<FrameView>>,
}

impl Default for GlobalFrameView {
    fn default() -> Self {
        let view = Arc::new(Mutex::new(FrameView::default()));
        let view_clone = view.clone();
        let sink_id = crate::GlobalProfiler::lock().add_sink(Box::new(move |frame| {
            view_clone.lock().unwrap().add_frame(frame);
        }));
        Self { sink_id, view }
    }
}

impl Drop for GlobalFrameView {
    fn drop(&mut self) {
        crate::GlobalProfiler::lock().remove_sink(self.sink_id);
    }
}

impl GlobalFrameView {
    /// View the latest profiling data.
    pub fn lock(&self) -> std::sync::MutexGuard<'_, FrameView> {
        self.view.lock().unwrap()
    }
}