honzo-chunks 0.1.0

Honzo ebook chunk types, validation, and analysis
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use honzo_core::HonzoError;
use serde::{Deserialize, Serialize};

pub const NAMESPACE: &str = super::SYNC_NAMESPACE;

/// Represents the type of synchronization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[repr(u8)]
pub enum SyncType {
    /// Audio synchronization (text-to-audio)
    #[default]
    Audio = 0,

    /// Video synchronization (text-to-video)
    Video = 1,

    /// Animation synchronization
    Animation = 2,

    /// Page turn synchronization (for pagination)
    Page = 3,

    /// Custom synchronization type
    Custom = 255,
}

/// Represents a synchronization cue point
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncCue {
    /// The type of synchronization
    #[serde(default)]
    pub sync_type: SyncType,

    /// ID of the chunk this cue applies to
    pub chunk_id: u32,

    /// Byte offset within the chunk
    pub offset: u32,

    /// Timestamp in milliseconds (or page number for Page sync type)
    pub timestamp_ms: u64,

    /// Optional identifier for the sync media
    #[serde(default)]
    pub media_id: Option<String>,

    /// Optional duration in milliseconds for this cue
    #[serde(default)]
    pub duration_ms: Option<u64>,

    /// Optional custom data for the cue (e.g., JSON metadata)
    #[serde(default)]
    pub metadata: Option<SyncMetadata>,
}

/// Custom metadata for sync cues
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SyncMetadata {
    /// String metadata
    String(String),

    /// Number metadata
    Number(u64),

    /// Boolean metadata
    Boolean(bool),

    /// Array of values
    Array(Vec<SyncMetadata>),

    /// Key-value pairs
    Map(Vec<(String, SyncMetadata)>),
}

/// Represents a synchronization track (collection of cues for a specific media)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncTrack {
    /// Unique identifier for this track
    pub track_id: String,

    /// Type of synchronization for this track
    pub track_type: SyncType,

    /// Optional media identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_id: Option<String>,

    /// Optional media duration in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub media_duration_ms: Option<u64>,

    /// List of synchronization cues in this track
    pub cues: Vec<SyncCue>,

    /// Optional track metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<SyncMetadata>,
}

/// Represents a complete synchronization document
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncDocument {
    /// Format version
    pub version: u8,

    /// List of synchronization tracks
    pub tracks: Vec<SyncTrack>,

    /// Global metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<SyncMetadata>,
}

/// Validates a sync cue
pub fn validate_cue(cue: &SyncCue) -> Result<(), HonzoError> {
    if let Some(duration) = cue.duration_ms {
        if duration == 0 {
            return Err(HonzoError::InvalidSyncCue);
        }
    }

    // For page syncs, validate page number range
    if cue.sync_type == SyncType::Page && cue.timestamp_ms > 100000 {
        // Arbitrary max page count (100,000 pages)
        return Err(HonzoError::InvalidSyncCue);
    }

    Ok(())
}

/// Validates a sync track
pub fn validate_track(track: &SyncTrack) -> Result<(), HonzoError> {
    // Allow empty cues for now
    // if track.cues.is_empty() {
    //     return Err(HonzoError::Truncated);
    // }

    // Validate all cues in the track
    for cue in &track.cues {
        // Ensure cue type matches track type
        if cue.sync_type != track.track_type && track.track_type != SyncType::Custom {
            return Err(HonzoError::InvalidSyncCue);
        }

        validate_cue(cue)?;
    }

    Ok(())
}

/// Validates a sync document
pub fn validate_document(doc: &SyncDocument) -> Result<(), HonzoError> {
    if doc.version != 1 {
        return Err(HonzoError::InvalidSyncCue);
    }

    // Allow empty tracks for now
    // if doc.tracks.is_empty() {
    //     return Err(HonzoError::Truncated);
    // }

    // Validate all tracks
    for track in &doc.tracks {
        validate_track(track)?;
    }

    Ok(())
}

/// Parses sync cues from binary data (legacy format)
pub fn parse_sync(body: &[u8]) -> Result<Vec<SyncCue>, HonzoError> {
    if body.is_empty() {
        return Ok(Vec::new());
    }

    let cues: Vec<SyncCue> = rmp_serde::from_slice(body).map_err(|e| {
        eprintln!("Failed to deserialize sync cues: {:?}", e);
        HonzoError::Truncated
    })?;

    // Validate all cues
    for cue in &cues {
        if let Err(e) = validate_cue(cue) {
            eprintln!("Invalid sync cue: {:?}", cue);
            return Err(e);
        }
    }

    Ok(cues)
}

/// Parses a sync document from binary data
pub fn parse_sync_document(body: &[u8]) -> Result<SyncDocument, HonzoError> {
    if body.is_empty() {
        return Ok(SyncDocument {
            version: 1,
            tracks: Vec::new(),
            metadata: None,
        });
    }

    let doc: SyncDocument = rmp_serde::from_slice(body).map_err(|e| {
        eprintln!("Failed to deserialize sync document: {:?}", e);
        HonzoError::Truncated
    })?;

    if let Err(e) = validate_document(&doc) {
        eprintln!("Invalid sync document: {:?}", doc);
        return Err(e);
    }

    Ok(doc)
}

/// Builds binary data from sync cues (legacy format)
pub fn build_sync(cues: &[SyncCue]) -> Result<Vec<u8>, HonzoError> {
    if cues.is_empty() {
        return Ok(Vec::new());
    }

    // Validate all cues before building
    for cue in cues {
        if let Err(e) = validate_cue(cue) {
            eprintln!("Invalid sync cue during build: {:?}", cue);
            return Err(e);
        }
    }

    rmp_serde::to_vec_named(cues).map_err(|e| {
        eprintln!("Failed to serialize sync cues: {:?}", e);
        HonzoError::Truncated
    })
}

/// Builds binary data from a sync document
pub fn build_sync_document(doc: &SyncDocument) -> Result<Vec<u8>, HonzoError> {
    if let Err(e) = validate_document(doc) {
        eprintln!("Invalid sync document during build: {:?}", doc);
        return Err(e);
    }

    rmp_serde::to_vec_named(doc).map_err(|e| {
        eprintln!("Failed to serialize sync document: {:?}", e);
        HonzoError::Truncated
    })
}

/// Creates a new audio sync cue
pub fn new_audio_cue(chunk_id: u32, offset: u32, timestamp_ms: u64) -> SyncCue {
    SyncCue {
        sync_type: SyncType::Audio,
        chunk_id,
        offset,
        timestamp_ms,
        media_id: None,
        duration_ms: None,
        metadata: None,
    }
}

/// Creates a new video sync cue
pub fn new_video_cue(chunk_id: u32, offset: u32, timestamp_ms: u64) -> SyncCue {
    SyncCue {
        sync_type: SyncType::Video,
        chunk_id,
        offset,
        timestamp_ms,
        media_id: None,
        duration_ms: None,
        metadata: None,
    }
}

/// Creates a new page sync cue (for pagination)
pub fn new_page_cue(chunk_id: u32, offset: u32, page_number: u32) -> SyncCue {
    SyncCue {
        sync_type: SyncType::Page,
        chunk_id,
        offset,
        timestamp_ms: page_number as u64,
        media_id: Some("page".to_string()),
        duration_ms: None,
        metadata: None,
    }
}

/// Creates a new media segment cue with duration
pub fn new_media_segment_cue(
    sync_type: SyncType,
    chunk_id: u32,
    offset: u32,
    timestamp_ms: u64,
    duration_ms: u64,
    media_id: &str,
) -> SyncCue {
    SyncCue {
        sync_type,
        chunk_id,
        offset,
        timestamp_ms,
        media_id: Some(media_id.to_string()),
        duration_ms: Some(duration_ms),
        metadata: None,
    }
}

/// Creates a new sync track
pub fn new_sync_track(
    track_id: &str,
    track_type: SyncType,
    media_id: Option<&str>,
    media_duration_ms: Option<u64>,
) -> SyncTrack {
    SyncTrack {
        track_id: track_id.to_string(),
        track_type,
        media_id: media_id.map(|s| s.to_string()),
        media_duration_ms,
        cues: Vec::new(),
        metadata: None,
    }
}

/// Creates a new sync document
pub fn new_sync_document() -> SyncDocument {
    SyncDocument {
        version: 1,
        tracks: Vec::new(),
        metadata: None,
    }
}

/// Converts sync cues to a more readable format for debugging
pub fn sync_cues_to_debug_string(cues: &[SyncCue]) -> String {
    cues.iter()
        .map(|cue| {
            format!(
                "SyncCue {{ type: {:?}, chunk: {}, offset: {}, time: {}ms, media: {:?}, duration: {:?}, metadata: {:?} }}",
                cue.sync_type,
                cue.chunk_id,
                cue.offset,
                cue.timestamp_ms,
                cue.media_id,
                cue.duration_ms,
                cue.metadata
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Filters sync cues by type
pub fn filter_sync_cues(cues: &[SyncCue], sync_type: SyncType) -> Vec<SyncCue> {
    cues.iter()
        .filter(|cue| cue.sync_type == sync_type)
        .cloned()
        .collect()
}

/// Filters sync cues by media ID
pub fn filter_sync_cues_by_media(cues: &[SyncCue], media_id: &str) -> Vec<SyncCue> {
    cues.iter()
        .filter(|cue| cue.media_id.as_deref() == Some(media_id))
        .cloned()
        .collect()
}

/// Finds the sync cue closest to a given timestamp
pub fn find_closest_cue(cues: &[SyncCue], timestamp_ms: u64) -> Option<&SyncCue> {
    cues.iter()
        .min_by_key(|cue| cue.timestamp_ms.abs_diff(timestamp_ms))
}

/// Finds the sync cue for a specific page number
pub fn find_page_cue(cues: &[SyncCue], page_number: u32) -> Option<&SyncCue> {
    cues.iter()
        .find(|cue| cue.sync_type == SyncType::Page && cue.timestamp_ms == page_number as u64)
}

/// Sorts sync cues by timestamp
pub fn sort_sync_cues(cues: &mut [SyncCue]) {
    cues.sort_by_key(|a| a.timestamp_ms);
}

/// Merges multiple sets of sync cues
pub fn merge_sync_cues(cues_sets: &[&[SyncCue]]) -> Vec<SyncCue> {
    let mut merged = Vec::new();
    for cues in cues_sets {
        merged.extend_from_slice(cues);
    }
    sort_sync_cues(&mut merged);
    merged
}

/// Converts legacy sync cues to a sync document
pub fn legacy_cues_to_document(cues: Vec<SyncCue>) -> SyncDocument {
    let mut doc = new_sync_document();

    // Group cues by type
    let mut audio_cues = Vec::new();
    let mut video_cues = Vec::new();
    let mut page_cues = Vec::new();
    let mut custom_cues = Vec::new();

    for cue in cues {
        match cue.sync_type {
            SyncType::Audio => audio_cues.push(cue),
            SyncType::Video => video_cues.push(cue),
            SyncType::Page => page_cues.push(cue),
            SyncType::Animation | SyncType::Custom => custom_cues.push(cue),
        }
    }

    // Create tracks for each type
    if !audio_cues.is_empty() {
        let mut track = new_sync_track("audio", SyncType::Audio, None, None);
        track.cues = audio_cues;
        doc.tracks.push(track);
    }

    if !video_cues.is_empty() {
        let mut track = new_sync_track("video", SyncType::Video, None, None);
        track.cues = video_cues;
        doc.tracks.push(track);
    }

    if !page_cues.is_empty() {
        let mut track = new_sync_track("pages", SyncType::Page, Some("page"), None);
        track.cues = page_cues;
        doc.tracks.push(track);
    }

    if !custom_cues.is_empty() {
        let mut track = new_sync_track("custom", SyncType::Custom, None, None);
        track.cues = custom_cues;
        doc.tracks.push(track);
    }

    doc
}