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
use crate::ScopeDetails;
use crate::{Error, FrameIndex, NanoSecond, Result, StreamInfo, ThreadInfo};
#[cfg(feature = "packing")]
use parking_lot::RwLock;

use std::{collections::BTreeMap, sync::Arc};

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

/// The streams of profiling data for each thread.
pub type ThreadStreams = BTreeMap<ThreadInfo, Arc<StreamInfo>>;

/// Meta-information about a frame.
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Debug)]
pub struct FrameMeta {
    /// What frame this is (counting from 0 at application startup).
    pub frame_index: FrameIndex,

    /// The span we cover.
    pub range_ns: (NanoSecond, NanoSecond),

    /// The unpacked size of all streams.
    pub num_bytes: usize,

    /// Total number of scopes.
    pub num_scopes: usize,
}

/// One frame worth of profile data, collected from many sources.
///
/// More often encoded as a [`FrameData`].
pub struct UnpackedFrameData {
    /// Frame metadata.
    pub meta: FrameMeta,
    /// The streams of profiling data for each thread.
    pub thread_streams: ThreadStreams,
}

impl UnpackedFrameData {
    /// Create a new [`UnpackedFrameData`].
    pub fn new(
        frame_index: FrameIndex,
        thread_streams: BTreeMap<ThreadInfo, StreamInfo>,
    ) -> Result<Self> {
        let thread_streams: BTreeMap<_, _> = thread_streams
            .into_iter()
            .map(|(info, stream_info)| (info, Arc::new(stream_info)))
            .collect();

        let mut num_bytes = 0;
        let mut num_scopes = 0;

        let mut min_ns = NanoSecond::MAX;
        let mut max_ns = NanoSecond::MIN;
        for stream_info in thread_streams.values() {
            num_bytes += stream_info.stream.len();
            num_scopes += stream_info.num_scopes;
            min_ns = min_ns.min(stream_info.range_ns.0);
            max_ns = max_ns.max(stream_info.range_ns.1);
        }

        if min_ns <= max_ns {
            Ok(Self {
                meta: FrameMeta {
                    frame_index,
                    range_ns: (min_ns, max_ns),
                    num_bytes,
                    num_scopes,
                },
                thread_streams,
            })
        } else {
            Err(Error::Empty)
        }
    }

    /// The index of this frame.
    pub fn frame_index(&self) -> u64 {
        self.meta.frame_index
    }

    /// The range in nanoseconds of the entire profile frame.
    pub fn range_ns(&self) -> (NanoSecond, NanoSecond) {
        self.meta.range_ns
    }

    /// The duration in nanoseconds of the entire profile frame.
    pub fn duration_ns(&self) -> NanoSecond {
        let (min, max) = self.meta.range_ns;
        max - min
    }
}

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

/// One frame worth of profile data, collected from many sources.
///
/// If you turn on the the "packing" feature, this will compress the
/// profiling data in order to save RAM.
#[cfg(not(feature = "packing"))]
pub struct FrameData {
    unpacked_frame: Arc<UnpackedFrameData>,
    /// Scopes that were registered during this frame.
    pub scope_delta: Vec<Arc<ScopeDetails>>,
    /// Does [`Self::scope_delta`] contain all the scopes up to this point?
    /// If `false`, it just contains the new scopes since last frame data.
    pub full_delta: bool,
}

#[cfg(not(feature = "packing"))]
pub enum Never {}

#[cfg(not(feature = "packing"))]
impl FrameData {
    /// Create a new [`FrameData`].
    pub fn new(
        frame_index: FrameIndex,
        thread_streams: BTreeMap<ThreadInfo, StreamInfo>,
        scope_delta: Vec<Arc<ScopeDetails>>,
        full_delta: bool,
    ) -> Result<Self> {
        Ok(Self::from_unpacked(
            Arc::new(UnpackedFrameData::new(frame_index, thread_streams)?),
            scope_delta,
            full_delta,
        ))
    }

    fn from_unpacked(
        unpacked_frame: Arc<UnpackedFrameData>,
        scope_delta: Vec<Arc<ScopeDetails>>,
        full_delta: bool,
    ) -> Self {
        Self {
            unpacked_frame,
            scope_delta,
            full_delta,
        }
    }

    /// Returns meta data from this frame.
    #[inline]
    pub fn meta(&self) -> &FrameMeta {
        &self.unpacked_frame.meta
    }

    /// Always returns `None`.
    pub fn packed_size(&self) -> Option<usize> {
        None
    }

    /// Number of bytes used when unpacked.
    pub fn unpacked_size(&self) -> Option<usize> {
        Some(self.unpacked_frame.meta.num_bytes)
    }

    /// Bytes currently used by the unpacked data.
    pub fn bytes_of_ram_used(&self) -> usize {
        self.unpacked_frame.meta.num_bytes
    }

    /// Always returns `false`.
    pub fn has_packed(&self) -> bool {
        false
    }

    /// Always returns `true`.
    pub fn has_unpacked(&self) -> bool {
        true
    }

    /// Return the unpacked data.
    pub fn unpacked(&self) -> std::result::Result<Arc<UnpackedFrameData>, Never> {
        Ok(self.unpacked_frame.clone())
    }

    /// Does nothing because this [`FrameData`] is unpacked by default.
    pub fn pack(&self) {}
}

#[cfg(all(feature = "serialization", not(feature = "packing")))]
compile_error!(
    "If the puffin feature 'serialization' is one, the 'packing' feature must also be enabled!"
);

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

/// See <https://github.com/EmbarkStudios/puffin/pull/130> for pros-and-cons of different compression algorithms.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CompressionKind {
    #[allow(dead_code)] // with some feature sets
    Uncompressed = 0,

    /// Very fast, and lightweight dependency
    #[allow(dead_code)] // with some feature sets
    Lz4 = 1,

    /// Big dependency, slow compression, but compresses better than lz4
    #[allow(dead_code)] // with some feature sets
    Zstd = 2,
}

impl CompressionKind {
    #[cfg(feature = "serialization")]
    fn from_u8(value: u8) -> anyhow::Result<Self> {
        match value {
            0 => Ok(Self::Uncompressed),
            1 => Ok(Self::Lz4),
            2 => Ok(Self::Zstd),
            _ => Err(anyhow::anyhow!("Unknown compression kind: {value}")),
        }
    }
}

/// Packed with bincode and compressed.
#[cfg(feature = "packing")]
struct PackedStreams {
    compression_kind: CompressionKind,
    bytes: Vec<u8>,
}

#[cfg(feature = "packing")]
impl PackedStreams {
    pub fn new(compression_kind: CompressionKind, bytes: Vec<u8>) -> Self {
        Self {
            compression_kind,
            bytes,
        }
    }

    pub fn pack(streams: &ThreadStreams) -> Self {
        use bincode::Options as _;

        let serialized = bincode::options()
            .serialize(streams)
            .expect("bincode failed to encode");

        cfg_if::cfg_if! {
            if #[cfg(feature = "lz4")] {
                Self {
                    compression_kind: CompressionKind::Lz4,
                    bytes: lz4_flex::compress_prepend_size(&serialized),
                }
            } else if #[cfg(feature = "zstd")] {
                let level = 3;
                let bytes = zstd::encode_all(std::io::Cursor::new(&serialized), level)
                    .expect("zstd failed to compress");
                Self {
                    compression_kind: CompressionKind::Zstd,
                    bytes,
                }
            } else {
                Self {
                    compression_kind: CompressionKind::Uncompressed,
                    bytes: serialized,
                }
            }
        }
    }

    pub fn num_bytes(&self) -> usize {
        self.bytes.len()
    }

    pub fn unpack(&self) -> anyhow::Result<ThreadStreams> {
        crate::profile_function!();

        use anyhow::Context as _;
        use bincode::Options as _;

        fn deserialize(bytes: &[u8]) -> anyhow::Result<ThreadStreams> {
            crate::profile_scope!("bincode deserialize");
            bincode::options()
                .deserialize(bytes)
                .context("bincode deserialize")
        }

        match self.compression_kind {
            CompressionKind::Uncompressed => deserialize(&self.bytes),

            CompressionKind::Lz4 => {
                cfg_if::cfg_if! {
                    if #[cfg(feature = "lz4")] {
                        let compressed = lz4_flex::decompress_size_prepended(&self.bytes)
                            .map_err(|err| anyhow::anyhow!("lz4: {err}"))?;
                        deserialize(&compressed)
                    } else {
                        anyhow::bail!("Data compressed with lz4, but the lz4 feature is not enabled")
                    }
                }
            }

            CompressionKind::Zstd => {
                cfg_if::cfg_if! {
                    if #[cfg(feature = "zstd")] {
                        deserialize(&decode_zstd(&self.bytes)?)
                    } else {
                        anyhow::bail!("Data compressed with zstd, but the zstd feature is not enabled")
                    }
                }
            }
        }
    }
}

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

/// One frame worth of profile data, collected from many sources.
///
/// If you turn on the "packing" feature, then [`FrameData`] has interior mutability with double storage:
/// * Unpacked data ([`UnpackedFrameData`])
/// * Packed (compressed) data
///
/// One or both are always stored.
/// This allows RAM-efficient storage and viewing of many frames of profiling data.
/// Packing and unpacking is done lazily, on-demand.
#[cfg(feature = "packing")]
pub struct FrameData {
    meta: FrameMeta,
    /// * [`None`] if still compressed.
    /// * `Some(Err(…))` if there was a problem during unpacking.
    /// * `Some(Ok(…))` if unpacked.
    unpacked_frame: RwLock<Option<anyhow::Result<Arc<UnpackedFrameData>>>>,

    /// [`UnpackedFrameData::thread_streams`], compressed.
    /// [`None`] if not yet compressed.
    packed_streams: RwLock<Option<PackedStreams>>,

    /// Scopes that were registered during this frame.
    pub scope_delta: Vec<Arc<ScopeDetails>>,

    /// Does [`Self::scope_delta`] contain all the scopes up to this point?
    /// If `false`, it just contains the new scopes since last frame data.
    pub full_delta: bool,
}

#[cfg(feature = "packing")]
impl FrameData {
    /// Create a new [`FrameData`].
    pub fn new(
        frame_index: FrameIndex,
        thread_streams: BTreeMap<ThreadInfo, StreamInfo>,
        scope_delta: Vec<Arc<ScopeDetails>>,
        full_delta: bool,
    ) -> Result<Self> {
        Ok(Self::from_unpacked(
            Arc::new(UnpackedFrameData::new(frame_index, thread_streams)?),
            scope_delta,
            full_delta,
        ))
    }

    fn from_unpacked(
        unpacked_frame: Arc<UnpackedFrameData>,
        scope_delta: Vec<Arc<ScopeDetails>>,
        full_delta: bool,
    ) -> Self {
        Self {
            meta: unpacked_frame.meta.clone(),
            unpacked_frame: RwLock::new(Some(Ok(unpacked_frame))),
            packed_streams: RwLock::new(None),
            scope_delta,
            full_delta,
        }
    }

    /// Returns meta data from this frame.
    #[inline]
    pub fn meta(&self) -> &FrameMeta {
        &self.meta
    }

    /// Number of bytes used by the packed data, if packed.
    pub fn packed_size(&self) -> Option<usize> {
        self.packed_streams.read().as_ref().map(|c| c.num_bytes())
    }

    /// Number of bytes used when unpacked, if known.
    pub fn unpacked_size(&self) -> Option<usize> {
        if self.has_unpacked() {
            Some(self.meta.num_bytes)
        } else {
            None
        }
    }

    /// bytes currently used by the unpacked and packed data.
    pub fn bytes_of_ram_used(&self) -> usize {
        self.unpacked_size().unwrap_or(0) + self.packed_size().unwrap_or(0)
    }

    /// Do we have a packed version stored internally?
    pub fn has_packed(&self) -> bool {
        self.packed_streams.read().is_some()
    }

    /// Do we have a unpacked version stored internally?
    pub fn has_unpacked(&self) -> bool {
        self.unpacked_frame.read().is_some()
    }

    /// Return the unpacked data.
    ///
    /// This will lazily unpack if needed (and only once).
    ///
    /// Returns `Err` if failing to decode the packed data.
    pub fn unpacked(&self) -> anyhow::Result<Arc<UnpackedFrameData>> {
        fn unpack_frame_data(
            meta: FrameMeta,
            packed: &PackedStreams,
        ) -> anyhow::Result<UnpackedFrameData> {
            Ok(UnpackedFrameData {
                meta,
                thread_streams: packed.unpack()?,
            })
        }

        let has_unpacked = self.unpacked_frame.read().is_some();
        if !has_unpacked {
            crate::profile_scope!("unpack_puffin_frame");
            let packed_lock = self.packed_streams.read();
            let packed = packed_lock
                .as_ref()
                .expect("FrameData is neither packed or unpacked");

            let frame_data_result = unpack_frame_data(self.meta.clone(), packed);
            let frame_data_result = frame_data_result.map(Arc::new);
            *self.unpacked_frame.write() = Some(frame_data_result);
        }

        match self.unpacked_frame.read().as_ref().unwrap() {
            Ok(frame) => Ok(frame.clone()),
            Err(err) => Err(anyhow::format_err!("{}", err)), // can't clone `anyhow::Error`
        }
    }

    /// Make the [`FrameData`] use up less memory.
    /// Idempotent.
    pub fn pack(&self) {
        self.create_packed();
        *self.unpacked_frame.write() = None;
    }

    /// Create a packed storage without freeing the unpacked storage.
    fn create_packed(&self) {
        let has_packed = self.packed_streams.read().is_some();
        if !has_packed {
            // crate::profile_scope!("pack_puffin_frame"); // we get called from `GlobalProfiler::new_frame`, so avoid recursiveness!
            let unpacked_frame = self
                .unpacked_frame
                .read()
                .as_ref()
                .expect("We should have an unpacked frame if we don't have a packed one")
                .as_ref()
                .expect("The unpacked frame should be error free, since it doesn't come from packed source")
                .clone();

            let packed = PackedStreams::pack(&unpacked_frame.thread_streams);

            *self.packed_streams.write() = Some(packed);
        }
    }

    /// Writes one [`FrameData`] into a stream, prefixed by its length ([`u32`] le).
    #[cfg(not(target_arch = "wasm32"))] // compression not supported on wasm
    #[cfg(feature = "serialization")]
    pub fn write_into(
        &self,
        scope_collection: &crate::ScopeCollection,
        send_all_scopes: bool,
        write: &mut impl std::io::Write,
    ) -> anyhow::Result<()> {
        use bincode::Options as _;
        use byteorder::{WriteBytesExt as _, LE};

        let meta_serialized = bincode::options().serialize(&self.meta)?;

        write.write_all(b"PFD4")?;
        write.write_all(&(meta_serialized.len() as u32).to_le_bytes())?;
        write.write_all(&meta_serialized)?;

        self.create_packed();
        let packed_streams_lock = self.packed_streams.read();
        let packed_streams = packed_streams_lock.as_ref().unwrap(); // We just called create_packed

        write.write_all(&(packed_streams.num_bytes() as u32).to_le_bytes())?;
        write.write_u8(packed_streams.compression_kind as u8)?;
        write.write_all(&packed_streams.bytes)?;

        let to_serialize_scopes: Vec<_> = if send_all_scopes {
            scope_collection.scopes_by_id().values().cloned().collect()
        } else {
            self.scope_delta.clone()
        };

        let serialized_scopes = bincode::options().serialize(&to_serialize_scopes)?;
        write.write_u32::<LE>(serialized_scopes.len() as u32)?;
        write.write_all(&serialized_scopes)?;
        Ok(())
    }

    /// Read the next [`FrameData`] from a stream.
    ///
    /// [`None`] is returned if the end of the stream is reached (EOF),
    /// or an end-of-stream sentinel of `0u32` is read.
    #[cfg(feature = "serialization")]
    pub fn read_next(read: &mut impl std::io::Read) -> anyhow::Result<Option<Self>> {
        use anyhow::Context as _;
        use bincode::Options as _;
        use byteorder::{ReadBytesExt, LE};

        let mut header = [0_u8; 4];
        if let Err(err) = read.read_exact(&mut header) {
            if err.kind() == std::io::ErrorKind::UnexpectedEof {
                return Ok(None);
            } else {
                return Err(err.into());
            }
        }

        #[derive(Clone, serde::Deserialize, serde::Serialize)]
        pub struct LegacyFrameData {
            pub frame_index: FrameIndex,
            pub thread_streams: ThreadStreams,
            pub range_ns: (NanoSecond, NanoSecond),
            pub num_bytes: usize,
            pub num_scopes: usize,
        }

        impl LegacyFrameData {
            fn into_unpacked_frame_data(self) -> UnpackedFrameData {
                let Self {
                    frame_index,
                    thread_streams,
                    range_ns,
                    num_bytes,
                    num_scopes,
                } = self;
                UnpackedFrameData {
                    meta: FrameMeta {
                        frame_index,
                        range_ns,
                        num_bytes,
                        num_scopes,
                    },
                    thread_streams,
                }
            }

            fn into_frame_data(self) -> FrameData {
                FrameData::from_unpacked(
                    Arc::new(self.into_unpacked_frame_data()),
                    Default::default(),
                    false,
                )
            }
        }

        if header == [0_u8; 4] {
            Ok(None) // end-of-stream sentinel.
        } else if header.starts_with(b"PFD") {
            if &header == b"PFD0" {
                // Like PDF1, but compressed with `lz4_flex`.
                // We stopped supporting this in 2021-11-16 in order to remove `lz4_flex` dependency.
                anyhow::bail!("Found legacy puffin data, which we can no longer decode")
            } else if &header == b"PFD1" {
                #[cfg(feature = "zstd")]
                {
                    // Added 2021-09
                    let mut compressed_length = [0_u8; 4];
                    read.read_exact(&mut compressed_length)?;
                    let compressed_length = u32::from_le_bytes(compressed_length) as usize;
                    let mut compressed = vec![0_u8; compressed_length];
                    read.read_exact(&mut compressed)?;

                    let serialized = decode_zstd(&compressed[..])?;

                    let legacy: LegacyFrameData = bincode::options()
                        .deserialize(&serialized)
                        .context("bincode deserialize")?;
                    Ok(Some(legacy.into_frame_data()))
                }
                #[cfg(not(feature = "zstd"))]
                {
                    anyhow::bail!("Cannot decode old puffin data without the `zstd` feature")
                }
            } else if &header == b"PFD2" {
                // Added 2021-11-15
                let mut meta_length = [0_u8; 4];
                read.read_exact(&mut meta_length)?;
                let meta_length = u32::from_le_bytes(meta_length) as usize;
                let mut meta = vec![0_u8; meta_length];
                read.read_exact(&mut meta)?;

                let meta: FrameMeta = bincode::options()
                    .deserialize(&meta)
                    .context("bincode deserialize")?;

                let mut streams_compressed_length = [0_u8; 4];
                read.read_exact(&mut streams_compressed_length)?;
                let streams_compressed_length =
                    u32::from_le_bytes(streams_compressed_length) as usize;
                let compression_kind = CompressionKind::Zstd;
                let mut streams_compressed = vec![0_u8; streams_compressed_length];
                read.read_exact(&mut streams_compressed)?;

                let packed_streams = PackedStreams::new(compression_kind, streams_compressed);

                // Don't unpack now - do it if/when needed!

                Ok(Some(Self {
                    meta,
                    unpacked_frame: RwLock::new(None),
                    packed_streams: RwLock::new(Some(packed_streams)),
                    scope_delta: Default::default(),
                    full_delta: false,
                }))
            } else if &header == b"PFD3" {
                // Added 2023-05-13: CompressionKind field
                let mut meta_length = [0_u8; 4];
                read.read_exact(&mut meta_length)?;
                let meta_length = u32::from_le_bytes(meta_length) as usize;
                let mut meta = vec![0_u8; meta_length];
                read.read_exact(&mut meta)?;

                let meta: FrameMeta = bincode::options()
                    .deserialize(&meta)
                    .context("bincode deserialize")?;

                let mut streams_compressed_length = [0_u8; 4];
                read.read_exact(&mut streams_compressed_length)?;
                let streams_compressed_length =
                    u32::from_le_bytes(streams_compressed_length) as usize;
                let compression_kind = read.read_u8()?;
                let compression_kind = CompressionKind::from_u8(compression_kind)?;
                let mut streams_compressed = vec![0_u8; streams_compressed_length];
                read.read_exact(&mut streams_compressed)?;

                let packed_streams = PackedStreams::new(compression_kind, streams_compressed);

                // Don't unpack now - do it if/when needed!

                Ok(Some(Self {
                    meta,
                    unpacked_frame: RwLock::new(None),
                    packed_streams: RwLock::new(Some(packed_streams)),
                    scope_delta: Default::default(),
                    full_delta: false,
                }))
            } else if &header == b"PFD4" {
                // Added 2024-01-08: Split up stream scope details from the record stream.
                let meta_length = read.read_u32::<LE>()? as usize;
                let meta = {
                    let mut meta = vec![0_u8; meta_length];
                    read.read_exact(&mut meta)?;
                    bincode::options()
                        .deserialize(&meta)
                        .context("bincode deserialize")?
                };

                let streams_compressed_length = read.read_u32::<LE>()? as usize;
                let compression_kind = CompressionKind::from_u8(read.read_u8()?)?;
                let streams_compressed = {
                    let mut streams_compressed = vec![0_u8; streams_compressed_length];
                    read.read_exact(&mut streams_compressed)?;
                    PackedStreams::new(compression_kind, streams_compressed)
                };

                let serialized_scope_len = read.read_u32::<LE>()?;
                let deserialized_scopes: Vec<crate::ScopeDetails> = {
                    let mut serialized_scopes = vec![0; serialized_scope_len as usize];
                    read.read_exact(&mut serialized_scopes)?;
                    bincode::options()
                        .deserialize_from(serialized_scopes.as_slice())
                        .context("Can not deserialize scope details")?
                };

                let new_scopes: Vec<_> = deserialized_scopes
                    .into_iter()
                    .map(|x| Arc::new(x.clone()))
                    .collect();

                Ok(Some(Self {
                    meta,
                    unpacked_frame: RwLock::new(None),
                    packed_streams: RwLock::new(Some(streams_compressed)),
                    scope_delta: new_scopes,
                    full_delta: false,
                }))
            } else {
                anyhow::bail!("Failed to decode: this data is newer than this reader. Please update your puffin version!");
            }
        } else {
            // Very old packet without magic header
            let mut bytes = vec![0_u8; u32::from_le_bytes(header) as usize];
            read.read_exact(&mut bytes)?;

            use bincode::Options as _;
            let legacy: LegacyFrameData = bincode::options()
                .deserialize(&bytes)
                .context("bincode deserialize")?;
            Ok(Some(legacy.into_frame_data()))
        }
    }
}

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

impl FrameData {
    /// The index of this frame.
    pub fn frame_index(&self) -> u64 {
        self.meta().frame_index
    }

    /// The range in nanoseconds of the entire profile frame.
    pub fn range_ns(&self) -> (NanoSecond, NanoSecond) {
        self.meta().range_ns
    }

    /// The duration in nanoseconds of the entire profile frame.
    pub fn duration_ns(&self) -> NanoSecond {
        let (min, max) = self.meta().range_ns;
        max - min
    }
}

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

#[cfg(feature = "packing")]
#[cfg(not(target_arch = "wasm32"))]
#[cfg(feature = "zstd")]
fn decode_zstd(bytes: &[u8]) -> anyhow::Result<Vec<u8>> {
    use anyhow::Context as _;
    zstd::decode_all(bytes).context("zstd decompress failed")
}

#[cfg(feature = "packing")]
#[cfg(target_arch = "wasm32")]
#[cfg(feature = "zstd")]
fn decode_zstd(mut bytes: &[u8]) -> anyhow::Result<Vec<u8>> {
    use anyhow::Context as _;
    use std::io::Read as _;
    let mut decoded = Vec::new();
    let mut decoder = ruzstd::StreamingDecoder::new(&mut bytes)
        .map_err(|err| anyhow::format_err!("zstd decompress: {}", err))?;
    decoder
        .read_to_end(&mut decoded)
        .context("zstd decompress")?;
    Ok(decoded)
}