File size: 27,647 Bytes
b450976
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import Foundation

public struct StreamVideoConfig {
    public let width: Int?
    public let height: Int?
    public let bitrate: Int?
    public let minBitrateBps: Int?
    public let initialBitrateBps: Int?
    public let fps: Int?
    /// WHIP adaptation policy; nil preserves the glasses' MAINTAIN_FRAMERATE default.
    public let degradationPreference: String?

    public init(
        width: Int? = nil,
        height: Int? = nil,
        bitrate: Int? = nil,
        fps: Int? = nil,
        minBitrateBps: Int? = nil,
        initialBitrateBps: Int? = nil,
        degradationPreference: String? = nil
    ) {
        self.width = width
        self.height = height
        self.bitrate = bitrate
        self.minBitrateBps = minBitrateBps
        self.initialBitrateBps = initialBitrateBps
        self.fps = fps
        self.degradationPreference = degradationPreference
    }

    var dictionary: [String: Any] {
        var values: [String: Any] = [:]
        if let width { values["width"] = width }
        if let height { values["height"] = height }
        if let bitrate { values["bitrate"] = bitrate }
        if let minBitrateBps { values["minBitrateBps"] = minBitrateBps }
        if let initialBitrateBps { values["initialBitrateBps"] = initialBitrateBps }
        if let degradationPreference { values["degradationPreference"] = degradationPreference }
        // ASG stream parsers shipped with the BLE key named "frameRate".
        if let fps { values["frameRate"] = fps }
        return values
    }

    init?(values: [String: Any]?) {
        guard let values else { return nil }
        self.init(
            width: intValue(values["width"]),
            height: intValue(values["height"]),
            bitrate: intValue(values["bitrate"]),
            fps: intValue(values["fps"]),
            minBitrateBps: intValue(values["minBitrateBps"]),
            initialBitrateBps: intValue(values["initialBitrateBps"]),
            degradationPreference: stringValue(values, "degradationPreference", "dp")
        )
    }
}

public struct StreamAudioConfig {
    public let bitrate: Int?
    public let sampleRate: Int?
    public let echoCancellation: Bool?
    public let noiseSuppression: Bool?

    public init(
        bitrate: Int? = nil,
        sampleRate: Int? = nil,
        echoCancellation: Bool? = nil,
        noiseSuppression: Bool? = nil
    ) {
        self.bitrate = bitrate
        self.sampleRate = sampleRate
        self.echoCancellation = echoCancellation
        self.noiseSuppression = noiseSuppression
    }

    var dictionary: [String: Any] {
        var values: [String: Any] = [:]
        if let bitrate { values["bitrate"] = bitrate }
        if let sampleRate { values["sampleRate"] = sampleRate }
        if let echoCancellation { values["echoCancellation"] = echoCancellation }
        if let noiseSuppression { values["noiseSuppression"] = noiseSuppression }
        return values
    }

    init?(values: [String: Any]?) {
        guard let values else { return nil }
        self.init(
            bitrate: intValue(values["bitrate"]),
            sampleRate: intValue(values["sampleRate"]),
            echoCancellation: values["echoCancellation"] as? Bool,
            noiseSuppression: values["noiseSuppression"] as? Bool
        )
    }
}

/// ICE overrides for a WHIP stream. Ignored by the RTMP and SRT paths.
public struct StreamIceConfig {
    /// STUN server the glasses use while gathering candidates.
    ///
    /// `nil` and empty are different answers, and both have to survive the BLE round trip. `nil`
    /// leaves the glasses on their default Cloudflare STUN server; an empty string is an explicit
    /// request for host-only gathering, which is what a WHIP server on the glasses' own hotspot
    /// needs, since a reflexive candidate there is meaningless and unreachable.
    public let stun: String?

    public init(stun: String? = nil) {
        self.stun = stun
    }

    var dictionary: [String: Any] {
        var values: [String: Any] = [:]
        // Not filtered on emptiness, unlike the other optional string fields here: "" is the
        // host-only signal, so dropping it would silently restore the default STUN server.
        if let stun { values["stun"] = stun }
        return values
    }

    init?(values: [String: Any]?) {
        guard let values else { return nil }
        self.init(stun: values["stun"] as? String ?? values["s"] as? String)
    }
}

/// Effective video settings reported by the glasses after defaults and clamps.
public struct StreamResolvedVideoConfig: Equatable {
    /// Encoded output width sent to the stream endpoint.
    public let width: Int
    /// Encoded output height sent to the stream endpoint.
    public let height: Int
    /// Native camera buffer width selected before crop/downscale.
    public let captureWidth: Int?
    /// Native camera buffer height selected before crop/downscale.
    public let captureHeight: Int?
    /// Encoded video bitrate in bits per second.
    public let bitrate: Int
    /// Resolved capture/encode frame rate.
    public let fps: Double
    /// Applied WHIP adaptation policy; absent on older firmware and other transports.
    public let degradationPreference: String?

    public init(
        width: Int,
        height: Int,
        captureWidth: Int? = nil,
        captureHeight: Int? = nil,
        bitrate: Int,
        fps: Double,
        degradationPreference: String? = nil
    ) {
        self.width = width
        self.height = height
        self.captureWidth = captureWidth
        self.captureHeight = captureHeight
        self.bitrate = bitrate
        self.fps = fps
        self.degradationPreference = degradationPreference
    }

    init?(values: [String: Any]?) {
        guard let values,
              let width = intValue(values["width"]),
              let height = intValue(values["height"]),
              let bitrate = intValue(values["bitrate"]),
              let fps = doubleValue(values["fps"])
        else {
            return nil
        }
        self.init(
            width: width,
            height: height,
            captureWidth: intValue(values["captureWidth"]),
            captureHeight: intValue(values["captureHeight"]),
            bitrate: bitrate,
            fps: fps,
            degradationPreference: stringValue(values, "degradationPreference", "dp")
        )
    }

    var values: [String: Any] {
        var values: [String: Any] = [
            "width": width,
            "height": height,
            "bitrate": bitrate,
            "fps": fps,
        ]
        if let captureWidth { values["captureWidth"] = captureWidth }
        if let captureHeight { values["captureHeight"] = captureHeight }
        if let degradationPreference { values["degradationPreference"] = degradationPreference }
        return values
    }
}

public struct StreamResolvedAudioConfig: Equatable {
    public let bitrate: Int?
    public let sampleRate: Int?
    public let echoCancellation: Bool?
    public let noiseSuppression: Bool?

    public init(
        bitrate: Int? = nil,
        sampleRate: Int? = nil,
        echoCancellation: Bool? = nil,
        noiseSuppression: Bool? = nil
    ) {
        self.bitrate = bitrate
        self.sampleRate = sampleRate
        self.echoCancellation = echoCancellation
        self.noiseSuppression = noiseSuppression
    }

    init?(values: [String: Any]?) {
        guard let values else { return nil }
        self.init(
            bitrate: intValue(values["bitrate"]),
            sampleRate: intValue(values["sampleRate"]),
            echoCancellation: boolValue(values, "echoCancellation"),
            noiseSuppression: boolValue(values, "noiseSuppression")
        )
    }

    var values: [String: Any] {
        var values: [String: Any] = [:]
        if let bitrate { values["bitrate"] = bitrate }
        if let sampleRate { values["sampleRate"] = sampleRate }
        if let echoCancellation { values["echoCancellation"] = echoCancellation }
        if let noiseSuppression { values["noiseSuppression"] = noiseSuppression }
        return values
    }
}

public enum StreamTransport: String, Equatable {
    case rtmp
    case srt
    case whip
}

public struct StreamResolvedConfig: Equatable {
    public let transport: StreamTransport?
    public let video: StreamResolvedVideoConfig?
    public let audio: StreamResolvedAudioConfig?

    public init(
        transport: StreamTransport? = nil,
        video: StreamResolvedVideoConfig? = nil,
        audio: StreamResolvedAudioConfig? = nil
    ) {
        self.transport = transport
        self.video = video
        self.audio = audio
    }

    init?(values: [String: Any]?) {
        guard let values else { return nil }
        self.init(
            transport: stringValue(values, "transport").flatMap(StreamTransport.init(rawValue:)),
            video: StreamResolvedVideoConfig(values: values["video"] as? [String: Any]),
            audio: StreamResolvedAudioConfig(values: values["audio"] as? [String: Any])
        )
    }

    var values: [String: Any] {
        var values: [String: Any] = [:]
        if let transport { values["transport"] = transport.rawValue }
        if let video { values["video"] = video.values }
        if let audio { values["audio"] = audio.values }
        return values
    }
}

private func streamInt64Value(_ value: Any?) -> Int64? {
    if let int64 = value as? Int64 { return int64 }
    if let int = value as? Int { return Int64(int) }
    if let number = value as? NSNumber { return number.int64Value }
    return nil
}

/// Live encoder and device telemetry reported by the glasses while streaming.
public struct StreamLiveStats: Equatable {
    public let bitrate: Int64?
    public let fps: Double?
    public let droppedFrames: Int64?
    public let duration: Int64?
    public let temperatureC: Double?

    public init(
        bitrate: Int64? = nil,
        fps: Double? = nil,
        droppedFrames: Int64? = nil,
        duration: Int64? = nil,
        temperatureC: Double? = nil
    ) {
        self.bitrate = bitrate
        self.fps = fps
        self.droppedFrames = droppedFrames
        self.duration = duration
        self.temperatureC = temperatureC
    }

    init?(values: [String: Any]?) {
        guard let values else { return nil }
        self.init(
            bitrate: streamInt64Value(values["bitrate"]),
            fps: doubleValue(values["fps"]),
            droppedFrames: streamInt64Value(values["droppedFrames"]),
            duration: streamInt64Value(values["duration"]),
            temperatureC: doubleValue(values["temperatureC"])
        )
    }

    var values: [String: Any] {
        var values: [String: Any] = [:]
        if let bitrate { values["bitrate"] = bitrate }
        if let fps { values["fps"] = fps }
        if let droppedFrames { values["droppedFrames"] = droppedFrames }
        if let duration { values["duration"] = duration }
        if let temperatureC { values["temperatureC"] = temperatureC }
        return values
    }
}

public struct StreamRequest {
    public let streamUrl: String
    public let streamId: String
    public let sound: Bool
    public let video: StreamVideoConfig?
    public let audio: StreamAudioConfig?
    public let authToken: String?
    public let captureAudio: Bool
    public let ice: StreamIceConfig?
    /// Correlation id the glasses echo in every SOFTAP_TRACE line, so phone and glasses logs can
    /// be joined despite unsynchronised clocks.
    public let traceId: String?
    public let telemetry: Bool?

    public init(
        streamUrl: String,
        streamId: String = "",
        sound: Bool = true,
        video: StreamVideoConfig? = nil,
        audio: StreamAudioConfig? = nil,
        authToken: String? = nil,
        captureAudio: Bool = true,
        ice: StreamIceConfig? = nil,
        traceId: String? = nil,
        telemetry: Bool? = nil
    ) {
        self.streamUrl = streamUrl
        self.streamId = streamId
        self.sound = sound
        self.video = video
        self.audio = audio
        self.authToken = authToken
        self.captureAudio = captureAudio
        self.ice = ice
        self.traceId = traceId
        self.telemetry = telemetry
    }

    init(values: [String: Any]) {
        let telemetryValue: Bool?
        if let telemetry = values["telemetry"] as? Bool {
            telemetryValue = telemetry
        } else if let tl = values["tl"] as? Bool {
            telemetryValue = tl
        } else {
            telemetryValue = nil
        }

        self.init(
            streamUrl: values["streamUrl"] as? String
                ?? values["rtmpUrl"] as? String
                ?? values["srtUrl"] as? String
                ?? values["whipUrl"] as? String
                ?? "",
            streamId: values["streamId"] as? String ?? "",
            sound: values["sound"] as? Bool ?? true,
            video: StreamVideoConfig(values: values["video"] as? [String: Any]),
            audio: StreamAudioConfig(values: values["audio"] as? [String: Any]),
            authToken: values["authToken"] as? String ?? values["auth_token"] as? String,
            captureAudio: (values["captureAudio"] as? Bool) ?? (values["ca"] as? Bool) ?? true,
            ice: StreamIceConfig(
                values: (values["ice"] as? [String: Any]) ?? (values["i"] as? [String: Any])
            ),
            traceId: values["traceId"] as? String,
            telemetry: telemetryValue
        )
    }

    public var values: [String: Any] {
        var values: [String: Any] = [:]
        values["type"] = "start_stream"
        values["streamUrl"] = streamUrl
        values["streamId"] = streamId
        values["sound"] = sound
        if let videoValues = video?.dictionary, !videoValues.isEmpty {
            values["video"] = videoValues
        }
        if let audioValues = audio?.dictionary, !audioValues.isEmpty {
            values["audio"] = audioValues
        }
        if let authToken, !authToken.isEmpty {
            values["authToken"] = authToken
        }
        if !captureAudio {
            values["captureAudio"] = false
        }
        if let iceValues = ice?.dictionary, !iceValues.isEmpty {
            values["ice"] = iceValues
        }
        if let traceId, !traceId.isEmpty {
            values["traceId"] = traceId
        }
        if let telemetry {
            values["telemetry"] = telemetry
        }
        return values
    }
}

struct StreamKeepAliveRequest {
    let streamId: String
    let ackId: String

    init(streamId: String, ackId: String) {
        self.streamId = streamId
        self.ackId = ackId
    }

    init(values: [String: Any]) {
        self.init(
            streamId: values["streamId"] as? String ?? "",
            ackId: values["ackId"] as? String ?? ""
        )
    }

    var values: [String: Any] {
        var values: [String: Any] = [:]
        values["type"] = "keep_stream_alive"
        values["streamId"] = streamId
        values["ackId"] = ackId
        return values
    }
}

public enum StreamState: String, Equatable {
    case initializing
    case streaming
    case stopping
    case stopped
    case reconnecting
    case reconnected
    case reconnectFailed = "reconnect_failed"
    case error

    fileprivate static func from(_ value: String?) -> StreamState? {
        switch value?.lowercased() {
        case "initializing", "starting", "connecting":
            return .initializing
        case "streaming", "streaming_started", "active":
            return .streaming
        case "stopping":
            return .stopping
        case "stopped", "not_streaming", "disconnected", "timeout":
            return .stopped
        case "reconnecting":
            return .reconnecting
        case "reconnected":
            return .reconnected
        case "reconnect_failed":
            return .reconnectFailed
        case "error", "error_not_streaming":
            return .error
        default:
            return nil
        }
    }
}

public enum StreamStatusKind: String, Equatable {
    case lifecycle
    case reconnect
    case error
    case snapshot
}

public enum StreamStatus: CustomStringConvertible, Equatable {
    case lifecycle(state: StreamState, streamId: String?, timestamp: Int?, resolvedConfig: StreamResolvedConfig?)
    case reconnecting(
        streamId: String?,
        attempt: Int,
        maxAttempts: Int,
        reason: String,
        timestamp: Int?,
        resolvedConfig: StreamResolvedConfig?
    )
    case reconnected(streamId: String?, attempt: Int, timestamp: Int?, resolvedConfig: StreamResolvedConfig?)
    case reconnectFailed(streamId: String?, maxAttempts: Int, timestamp: Int?, resolvedConfig: StreamResolvedConfig?)
    case error(streamId: String?, errorDetails: String, timestamp: Int?, resolvedConfig: StreamResolvedConfig?)
    case snapshot(
        state: StreamState,
        streaming: Bool,
        reconnecting: Bool,
        streamId: String?,
        attempt: Int?,
        timestamp: Int?,
        resolvedConfig: StreamResolvedConfig?
    )

    public init(values: [String: Any]) {
        let rawState = stringValue(values, "status")
        let streamId = stringValue(values, "streamId")
        let timestamp = intValue(values["timestamp"])
        let resolvedConfig = StreamResolvedConfig(values: values["resolvedConfig"] as? [String: Any])
        let attempt = optionalIntValue(values, "attempt")
        let maxAttempts = optionalIntValue(values, "maxAttempts") ?? 0
        let parsedState = StreamState.from(rawState)

        if hasAnyKey(values, "streaming") || hasAnyKey(values, "reconnecting") {
            let streaming = boolValue(values, "streaming") == true
            let reconnecting = boolValue(values, "reconnecting") == true
            let snapshotState: StreamState
            if reconnecting {
                snapshotState = .reconnecting
            } else if streaming {
                snapshotState = .streaming
            } else {
                snapshotState = parsedState ?? .stopped
            }
            self = .snapshot(
                state: snapshotState,
                streaming: streaming,
                reconnecting: reconnecting,
                streamId: streamId,
                attempt: attempt,
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
            return
        }

        guard let state = parsedState else {
            self = .error(
                streamId: streamId,
                errorDetails: rawState.map { "Unknown stream status: \($0)" } ?? "Missing stream status",
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
            return
        }

        switch state {
        case .reconnecting:
            self = .reconnecting(
                streamId: streamId,
                attempt: attempt ?? 0,
                maxAttempts: maxAttempts,
                reason: stringValue(values, "reason") ?? "",
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
        case .reconnected:
            self = .reconnected(
                streamId: streamId,
                attempt: attempt ?? 0,
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
        case .reconnectFailed:
            self = .reconnectFailed(
                streamId: streamId,
                maxAttempts: maxAttempts,
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
        case .error:
            self = .error(
                streamId: streamId,
                errorDetails: stringValue(values, "errorDetails")
                    ?? (rawState == "error_not_streaming" ? "not_streaming" : "Unknown stream error"),
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
        default:
            self = .lifecycle(
                state: state,
                streamId: streamId,
                timestamp: timestamp,
                resolvedConfig: resolvedConfig
            )
        }
    }

    public var kind: StreamStatusKind {
        switch self {
        case .lifecycle:
            .lifecycle
        case .reconnecting, .reconnected, .reconnectFailed:
            .reconnect
        case .error:
            .error
        case .snapshot:
            .snapshot
        }
    }

    public var state: StreamState {
        switch self {
        case let .lifecycle(state, _, _, _):
            state
        case .reconnecting:
            .reconnecting
        case .reconnected:
            .reconnected
        case .reconnectFailed:
            .reconnectFailed
        case .error:
            .error
        case let .snapshot(state, _, _, _, _, _, _):
            state
        }
    }

    public var streamId: String? {
        switch self {
        case let .lifecycle(_, streamId, _, _),
             let .reconnecting(streamId, _, _, _, _, _),
             let .reconnected(streamId, _, _, _),
             let .reconnectFailed(streamId, _, _, _),
             let .error(streamId, _, _, _),
             let .snapshot(_, _, _, streamId, _, _, _):
            streamId
        }
    }

    public var timestamp: Int? {
        switch self {
        case let .lifecycle(_, _, timestamp, _),
             let .reconnecting(_, _, _, _, timestamp, _),
             let .reconnected(_, _, timestamp, _),
             let .reconnectFailed(_, _, timestamp, _),
             let .error(_, _, timestamp, _),
             let .snapshot(_, _, _, _, _, timestamp, _):
            timestamp
        }
    }

    public var resolvedConfig: StreamResolvedConfig? {
        switch self {
        case let .lifecycle(_, _, _, resolvedConfig),
             let .reconnecting(_, _, _, _, _, resolvedConfig),
             let .reconnected(_, _, _, resolvedConfig),
             let .reconnectFailed(_, _, _, resolvedConfig),
             let .error(_, _, _, resolvedConfig),
             let .snapshot(_, _, _, _, _, _, resolvedConfig):
            resolvedConfig
        }
    }

    public var values: [String: Any] {
        var values: [String: Any] = [
            "kind": kind.rawValue,
            "status": state.rawValue,
        ]
        if let streamId, !streamId.isEmpty {
            values["streamId"] = streamId
        }
        if let timestamp {
            values["timestamp"] = timestamp
        }
        if let resolvedConfig {
            values["resolvedConfig"] = resolvedConfig.values
        }

        switch self {
        case .lifecycle:
            break
        case let .reconnecting(_, attempt, maxAttempts, reason, _, _):
            values["attempt"] = attempt
            values["maxAttempts"] = maxAttempts
            values["reason"] = reason
        case let .reconnected(_, attempt, _, _):
            values["attempt"] = attempt
        case let .reconnectFailed(_, maxAttempts, _, _):
            values["maxAttempts"] = maxAttempts
        case let .error(_, errorDetails, _, _):
            values["errorDetails"] = errorDetails
        case let .snapshot(_, streaming, reconnecting, _, attempt, _, _):
            values["streaming"] = streaming
            values["reconnecting"] = reconnecting
            if let attempt {
                values["attempt"] = attempt
            }
        }

        return values
    }

    public var description: String {
        "StreamStatus(kind: \(kind.rawValue), status: \(state.rawValue), streamId: \(streamId ?? "none"))"
    }
}

public struct StreamStatusEvent: CustomStringConvertible {
    public let status: StreamStatus
    public let stats: StreamLiveStats?
    public private(set) var processSessionId: String?
    public private(set) var revision: Int?
    public private(set) var terminal: Bool?
    public private(set) var errorDetails: String?
    /// True when the glasses will retry the failed publisher themselves
    /// (emitting side lands in PR #3488); absent on older firmware and on
    /// events not parsed from a glasses status map. Carried here instead of
    /// as an `.error` associated value so the public case stays unchanged.
    public private(set) var willRetry: Bool?

    public init(status: StreamStatus, stats: StreamLiveStats? = nil) {
        self.status = status
        self.stats = stats
    }

    public init(values: [String: Any]) {
        status = StreamStatus(values: values)
        stats = StreamLiveStats(values: values["stats"] as? [String: Any])
        willRetry = boolValue(values, "willRetry")
        processSessionId = stringValue(values, "sid")
        revision = optionalIntValue(values, "revision")
        terminal = boolValue(values, "terminal")
        errorDetails = stringValue(values, "errorDetails")
    }

    public var state: StreamState {
        status.state
    }

    public var streamId: String? {
        status.streamId
    }

    public var resolvedConfig: StreamResolvedConfig? {
        status.resolvedConfig
    }

    public var values: [String: Any] {
        var values = status.values
        values["type"] = "stream_status"
        if let processSessionId { values["sid"] = processSessionId }
        if let revision { values["revision"] = revision }
        if let terminal { values["terminal"] = terminal }
        if let errorDetails { values["errorDetails"] = errorDetails }
        if let stats {
            values["stats"] = stats.values
        }
        if let willRetry {
            values["willRetry"] = willRetry
        }
        return values
    }

    public var description: String {
        "StreamStatusEvent(kind: \(status.kind.rawValue), status: \(state.rawValue), streamId: \(streamId ?? "none"))"
    }
}

public struct KeepAliveAckEvent: CustomStringConvertible, Equatable {
    public let streamId: String
    public let ackId: String
    public let timestamp: Int?

    public init(streamId: String, ackId: String, timestamp: Int? = nil) {
        self.streamId = streamId
        self.ackId = ackId
        self.timestamp = timestamp
    }

    public init(values: [String: Any]) {
        streamId = stringValue(values, "streamId") ?? ""
        ackId = stringValue(values, "ackId") ?? ""
        timestamp = intValue(values["timestamp"])
    }

    public var values: [String: Any] {
        var values: [String: Any] = [
            "type": "keep_alive_ack",
            "streamId": streamId,
            "ackId": ackId,
        ]
        if let timestamp {
            values["timestamp"] = timestamp
        }
        return values
    }

    public var description: String {
        "KeepAliveAckEvent(streamId: \(streamId), ackId: \(ackId))"
    }
}