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
/*
    Copyright (C) 2020  Rafal Michalski

    This file is part of SPECTRUSTY, a Rust library for building emulators.

    For the full copyright notice, see the lib.rs file.
*/
//! T-state timestamp types and counters.
use core::cmp::{Ordering, Ord, PartialEq, PartialOrd};
use core::convert::{TryInto, TryFrom};
use core::fmt::Debug;
use core::hash::{Hash, Hasher};
use core::marker::PhantomData;
use core::num::{NonZeroU8, NonZeroU16};
use core::ops::{Deref, DerefMut};

use z80emu::{Clock, host::cycles::*};
#[cfg(feature = "snapshot")]
use serde::{Serialize, Deserialize};

use crate::video::VideoFrame;

mod packed;
mod ops;
pub use packed::*;
pub use ops::*;

/// A linear T-state timestamp type.
pub type FTs = i32;
/// A type used for a horizontal T-state timestamp or a video scanline index for [VideoTs].
pub type Ts = i16;

/// A timestamp type that consists of two video counters: vertical and horizontal.
///
/// `VideoTs { vc: 0, hc: 0 }` marks the start of the video frame.
#[cfg_attr(feature = "snapshot", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct VideoTs {
    /// A vertical counter - a video scan-line index.
    pub vc: Ts,
    /// A horizontal counter - measured in T-states.
    pub hc: Ts,
}

/// A [VideoTs] timestamp wrapper with a constraint to the `V:` [VideoFrame],
/// implementing methods and traits for timestamp calculations.
#[cfg_attr(feature = "snapshot", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "snapshot", serde(try_from="FTs", into="FTs"))]
#[cfg_attr(feature = "snapshot", serde(bound = "V: VideoFrame"))]
#[derive(Copy, Debug)]
pub struct VFrameTs<V> {
    /// The current value of the timestamp.
    pub ts: VideoTs,
    _vframe: PhantomData<V>,
}

/// A trait used by [VFrameTsCounter] for checking if an `address` is a contended one.
pub trait MemoryContention: Copy + Debug {
    fn is_contended_address(self, address: u16) -> bool;
}

/// A generic [`VFrameTs<V>`][VFrameTs] based T-states counter.
///
/// Implements [Clock] for counting cycles when code is being executed by [z80emu::Cpu].
///
/// Inserts additional T-states according to the contention model specified by generic
/// parameters: `V:` [VideoFrame] and `C:` [MemoryContention].
///
/// [Clock]: /z80emu/%2A/z80emu/host/trait.Clock.html
/// [z80emu::Cpu]: /z80emu/%2A/z80emu/trait.Cpu.html
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct VFrameTsCounter<V, C>  {
    /// The current value of the counter.
    pub vts: VFrameTs<V>,
    /// An instance implementing a [MemoryContention] trait.
    pub contention: C,
}

/// If a vertical counter of [VideoTs] exceeds this value, it signals the control unit
/// to emulate hanging CPU indefinitely.
pub const HALT_VC_THRESHOLD: i16 = i16::max_value() >> 1;

const WAIT_STATES_THRESHOLD: u16 = i16::max_value() as u16 - 256;

impl VideoTs {
    #[inline]
    pub const fn new(vc: Ts, hc: Ts) -> Self {
        VideoTs { vc, hc }
    }
}

impl <V: VideoFrame> VFrameTs<V> {
    /// The end-of-frame timestamp, equal to the total number of T-states per frame.
    pub const EOF: VFrameTs<V> = VFrameTs { ts: VideoTs {
                                                vc: V::VSL_COUNT,
                                                hc: 0
                                            },
                                             _vframe: PhantomData };
    /// Constructs a new `VFrameTs` from the given vertical and horizontal counter values.
    ///
    /// __Note__: The returned `VFrameTs` is not normalized.
    #[inline]
    pub fn new(vc: Ts, hc: Ts) -> Self {
        VFrameTs { ts: VideoTs::new(vc, hc), _vframe: PhantomData }
    }
    /// Returns `true` if a video timestamp is normalized. Otherwise returns `false`.
    #[inline]
    pub fn is_normalized(self) -> bool {
        V::HTS_RANGE.contains(&self.ts.hc)
    }
    /// Normalizes self with a horizontal counter within the allowed range and a scan line
    /// counter adjusted accordingly.
    ///
    /// # Panics
    /// Panics when an attempt to normalize leads to an overflow of the capacity of [VideoTs].
    #[inline]
    pub fn normalized(self) -> Self {
        let VideoTs { mut vc, mut hc } = self.ts;
        if hc < V::HTS_RANGE.start || hc >= V::HTS_RANGE.end {
            let fhc: FTs = hc as FTs - if hc < 0 {
                V::HTS_RANGE.end
            }
            else {
                V::HTS_RANGE.start
            } as FTs;
            vc = vc.checked_add((fhc / V::HTS_COUNT as FTs) as Ts)
                   .expect("video timestamp overflow");
            hc = fhc.rem_euclid(V::HTS_COUNT as FTs) as Ts + V::HTS_RANGE.start;
        }
        VFrameTs::new(vc, hc)
    }
    /// Returns a video timestamp with a horizontal counter within the allowed range and a scan line
    /// counter adjusted accordingly. Saturates at [VFrameTs::min_value] or [VFrameTs::max_value].
    #[inline]
    pub fn saturating_normalized(self) -> Self {
        let VideoTs { mut vc, mut hc } = self.ts;
        if hc < V::HTS_RANGE.start || hc >= V::HTS_RANGE.end {
            let fhc: FTs = hc as FTs - if hc < 0 {
                V::HTS_RANGE.end
            }
            else {
                V::HTS_RANGE.start
            } as FTs;
            let dvc = (fhc / V::HTS_COUNT as FTs) as Ts;
            if let Some(vc1) = vc.checked_add(dvc) {
                vc = vc1;
                hc = fhc.rem_euclid(V::HTS_COUNT as FTs) as Ts + V::HTS_RANGE.start;
            }
            else {
                return if dvc < 0 { Self::min_value() } else { Self::max_value() };
            }
        }
        VFrameTs::new(vc, hc)
    }
    /// Returns the largest value that can be represented by a normalized timestamp.
    #[inline(always)]
    pub fn max_value() -> Self {
        VFrameTs { ts: VideoTs { vc: Ts::max_value(), hc: V::HTS_RANGE.end - 1 },
                   _vframe: PhantomData }
    }
    /// Returns the smallest value that can be represented by a normalized timestamp.
    #[inline(always)]
    pub fn min_value() -> Self {
        VFrameTs { ts: VideoTs { vc: Ts::min_value(), hc: V::HTS_RANGE.start },
                   _vframe: PhantomData }
    }
    /// Returns `true` if the counter value is past or near the end of a frame. Otherwise returns `false`.
    ///
    /// Specifically, the condition is met if the vertical counter is equal to or greater than [VideoFrame::VSL_COUNT].
    #[inline(always)]
    pub fn is_eof(self) -> bool {
        self.vc >= V::VSL_COUNT
    }
    /// Ensures the vertical counter is in the range: `(-VSL_COUNT, VSL_COUNT)` by calculating
    /// a remainder of the division of the vertical counter by [VideoFrame::VSL_COUNT].
    #[inline(always)]
    pub fn wrap_frame(&mut self) {
        self.ts.vc %= V::VSL_COUNT
    }
    /// Returns a video timestamp after subtracting the total number of frame video scanlines
    /// from the scan line counter.
    #[inline]
    pub fn saturating_sub_frame(self) -> Self {
        let VideoTs { vc, hc } = self.ts;
        let vc = vc.saturating_sub(V::VSL_COUNT);
        VFrameTs::new(vc, hc)
    }
    /// Returns a normalized timestamp from the given number of T-states.
    ///
    /// # Panics
    /// Panics when the given `ts` overflows the capacity of the timestamp.
    #[inline]
    pub fn from_tstates(ts: FTs) -> Self {
        Self::try_from_tstates(ts).expect("video timestamp overflow")
    }
    /// On success returns a normalized timestamp from the given number of T-states.
    ///
    /// Returns `None` when the given `ts` overflows the capacity of the timestamp.
    #[inline]
    pub fn try_from_tstates(ts: FTs) -> Option<Self> {
        let mut vc = match (ts / V::HTS_COUNT as FTs).try_into() {
            Ok(vc) => vc,
            Err(..) => return None
        };
        let mut hc: Ts = (ts % V::HTS_COUNT as FTs) as Ts;
        if hc >= V::HTS_RANGE.end {
            hc -= V::HTS_COUNT;
            vc += 1;
        }
        else if hc < V::HTS_RANGE.start {
            hc += V::HTS_COUNT;
            vc -= 1;
        }
        Some(VFrameTs::new(vc, hc))
    }
    /// Converts the timestamp to FTs.
    #[inline]
    pub fn into_tstates(self) -> FTs {
        let VideoTs { vc, hc } = self.ts;
        V::vc_hc_to_tstates(vc, hc)
    }
    /// Returns a tuple with an adjusted frame counter and with the frame-normalized timestamp as
    /// the number of T-states measured from the start of the frame.
    ///
    /// The frame starts when the horizontal and vertical counter are both 0.
    ///
    /// The returned timestamp value is in the range [0, [VideoFrame::FRAME_TSTATES_COUNT]).
    #[inline]
    pub fn into_frame_tstates(self, frames: u64) -> (u64, FTs) {
        let ts = TimestampOps::into_tstates(self);
        let frmdlt = ts / V::FRAME_TSTATES_COUNT;
        let ufrmdlt = if ts < 0 { frmdlt - 1 } else { frmdlt } as u64;
        let frames = frames.wrapping_add(ufrmdlt);
        let ts = ts.rem_euclid(V::FRAME_TSTATES_COUNT);
        (frames, ts)
    }

    #[inline]
    fn set_hc_after_small_increment(&mut self, mut hc: Ts) {
        if hc >= V::HTS_RANGE.end {
            hc -= V::HTS_COUNT as Ts;
            self.ts.vc += 1;
        }
        self.ts.hc = hc;
    }
}

impl<V, C> VFrameTsCounter<V, C>
    where V: VideoFrame,
          C: MemoryContention
{
    /// Constructs a new and normalized `VFrameTsCounter` from the given vertical and horizontal counter values.
    ///
    /// # Panics
    /// Panics when the given values lead to an overflow of the capacity of [VideoTs].
    #[inline]
    pub fn new(vc: Ts, hc: Ts, contention: C) -> Self {
        let vts = VFrameTs::new(vc, hc).normalized();
        VFrameTsCounter { vts, contention }
    }
    /// Builds a normalized [VFrameTsCounter] from the given count of T-states.
    ///
    /// # Panics
    ///
    /// Panics when the given `ts` overflows the capacity of [VideoTs].
    #[inline]
    pub fn from_tstates(ts: FTs, contention: C) -> Self {
        let vts = TimestampOps::from_tstates(ts);
        VFrameTsCounter { vts, contention }
    }
    /// Builds a normalized [VFrameTsCounter] from the given count of T-states.
    ///
    /// # Panics
    ///
    /// Panics when the given `ts` overflows the capacity of [VideoTs].
    #[inline]
    pub fn from_video_ts(vts: VideoTs, contention: C) -> Self {
        let vts = VFrameTs::from(vts).normalized();
        VFrameTsCounter { vts, contention }
    }
    /// Builds a normalized [VFrameTsCounter] from the given count of T-states.
    ///
    /// # Panics
    ///
    /// Panics when the given `ts` overflows the capacity of [VideoTs].
    #[inline]
    pub fn from_vframe_ts(vfts: VFrameTs<V>, contention: C) -> Self {
        let vts = vfts.normalized();
        VFrameTsCounter { vts, contention }
    }

    #[inline]
    pub fn is_contended_address(self, address: u16) -> bool {
        self.contention.is_contended_address(address)
    }
}

/// This macro is used to implement the ULA I/O contention scheme, for [z80emu::Clock::add_io] method of
/// [VFrameTsCounter].
/// It's being exported for the purpose of performing FUSE tests.
///
/// * $mc should be a type implementing [MemoryContention] trait.
/// * $port is a port address.
/// * $hc is an identifier of a mutable variable containing the `hc` property of a `VideoTs` timestamp.
/// * $contention should be a path to the [VideoFrame::contention] function.
///
/// The macro returns a horizontal timestamp pointing after the whole I/O cycle is over.
/// The `hc` variable is modified to contain a horizontal timestamp indicating when the data R/W operation 
/// takes place.
#[macro_export]
macro_rules! ula_io_contention {
    ($mc:expr, $port:expr, $hc:ident, $contention:path) => {
        {
            use $crate::z80emu::host::cycles::*;
            if $mc.is_contended_address($port) {
                $hc = $contention($hc) + IO_IORQ_LOW_TS as Ts;
                if $port & 1 == 0 { // C:1, C:3
                    $contention($hc) + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
                }
                else { // C:1, C:1, C:1, C:1
                    let mut hc1 = $hc;
                    for _ in 0..(IO_CYCLE_TS - IO_IORQ_LOW_TS) {
                        hc1 = $contention(hc1) + 1;
                    }
                    hc1
                }
            }
            else {
                $hc += IO_IORQ_LOW_TS as Ts;
                if $port & 1 == 0 { // N:1 C:3
                    $contention($hc) + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
                }
                else { // N:4
                    $hc + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
                }
            }
        }
    };
}
/*
impl<V: VideoFrame> Clock for VFrameTs<V> {
    type Limit = Ts;
    type Timestamp = VideoTs;

    #[inline(always)]
    fn is_past_limit(&self, limit: Self::Limit) -> bool {
        self.vc >= limit
    }

    fn add_irq(&mut self, _pc: u16) -> Self::Timestamp {
        self.set_hc_after_small_increment(self.hc + IRQ_ACK_CYCLE_TS as Ts);
        self.as_timestamp()
    }

    fn add_no_mreq(&mut self, _address: u16, add_ts: NonZeroU8) {
        let hc = self.hc + add_ts.get() as Ts;
        self.set_hc_after_small_increment(hc);
    }

    fn add_m1(&mut self, _address: u16) -> Self::Timestamp {
        self.set_hc_after_small_increment(self.hc + M1_CYCLE_TS as Ts);
        self.as_timestamp()
    }

    fn add_mreq(&mut self, _address: u16) -> Self::Timestamp {
        self.set_hc_after_small_increment(self.hc + MEMRW_CYCLE_TS as Ts);
        self.as_timestamp()
    }

    fn add_io(&mut self, _port: u16) -> Self::Timestamp {
        let hc = self.hc + IO_IORQ_LOW_TS as Ts;
        let hc1 = hc + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts;

        let mut tsc = *self;
        tsc.set_hc_after_small_increment(hc);
        self.set_hc_after_small_increment(hc1);
        tsc.as_timestamp()
    }

    fn add_wait_states(&mut self, _bus: u16, wait_states: NonZeroU16) {
        let ws = wait_states.get();
        if ws > WAIT_STATES_THRESHOLD {
            // emulate hanging the Spectrum
            self.vc += HALT_VC_THRESHOLD;
        }
        else if ws < V::HTS_COUNT as u16 {
            self.set_hc_after_small_increment(self.hc + ws as i16);
        }
        else {
            *self += ws as u32;
        }
    }

    #[inline(always)]
    fn as_timestamp(&self) -> Self::Timestamp {
        self.ts
    }
}
*/
impl<V: VideoFrame, C: MemoryContention> Clock for VFrameTsCounter<V, C> {
    type Limit = Ts;
    type Timestamp = VideoTs;

    #[inline(always)]
    fn is_past_limit(&self, limit: Self::Limit) -> bool {
        self.vc >= limit
    }

    fn add_irq(&mut self, _pc: u16) -> Self::Timestamp {
        self.vts.set_hc_after_small_increment(self.hc + IRQ_ACK_CYCLE_TS as Ts);
        self.as_timestamp()
    }

    fn add_no_mreq(&mut self, address: u16, add_ts: NonZeroU8) {
        let mut hc = self.hc;
        if V::is_contended_line_no_mreq(self.vc) && self.contention.is_contended_address(address) {
            for _ in 0..add_ts.get() {
                hc = V::contention(hc) + 1;
            }
        }
        else {
            hc += add_ts.get() as Ts;
        }
        self.vts.set_hc_after_small_increment(hc);
    }

    fn add_m1(&mut self, address: u16) -> Self::Timestamp {
        // match address {
        //     // 0x8043 => println!("0x{:04x}: {} {:?}", address, self.as_tstates(), self.tsc),
        //     0x806F..=0x8078 => println!("0x{:04x}: {} {:?}", address, self.as_tstates(), self.tsc),
        //     // 0xC008..=0xC011 => println!("0x{:04x}: {} {:?}", address, self.as_tstates(), self.tsc),
        //     _ => {}
        // }
        let hc = if V::is_contended_line_mreq(self.vc) && self.contention.is_contended_address(address) {
            V::contention(self.hc)
        }
        else {
            self.hc
        };
        self.vts.set_hc_after_small_increment(hc + M1_CYCLE_TS as Ts);
        self.as_timestamp()
    }

    fn add_mreq(&mut self, address: u16) -> Self::Timestamp {
        let hc = if V::is_contended_line_mreq(self.vc) && self.contention.is_contended_address(address) {
            V::contention(self.hc)
        }
        else {
            self.hc
        };
        self.vts.set_hc_after_small_increment(hc + MEMRW_CYCLE_TS as Ts);
        self.as_timestamp()
    }

    // fn add_io(&mut self, port: u16) -> Self::Timestamp {
    //     let VideoTs{ vc, hc } = self.tsc;
    //     let hc = if V::is_contended_line_no_mreq(vc) {
    //         if self.contention.is_contended_address(port) {
    //             let hc = V::contention(hc) + 1;
    //             if port & 1 == 0 { // C:1, C:3
    //                 V::contention(hc) + (IO_CYCLE_TS - 1) as Ts
    //             }
    //             else { // C:1, C:1, C:1, C:1
    //                 let mut hc1 = hc;
    //                 for _ in 1..IO_CYCLE_TS {
    //                     hc1 = V::contention(hc1) + 1;
    //                 }
    //                 hc1
    //             }
    //         }
    //         else {
    //             if port & 1 == 0 { // N:1 C:3
    //                 V::contention(hc + 1) + (IO_CYCLE_TS - 1) as Ts
    //             }
    //             else { // N:4
    //                 hc + IO_CYCLE_TS as Ts
    //             }
    //         }
    //     }
    //     else { // N:4
    //         hc + IO_CYCLE_TS as Ts
    //     };
    //     self.vts.set_hc_after_small_increment(hc);
    //     Self::new(vc, hc - 1).as_timestamp() // data read at last cycle
    // }

    fn add_io(&mut self, port: u16) -> Self::Timestamp {
        let VideoTs{ vc, mut hc } = self.as_timestamp();
        // if port == 0x7ffd {
        //     println!("0x{:04x}: {} {:?}", port, self.as_tstates(), self.tsc);
        // }
        let hc1 = if V::is_contended_line_no_mreq(vc) {
            ula_io_contention!(self.contention, port, hc, V::contention)
            // if is_contended_address(self.contention_mask, port) {
            //     hc = V::contention(hc) + IO_IORQ_LOW_TS as Ts;
            //     if port & 1 == 0 { // C:1, C:3
            //         V::contention(hc) + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
            //     }
            //     else { // C:1, C:1, C:1, C:1
            //         let mut hc1 = hc;
            //         for _ in 0..(IO_CYCLE_TS - IO_IORQ_LOW_TS) {
            //             hc1 = V::contention(hc1) + 1;
            //         }
            //         hc1
            //     }
            // }
            // else {
            //     hc += IO_IORQ_LOW_TS as Ts;
            //     if port & 1 == 0 { // N:1 C:3
            //         V::contention(hc) + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
            //     }
            //     else { // N:4
            //         hc + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
            //     }
            // }
        }
        else {
            hc += IO_IORQ_LOW_TS as Ts;
            hc + (IO_CYCLE_TS - IO_IORQ_LOW_TS) as Ts
        };
        let mut vtsc = *self;
        vtsc.vts.set_hc_after_small_increment(hc);
        self.vts.set_hc_after_small_increment(hc1);
        vtsc.as_timestamp()
    }

    fn add_wait_states(&mut self, _bus: u16, wait_states: NonZeroU16) {
        let ws = wait_states.get();
        if ws > WAIT_STATES_THRESHOLD {
            // emulate hanging the Spectrum
            self.vc += HALT_VC_THRESHOLD;
        }
        else if ws < V::HTS_COUNT as u16 {
            self.vts.set_hc_after_small_increment(self.hc + ws as i16);
        }
        else {
            *self += ws as u32;
        }
    }

    #[inline(always)]
    fn as_timestamp(&self) -> Self::Timestamp {
        ***self
    }
}

impl<V> Default for VFrameTs<V> {
    fn default() -> Self {
        VFrameTs::from(VideoTs::default())
    }
}

impl<V> Clone for VFrameTs<V> {
    fn clone(&self) -> Self {
        VFrameTs::from(self.ts)
    }
}

impl<V> Hash for VFrameTs<V> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.ts.hash(state);
    }
}

impl<V> Eq for VFrameTs<V> {}

impl<V> PartialEq for VFrameTs<V> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.ts == other.ts
    }
}

impl<V> Ord for VFrameTs<V> {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> Ordering {
        self.ts.cmp(other)
    }
}

impl<V> PartialOrd for VFrameTs<V> {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<V: VideoFrame> From<VFrameTs<V>> for FTs {
    #[inline(always)]
    fn from(vfts: VFrameTs<V>) -> FTs {
        VFrameTs::into_tstates(vfts)
    }
}

impl<V: VideoFrame> TryFrom<FTs> for VFrameTs<V> {
    type Error = &'static str;

    fn try_from(ts: FTs) -> Result<Self, Self::Error> {
        VFrameTs::try_from_tstates(ts).ok_or_else(
            || "out of range video timestamp conversion attempted")
    }
}

impl<V> From<VFrameTs<V>> for VideoTs {
    #[inline(always)]
    fn from(vfts: VFrameTs<V>) -> VideoTs {
        vfts.ts
    }
}

impl<V> From<VideoTs> for VFrameTs<V> {
    /// Returns a [VFrameTs] from the given [VideoTs].
    /// A returned `VFrameTs` is not being normalized.
    ///
    /// # Panics
    ///
    /// Panics when the given `ts` overflows the capacity of [VideoTs].
    #[inline(always)]
    fn from(ts: VideoTs) -> Self {
        VFrameTs { ts, _vframe: PhantomData }
    }
}

impl<V, C> From<VFrameTsCounter<V, C>> for VideoTs {
    #[inline(always)]
    fn from(vftsc: VFrameTsCounter<V, C>) -> VideoTs {
        vftsc.vts.ts
    }
}

impl<V, C> From<VFrameTsCounter<V, C>> for VFrameTs<V> {
    #[inline(always)]
    fn from(vftsc: VFrameTsCounter<V, C>) -> VFrameTs<V> {
        vftsc.vts
    }
}

impl<V> Deref for VFrameTs<V> {
    type Target = VideoTs;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.ts
    }
}

impl<V> DerefMut for VFrameTs<V> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.ts
    }
}

impl<V, C> Deref for VFrameTsCounter<V, C> {
    type Target = VFrameTs<V>;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        &self.vts
    }
}

impl<V, C> DerefMut for VFrameTsCounter<V, C> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.vts
    }
}