mediatime 0.2.0

Exact-integer rational time types for media pipelines — FFmpeg-style Timebase, Timestamp, and TimeRange. no_std, zero dependencies, const fn.
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
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
//! `buffa::Message` implementations for the mediatime types, behind the
//! `buffa` feature. Used via `extern_path` from buffa-generated crates.
//!
//! Wire format (clean redesign — no compatibility with findit-proto's
//! hand-rolled encoding is required):
//!   Timebase  { int32  num = 1;  int32  den = 2; }
//!   TimeRange { int64  start = 1; int64  end = 2; Timebase timebase = 3; }
//!   Timestamp { int64  pts = 1;  Timebase timebase = 2; }
//!
//! The nested `Timebase` is always encoded (presence-independent) so that
//! `decode(encode(x)) == x` holds unconditionally.
//!
//! `Timebase`'s fields were `uint32` before the type became signed. Protobuf's
//! `int32` and `uint32` are the same plain (non-ZigZag) varint for values a
//! `Timebase` can hold — both are non-negative and at most `i32::MAX` — so the
//! bytes are unchanged in both directions. `sint32` would have been the
//! silent break: ZigZag re-encodes every value.

use core::num::NonZeroI32;

use ::buffa::{
  DecodeContext, DecodeError, DefaultInstance, EncodeSink, Message, SizeCache,
  bytes::Buf,
  encoding::{Tag, WireType, encode_varint, skip_field_depth, varint_len},
  types::{
    decode_int32, decode_int64, encode_int32, encode_int64, int32_encoded_len, int64_encoded_len,
  },
};

use crate::{DEN_ONE, TimeRange, Timebase, Timestamp};

const VARINT: u8 = WireType::Varint as u8;
const LEN: u8 = WireType::LengthDelimited as u8;

// ----------------------------------------------------------------------------
// Timebase — leaf message { int32 num = 1; int32 den = 2; }
// ----------------------------------------------------------------------------

impl DefaultInstance for Timebase {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Timebase> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Timebase::default()))
  }
}

impl Message for Timebase {
  // `num`/`den` are encoded UNCONDITIONALLY — no proto3 "skip default (0)"
  // elision. buffa's decoder seeds the message from `Timebase::default()`
  // (mediatime's Default = 1/1), NOT proto3 zero. Eliding `num == 0` would
  // therefore decode back as `num == 1` and break round-trip for e.g.
  // `Timebase::new(0, _)`. Both tags are single-byte (fields 1 and 2 < 16).
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    2 + int32_encoded_len(self.num()) as u32 + int32_encoded_len(self.den().get()) as u32
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::Varint).encode(buf);
    encode_int32(self.num(), buf);
    Tag::new(2, WireType::Varint).encode(buf);
    encode_int32(self.den().get(), buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // `Timebase::new` panics on a negative numerator, so decode must not
        // hand it one. Our own encoder never writes a negative; a peer can,
        // either directly or by writing a `uint32` above `i32::MAX` that
        // `decode_int32` truncates into the negative half. Clamp to the
        // smallest legal numerator so decode stays total, as `den` does.
        let num = decode_int32(buf)?.max(0);
        *self = Timebase::new(num, self.den());
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // A malformed den — zero, or negative by the same route as `num`
        // above — is clamped to 1 to keep decode total. `NonZeroI32::MIN` is
        // `i32::MIN`, so the clamp target is spelled out as `DEN_ONE`.
        let den = NonZeroI32::new(decode_int32(buf)?)
          .filter(|d| d.get() > 0)
          .unwrap_or(DEN_ONE);
        *self = Timebase::new(self.num(), den);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Timebase::default();
  }
}

// ----------------------------------------------------------------------------
// TimeRange — { int64 start = 1; int64 end = 2; Timebase timebase = 3; }
// ----------------------------------------------------------------------------

impl DefaultInstance for TimeRange {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<TimeRange> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(TimeRange::new(0, 0, Timebase::default())))
  }
}

impl Message for TimeRange {
  fn compute_size(&self, cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound here — the decoder seeds start/end/pts at 0.
    if self.start_pts() != 0 {
      size += 1 + int64_encoded_len(self.start_pts()) as u32;
    }
    // proto3 zero-elision: sound here — the decoder seeds start/end/pts at 0.
    if self.end_pts() != 0 {
      size += 1 + int64_encoded_len(self.end_pts()) as u32;
    }
    // timebase (field 3) — always encoded for unconditional round-trip.
    let slot = cache.reserve();
    let inner = self.timebase().compute_size(cache);
    cache.set(slot, inner);
    size += 1 + varint_len(inner as u64) as u32 + inner;
    size
  }

  fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound here — the decoder seeds start/end/pts at 0.
    if self.start_pts() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_int64(self.start_pts(), buf);
    }
    // proto3 zero-elision: sound here — the decoder seeds start/end/pts at 0.
    if self.end_pts() != 0 {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_int64(self.end_pts(), buf);
    }
    Tag::new(3, WireType::LengthDelimited).encode(buf);
    encode_varint(cache.consume_next() as u64, buf);
    self.timebase().write_to(cache, buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_int64(buf)?;
        // Use the bypass constructor: intermediate state may have
        // start > end if `start` field arrives before `end`.
        *self = TimeRange::new_for_decode(v, self.end_pts(), self.timebase());
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_int64(buf)?;
        // Use the bypass constructor: intermediate state may have
        // start > end if `end` field arrives before `start`.
        *self = TimeRange::new_for_decode(self.start_pts(), v, self.timebase());
      }
      3 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 3,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut tb = self.timebase();
        buffa::Message::merge_length_delimited(&mut tb, buf, ctx)?;
        *self = TimeRange::new_for_decode(self.start_pts(), self.end_pts(), tb);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = TimeRange::new(0, 0, Timebase::default());
  }
}

// ----------------------------------------------------------------------------
// Timestamp — { int64 pts = 1; Timebase timebase = 2; }
// ----------------------------------------------------------------------------

impl DefaultInstance for Timestamp {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Timestamp> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Timestamp::new(0, Timebase::default())))
  }
}

impl Message for Timestamp {
  fn compute_size(&self, cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound here — the decoder seeds start/end/pts at 0.
    if self.pts() != 0 {
      size += 1 + int64_encoded_len(self.pts()) as u32;
    }
    let slot = cache.reserve();
    let inner = self.timebase().compute_size(cache);
    cache.set(slot, inner);
    size += 1 + varint_len(inner as u64) as u32 + inner;
    size
  }

  fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound here — the decoder seeds start/end/pts at 0.
    if self.pts() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_int64(self.pts(), buf);
    }
    Tag::new(2, WireType::LengthDelimited).encode(buf);
    encode_varint(cache.consume_next() as u64, buf);
    self.timebase().write_to(cache, buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_int64(buf)?;
        *self = Timestamp::new(v, self.timebase());
      }
      2 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut tb = self.timebase();
        buffa::Message::merge_length_delimited(&mut tb, buf, ctx)?;
        *self = Timestamp::new(self.pts(), tb);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Timestamp::new(0, Timebase::default());
  }
}

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

  fn nz(n: i32) -> NonZeroI32 {
    NonZeroI32::new(n).unwrap()
  }

  // ---- Timebase ----

  #[test]
  fn timebase_default_instance_and_clear() {
    assert_eq!(
      *<Timebase as DefaultInstance>::default_instance(),
      Timebase::default()
    );
    let mut tb = Timebase::new(7, nz(9));
    Message::clear(&mut tb);
    assert_eq!(tb, Timebase::default());
  }

  #[test]
  fn timebase_field1_wrong_wire_type_errors() {
    let mut buf: Vec<u8> = Vec::new();
    Tag::new(1, WireType::LengthDelimited).encode(&mut buf);
    encode_varint(0, &mut buf);
    let err = <Timebase as Message>::decode_from_slice(&buf).unwrap_err();
    assert!(
      matches!(err, DecodeError::WireTypeMismatch { field_number: 1, expected, actual }
        if expected == VARINT && actual == LEN),
      "got {err:?}"
    );
  }

  #[test]
  fn timebase_field2_wrong_wire_type_errors() {
    let mut buf: Vec<u8> = Vec::new();
    Tag::new(1, WireType::Varint).encode(&mut buf);
    encode_int32(5, &mut buf);
    Tag::new(2, WireType::LengthDelimited).encode(&mut buf);
    encode_varint(0, &mut buf);
    let err = <Timebase as Message>::decode_from_slice(&buf).unwrap_err();
    assert!(
      matches!(err, DecodeError::WireTypeMismatch { field_number: 2, expected, actual }
        if expected == VARINT && actual == LEN),
      "got {err:?}"
    );
  }

  #[test]
  fn timebase_den_zero_is_clamped_to_one() {
    let mut buf: Vec<u8> = Vec::new();
    Tag::new(1, WireType::Varint).encode(&mut buf);
    encode_int32(7, &mut buf);
    Tag::new(2, WireType::Varint).encode(&mut buf);
    encode_int32(0, &mut buf); // malformed den == 0 on the wire
    let tb = <Timebase as Message>::decode_from_slice(&buf).expect("decodes with clamp");
    assert_eq!(tb.num(), 7);
    assert_eq!(tb.den().get(), 1);
  }

  #[test]
  fn timebase_negative_fields_are_clamped() {
    // A peer writing `uint32` values above `i32::MAX` produces varints that
    // `decode_int32` truncates into the negative half. Both fields clamp to
    // their smallest legal value rather than panicking in `Timebase::new`.
    let mut buf: Vec<u8> = Vec::new();
    Tag::new(1, WireType::Varint).encode(&mut buf);
    encode_int32(-7, &mut buf);
    Tag::new(2, WireType::Varint).encode(&mut buf);
    encode_int32(-9, &mut buf);
    let tb = <Timebase as Message>::decode_from_slice(&buf).expect("decodes with clamp");
    assert_eq!(tb.num(), 0);
    assert_eq!(tb.den().get(), 1);
  }

  #[test]
  fn timebase_wire_bytes_are_unchanged_by_the_signed_fields() {
    // Golden bytes captured from the `uint32` encoding this type used before
    // `num`/`den` became signed. `int32` and `uint32` are the same plain
    // varint for non-negative values, so the encoding must not have moved —
    // and old bytes must still decode to the same value.
    for (tb, golden) in [
      (
        Timebase::new(30_000, nz(1001)),
        &b"\x08\xb0\xea\x01\x10\xe9\x07"[..],
      ),
      (Timebase::new(0, nz(1)), &b"\x08\x00\x10\x01"[..]),
      (
        Timebase::new(1, nz(48_000)),
        &b"\x08\x01\x10\x80\xf7\x02"[..],
      ),
      (Timebase::new(1, nz(1)), &b"\x08\x01\x10\x01"[..]),
      (
        Timebase::new(i32::MAX, nz(i32::MAX)),
        &b"\x08\xff\xff\xff\xff\x07\x10\xff\xff\xff\xff\x07"[..],
      ),
    ] {
      assert_eq!(tb.encode_to_vec(), golden, "encoding moved for {tb:?}");
      assert_eq!(
        <Timebase as Message>::decode_from_slice(golden).expect("golden decodes"),
        tb
      );
    }
  }

  #[test]
  fn timebase_unknown_field_is_skipped() {
    let mut buf: Vec<u8> = Vec::new();
    Tag::new(1, WireType::Varint).encode(&mut buf);
    encode_int32(2, &mut buf);
    Tag::new(2, WireType::Varint).encode(&mut buf);
    encode_int32(3, &mut buf);
    Tag::new(7, WireType::Varint).encode(&mut buf); // unknown field → skip_field_depth
    encode_varint(99, &mut buf);
    let tb = <Timebase as Message>::decode_from_slice(&buf).expect("unknown field skipped");
    assert_eq!(tb, Timebase::new(2, nz(3)));
  }

  // ---- TimeRange ----

  #[test]
  fn timerange_default_instance_and_clear() {
    let di = <TimeRange as DefaultInstance>::default_instance();
    assert_eq!((di.start_pts(), di.end_pts()), (0, 0));
    assert_eq!(di.timebase(), Timebase::default());
    let mut r = TimeRange::new(3, 5, Timebase::new(2, nz(3)));
    Message::clear(&mut r);
    assert_eq!((r.start_pts(), r.end_pts()), (0, 0));
    assert_eq!(r.timebase(), Timebase::default());
  }

  #[test]
  fn timerange_wrong_wire_types_error() {
    let mut b1: Vec<u8> = Vec::new();
    Tag::new(1, WireType::LengthDelimited).encode(&mut b1);
    encode_varint(0, &mut b1);
    assert!(matches!(
      <TimeRange as Message>::decode_from_slice(&b1).unwrap_err(),
      DecodeError::WireTypeMismatch { field_number: 1, expected, actual }
        if expected == VARINT && actual == LEN
    ));
    let mut b2: Vec<u8> = Vec::new();
    Tag::new(2, WireType::LengthDelimited).encode(&mut b2);
    encode_varint(0, &mut b2);
    assert!(matches!(
      <TimeRange as Message>::decode_from_slice(&b2).unwrap_err(),
      DecodeError::WireTypeMismatch { field_number: 2, expected, actual }
        if expected == VARINT && actual == LEN
    ));
    let mut b3: Vec<u8> = Vec::new();
    Tag::new(3, WireType::Varint).encode(&mut b3);
    encode_varint(0, &mut b3);
    assert!(matches!(
      <TimeRange as Message>::decode_from_slice(&b3).unwrap_err(),
      DecodeError::WireTypeMismatch { field_number: 3, expected, actual }
        if expected == LEN && actual == VARINT
    ));
  }

  #[test]
  fn timerange_unknown_field_is_skipped() {
    let original = TimeRange::new(10, 20, Timebase::new(30000, nz(1001)));
    let mut buf = original.encode_to_vec();
    Tag::new(9, WireType::Varint).encode(&mut buf); // unknown → skip_field_depth
    encode_varint(123, &mut buf);
    let r = <TimeRange as Message>::decode_from_slice(&buf).expect("unknown field skipped");
    assert_eq!(r, original);
  }

  // ---- Timestamp ----

  #[test]
  fn timestamp_default_instance_and_clear() {
    let di = <Timestamp as DefaultInstance>::default_instance();
    assert_eq!(di.pts(), 0);
    assert_eq!(di.timebase(), Timebase::default());
    let mut ts = Timestamp::new(42, Timebase::new(2, nz(3)));
    Message::clear(&mut ts);
    assert_eq!(ts.pts(), 0);
    assert_eq!(ts.timebase(), Timebase::default());
  }

  #[test]
  fn timestamp_wrong_wire_types_error() {
    let mut b1: Vec<u8> = Vec::new();
    Tag::new(1, WireType::LengthDelimited).encode(&mut b1);
    encode_varint(0, &mut b1);
    assert!(matches!(
      <Timestamp as Message>::decode_from_slice(&b1).unwrap_err(),
      DecodeError::WireTypeMismatch { field_number: 1, expected, actual }
        if expected == VARINT && actual == LEN
    ));
    let mut b2: Vec<u8> = Vec::new();
    Tag::new(2, WireType::Varint).encode(&mut b2);
    encode_varint(0, &mut b2);
    assert!(matches!(
      <Timestamp as Message>::decode_from_slice(&b2).unwrap_err(),
      DecodeError::WireTypeMismatch { field_number: 2, expected, actual }
        if expected == LEN && actual == VARINT
    ));
  }

  #[test]
  fn timestamp_unknown_field_is_skipped() {
    let original = Timestamp::new(-99, Timebase::new(24000, nz(1001)));
    let mut buf = original.encode_to_vec();
    Tag::new(6, WireType::Varint).encode(&mut buf); // unknown → skip_field_depth
    encode_varint(7, &mut buf);
    let ts = <Timestamp as Message>::decode_from_slice(&buf).expect("unknown field skipped");
    assert_eq!(ts, original);
  }
}