kino-core 0.1.0

Core video player library - HLS/DASH parsing, buffer management, and playback control
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Analytics event emission
//!
//! Captures playback events for:
//! - Quality of Experience (QoE) metrics
//! - Error tracking
//! - Usage analytics
//! - A/B testing

use crate::types::*;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, RwLock};
use tracing::{debug, info};
use uuid::Uuid;

/// Analytics event types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum AnalyticsEvent {
    /// Content loaded
    Load {
        url: String,
        is_live: bool,
    },

    /// Playback started
    Play {
        position: f64,
    },

    /// Playback paused
    Pause {
        position: f64,
    },

    /// Seek performed
    Seek {
        from: f64,
        to: f64,
    },

    /// Rebuffering started
    Rebuffer {
        position: f64,
        buffer_level: f64,
    },

    /// Rebuffering ended
    RebufferEnd {
        position: f64,
        duration: f64,
    },

    /// Quality change
    QualityChange {
        from_bitrate: u64,
        to_bitrate: u64,
        from_resolution: Option<Resolution>,
        to_resolution: Option<Resolution>,
        reason: QualityChangeReason,
    },

    /// State change
    StateChange {
        from: PlayerState,
        to: PlayerState,
        position: f64,
    },

    /// Playback ended
    End {
        position: f64,
        watch_time: f64,
    },

    /// Error occurred
    Error {
        code: String,
        message: String,
        fatal: bool,
        position: f64,
    },

    /// Heartbeat (periodic)
    Heartbeat {
        position: f64,
        buffer_level: f64,
        bitrate: u64,
        dropped_frames: u64,
        decoded_frames: u64,
    },

    /// Custom event
    Custom {
        name: String,
        data: serde_json::Value,
    },
}

/// Reason for quality change
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QualityChangeReason {
    /// ABR algorithm decision
    Abr,
    /// User manual selection
    Manual,
    /// Buffer-based downgrade
    Buffer,
    /// Initial selection
    Initial,
}

/// Analytics event with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsEventRecord {
    /// Unique event ID
    pub id: Uuid,
    /// Session ID
    pub session_id: SessionId,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
    /// Sequence number
    pub sequence: u64,
    /// The event
    #[serde(flatten)]
    pub event: AnalyticsEvent,
}

/// Analytics emitter
pub struct AnalyticsEmitter {
    /// Session ID
    session_id: SessionId,
    /// Event sequence counter
    sequence: RwLock<u64>,
    /// Event buffer
    buffer: RwLock<Vec<AnalyticsEventRecord>>,
    /// Maximum buffer size before flush
    max_buffer_size: usize,
    /// Event channel for async processing
    event_tx: mpsc::Sender<AnalyticsEventRecord>,
    /// Beacon endpoint (if configured)
    beacon_url: Option<String>,
}

impl AnalyticsEmitter {
    /// Create a new analytics emitter
    pub fn new() -> Self {
        let (event_tx, mut event_rx) = mpsc::channel::<AnalyticsEventRecord>(1000);

        // Spawn background processor
        tokio::spawn(async move {
            while let Some(event) = event_rx.recv().await {
                // In production, batch and send to analytics endpoint
                debug!(
                    event_id = %event.id,
                    event = ?event.event,
                    "Analytics event"
                );
            }
        });

        Self {
            session_id: SessionId::new(),
            sequence: RwLock::new(0),
            buffer: RwLock::new(Vec::new()),
            max_buffer_size: 50,
            event_tx,
            beacon_url: None,
        }
    }

    /// Create with beacon endpoint
    pub fn with_beacon(beacon_url: String) -> Self {
        let mut emitter = Self::new();
        emitter.beacon_url = Some(beacon_url);
        emitter
    }

    /// Emit an analytics event
    pub async fn emit(&self, event: AnalyticsEvent) {
        let mut seq = self.sequence.write().await;
        *seq += 1;
        let sequence = *seq;

        let record = AnalyticsEventRecord {
            id: Uuid::new_v4(),
            session_id: self.session_id,
            timestamp: Utc::now(),
            sequence,
            event,
        };

        // Add to buffer
        let mut buffer = self.buffer.write().await;
        buffer.push(record.clone());

        // Flush if buffer is full
        if buffer.len() >= self.max_buffer_size {
            let events: Vec<_> = buffer.drain(..).collect();
            drop(buffer);
            self.flush_events(events).await;
        }

        // Send to channel for async processing
        let _ = self.event_tx.send(record).await;
    }

    /// Flush buffered events
    async fn flush_events(&self, events: Vec<AnalyticsEventRecord>) {
        if events.is_empty() {
            return;
        }

        info!(count = events.len(), "Flushing analytics events");

        // In production, send to analytics endpoint
        if let Some(ref url) = self.beacon_url {
            // Use reqwest to send events
            // This is fire-and-forget for beacons
            let client = reqwest::Client::new();
            let _ = client.post(url)
                .json(&events)
                .send()
                .await;
        }
    }

    /// Get all buffered events
    pub async fn get_events(&self) -> Vec<AnalyticsEventRecord> {
        self.buffer.read().await.clone()
    }

    /// Clear buffer
    pub async fn clear(&self) {
        self.buffer.write().await.clear();
    }

    /// Set beacon endpoint
    pub fn set_beacon_url(&mut self, url: String) {
        self.beacon_url = Some(url);
    }
}

impl Default for AnalyticsEmitter {
    fn default() -> Self {
        Self::new()
    }
}

/// QoE (Quality of Experience) calculator
pub struct QoeCalculator {
    /// Initial buffer time
    initial_buffer_time: f64,
    /// Total rebuffer count
    rebuffer_count: u32,
    /// Total rebuffer duration
    rebuffer_duration: f64,
    /// Playback start time
    _start_time: f64,
    /// Quality switches
    quality_switches: Vec<(f64, u64)>, // (timestamp, bitrate)
    /// Average bitrate (weighted by time)
    bitrate_samples: Vec<(f64, u64)>, // (duration, bitrate)
}

impl QoeCalculator {
    pub fn new() -> Self {
        Self {
            initial_buffer_time: 0.0,
            rebuffer_count: 0,
            rebuffer_duration: 0.0,
            _start_time: 0.0,
            quality_switches: Vec::new(),
            bitrate_samples: Vec::new(),
        }
    }

    /// Record initial buffering time
    pub fn record_initial_buffer(&mut self, duration: f64) {
        self.initial_buffer_time = duration;
    }

    /// Record rebuffer event
    pub fn record_rebuffer(&mut self, duration: f64) {
        self.rebuffer_count += 1;
        self.rebuffer_duration += duration;
    }

    /// Record quality switch
    pub fn record_quality_switch(&mut self, timestamp: f64, bitrate: u64) {
        self.quality_switches.push((timestamp, bitrate));
    }

    /// Record bitrate sample
    pub fn record_bitrate(&mut self, duration: f64, bitrate: u64) {
        self.bitrate_samples.push((duration, bitrate));
    }

    /// Calculate QoE score (0-100)
    pub fn calculate_qoe(&self) -> f64 {
        // MOS-like scoring based on:
        // - Initial buffer time (startup delay)
        // - Rebuffer frequency and duration
        // - Average quality
        // - Quality stability

        let mut score = 100.0;

        // Penalize initial buffer time
        // > 2s starts reducing score
        if self.initial_buffer_time > 2.0 {
            score -= (self.initial_buffer_time - 2.0) * 5.0;
        }

        // Penalize rebuffers heavily
        // Each rebuffer costs 10 points
        score -= self.rebuffer_count as f64 * 10.0;

        // Penalize rebuffer duration
        // Each second of rebuffering costs 5 points
        score -= self.rebuffer_duration * 5.0;

        // Penalize quality switches
        // Each switch costs 2 points
        score -= self.quality_switches.len() as f64 * 2.0;

        // Bonus for high average bitrate
        let avg_bitrate = self.average_bitrate();
        if avg_bitrate > 5_000_000 {
            score += 5.0;
        } else if avg_bitrate > 2_000_000 {
            score += 2.0;
        }

        score.clamp(0.0, 100.0)
    }

    /// Calculate average bitrate
    fn average_bitrate(&self) -> u64 {
        if self.bitrate_samples.is_empty() {
            return 0;
        }

        let total_duration: f64 = self.bitrate_samples.iter().map(|(d, _)| d).sum();
        if total_duration == 0.0 {
            return 0;
        }

        let weighted_sum: f64 = self.bitrate_samples
            .iter()
            .map(|(d, b)| d * *b as f64)
            .sum();

        (weighted_sum / total_duration) as u64
    }

    /// Get QoE breakdown
    pub fn breakdown(&self) -> QoeBreakdown {
        QoeBreakdown {
            score: self.calculate_qoe(),
            initial_buffer_time: self.initial_buffer_time,
            rebuffer_count: self.rebuffer_count,
            rebuffer_duration: self.rebuffer_duration,
            quality_switches: self.quality_switches.len() as u32,
            average_bitrate: self.average_bitrate(),
        }
    }
}

impl Default for QoeCalculator {
    fn default() -> Self {
        Self::new()
    }
}

/// QoE score breakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QoeBreakdown {
    pub score: f64,
    pub initial_buffer_time: f64,
    pub rebuffer_count: u32,
    pub rebuffer_duration: f64,
    pub quality_switches: u32,
    pub average_bitrate: u64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_qoe_perfect() {
        let calc = QoeCalculator::new();
        assert_eq!(calc.calculate_qoe(), 100.0);
    }

    #[test]
    fn test_qoe_with_rebuffers() {
        let mut calc = QoeCalculator::new();
        calc.record_rebuffer(1.0);
        calc.record_rebuffer(2.0);

        // 100 - 2*10 - 3*5 = 65
        assert!((calc.calculate_qoe() - 65.0).abs() < 0.1);
    }

    #[test]
    fn test_qoe_with_initial_buffer() {
        let mut calc = QoeCalculator::new();
        calc.record_initial_buffer(5.0); // 3 seconds over threshold

        // 100 - 3*5 = 85
        assert!((calc.calculate_qoe() - 85.0).abs() < 0.1);
    }

    #[tokio::test]
    async fn test_analytics_emitter() {
        let emitter = AnalyticsEmitter::new();

        emitter.emit(AnalyticsEvent::Play { position: 0.0 }).await;
        emitter.emit(AnalyticsEvent::Pause { position: 10.0 }).await;

        let events = emitter.get_events().await;
        assert_eq!(events.len(), 2);
    }
}