mlv 0.1.1

Utilities for reading and writing Magic Lantern MLV files
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
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
//! Each frame begins with 4 magic bytes defining the type of the frame,
//! followed by the 32-bit size of the frame, 64-bit timestamp and the frame data.
//!
//! Frames can be iteratively read using [`Frame::read`] or [`Frame::read_position`].

use crate::Fraction;

use packbytes::{ByteArray, FromBytes, ToBytes};

use std::io;

/// A frame in the MLV file.
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Frame<A = Vec<u8>> {
    /// The frame header.
    pub header: Header,
    /// Additional payload.
    pub payload: A,
}

/// A struct storing position and length of an MLV frame payload.
/// The payload may optionally be padded at the start or the end, so that it is aligned.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PayloadPosition {
    /// Position of the payload within the file.
    pub position: u64,
    /// The length of the full (unpadded) payload.
    pub full_length: usize,
    /// The padding at the start.
    pub padding_start: usize,
    /// The padding at the end.
    pub padding_end: usize,
}

/// MLV frame header.
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Header {
    /// Video data
    Video(Video),
    /// Audio data
    Audio(Audio),
    /// Raw info
    RawInfo(RawInfo),
    /// Raw capture info
    RawCapture(RawCapture),
    /// Waveform info
    WavInfo(WavInfo),
    /// Exposure info
    Exposure(Exposure),
    /// Lens info
    Lens(Lens),
    /// Extended lens info
    ExtendedLens(ExtendedLens),
    /// Real time clock info
    Rtci(Rtci),
    /// Camer identification
    Idnt(Idnt),
    /// Frame cross reference
    Xref(XrefHeader),
    /// Info string
    Info,
    /// Dual ISO info
    DualIso(DualIso),
    /// A marker set when recording
    Marker(Marker),
    /// Picture style info
    Style(Style),
    /// Electronic level info
    ElectronicLevel(ElectronicLevel),
    /// White balance info
    WhiteBalance(WhiteBalance),
    /// Debug info
    Debug(DebugHeader),
    /// Version info
    Version,
    /// Dark frame info
    Dark(Dark),
    /// Unknown header, along with its 4 magic bytes
    Unknown([u8; 4]),
}

/// Constants defined for each MlvHeader
pub trait MlvHeader {
    /// Magic bytes that denote this type of the header
    const MAGIC_BYTES: [u8; 4];
}

/// Video data.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Video {
    /// The number of the frame.
    pub number: u32,
    /// From which sensor row the frame was cropped (8x blocks).
    pub crop_x: u16,
    /// From which sensor column the frame was cropped (2x blocks).
    pub crop_y: u16,
    /// From which sensor row the frame was cropped (1x blocks).
    pub pan_x: u16,
    /// From which sensor column the frame was cropped (1x blocks).
    pub pan_y: u16,
}

impl MlvHeader for Video {
    const MAGIC_BYTES: [u8; 4] = *b"VIDF";
}

/// Audio data.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Audio {
    /// The number of the frame.
    pub number: u32,
}

impl MlvHeader for Audio {
    const MAGIC_BYTES: [u8; 4] = *b"AUDF";
}

/// Detailed raw format information.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RawInfo {
    /// Configured video width, may differ from the payload resolution.
    pub res_x: u16,
    /// Configured video height, may differ from the payload resolution.
    pub res_y: u16,
    /// RAW info API version.
    pub api_version: u32,
    /// Pointer to the buffer, unused in the MLV file.
    pub buffer: u32,
    /// Raw height.
    pub height: u32,
    /// Raw width.
    pub width: u32,
    /// Raw pitch.
    pub pitch: i32,
    /// Raw frame size.
    pub frame_size: u32,
    /// The number of bits per pixel.
    pub bits_per_pixel: u32,
    /// Autodetected black level.
    pub black_level: i32,
    /// White level.
    pub white_level: i32,
    /// DNG JPEG top left corner.
    pub origin: [i32; 2],
    /// DNG JPEG size.
    pub size: [i32; 2],
    /// DNG active sensor area.
    pub dng_active_area: [i32; 4],
    /// DNG exposure bias.
    pub exposure_bias: [i32; 2],
    /// DNG Color Filter Array pattern.
    pub cfa_pattern: i32,
    /// DNG calibration_illuminant.
    pub calibration_illuminant: i32,
    /// DNG color matrix.
    /// To convert to a matrix of floats, use
    /// ```ignore
    /// let matrix: [f32; 9] = raw_info.color_matrix.map(Into::into);
    /// ```
    pub color_matrix: [Fraction; 9],
    /// EV times 100.
    pub dynamic_range: i32,
}

impl MlvHeader for RawInfo {
    const MAGIC_BYTES: [u8; 4] = *b"RAWI";
}

/// Raw image capture information.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RawCapture {
    /// Sensor x resolution.
    pub sensor_x: u16,
    /// Sensor y resolution.
    pub sensor_y: u16,
    /// Sensor crop factor times 100.
    pub sensor_crop: u16,
    /// Reserved for future use.
    pub reserved: u16,
    /// Column binning (can be 1 or 3).
    pub binning_x: u8,
    /// Column skipping (so far 0 everywhere).
    pub skipping_x: u8,
    /// Row binning (can be 1, 3 or 5).
    pub binning_y: u8,
    /// Row skipping (can be 0, 2 or 4).
    pub skipping_y: u8,
    /// Crop x offset - optional.
    pub offset_x: i16,
    /// Crop y offset - optional.
    pub offset_y: i16,
}

impl MlvHeader for RawCapture {
    const MAGIC_BYTES: [u8; 4] = *b"RAWC";
}

/// Audio format details compatible with RIFF
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WavInfo {
    /// 1 = Integer PCM, 5 = alaw, 7 = mulaw
    pub format: u16,
    /// Audio channel count.
    pub channels: u16,
    /// Audio sampling rate.
    pub sample_rate: u32,
    /// Audio data rate.
    pub bytes_per_second: u32,
    /// See RIFF WAV header description.
    pub block_align: u16,
    /// Bits per sample.
    pub bits_per_sample: u16,
}

impl MlvHeader for WavInfo {
    const MAGIC_BYTES: [u8; 4] = *b"WAVI";
}

/// Exposure information (ISO, shutter)
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Exposure {
    /// 0 = manual, 1 = auto
    pub iso_mode: u32,
    /// Camera delivered ISO value.
    pub iso_value: u32,
    /// ISO obtained by hardware amplification.
    pub iso_analog: u32,
    /// Digital ISO gain (1024 = 1EV).
    pub digital_gain: u32,
    /// Exposure time in microseconds.
    pub shutter_value: u64,
}

impl MlvHeader for Exposure {
    const MAGIC_BYTES: [u8; 4] = *b"EXPO";
}

/// Lens information.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Lens {
    /// Focal lenght in mm.
    pub focal_len: u16,
    /// Focal distance in mm ([`u16::MAX`] = infinite).
    pub focal_dist: u16,
    /// f-number times 100.
    pub aperture: u16,
    /// Lens stabilization, 0 = off, 1 = on.
    pub stabilizer_mode: u8,
    /// Autofocus, 0 = off, 1 = on.
    pub autofocus_mode: u8,
    /// Lens flags.
    pub flags: u32,
    /// Lens ID
    pub lens_id: u32,
    /// Full lens C string.
    pub lens_name: [u8; 32],
    /// Ful lens serial number.
    pub lens_serial: [u8; 32],
}

impl MlvHeader for Lens {
    const MAGIC_BYTES: [u8; 4] = *b"LENS";
}

/// Extended lens block with longer lens name and optional fields.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ExtendedLens {
    /// The shortest focal lenght in mm.
    pub focal_len_min: u16,
    /// The longest focal lenght in mm.
    pub focal_len_max: u16,
    /// The lowest f-number times 100.
    pub aperture_min: u16,
    /// The highest f-number times 100.
    pub aperture_max: u16,
    /// Lens internal version, if available.
    pub verion: u32,
    /// Extender information, if provided by the camera.
    pub extender_info: u8,
    /// Capability information, if provided by the camera.
    pub capabilities: u8,
    /// When not zero, the lens was communicating with the camera.
    pub chipped: u8,
}

impl MlvHeader for ExtendedLens {
    const MAGIC_BYTES: [u8; 4] = *b"ELNS";
}

/// Real time clock metadata.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rtci {
    /// Seconds
    pub sec: u16,
    /// Minute
    pub min: u16,
    /// Hour
    pub hour: u16,
    /// Day of month
    pub mday: u16,
    /// Month
    pub mon: u16,
    /// Year since 1900
    pub year: u16,
    /// Day of week
    pub wday: u16,
    /// Day of year
    pub yday: u16,
    /// Is daylinght saving?
    pub is_dst: u16,
    /// GMT offset
    pub gmtoff: u16,
    /// Time zone C string
    pub zone: [u8; 8],
}

impl MlvHeader for Rtci {
    const MAGIC_BYTES: [u8; 4] = *b"RTCI";
}

/// Camera identification.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Idnt {
    /// Camera name C string.
    pub camera_name: [u8; 32],
    /// Camera model, see [`super::Camera`].
    pub camera_model: u32,
    /// Camera serial number.
    pub camera_serial: [u8; 32],
}

impl MlvHeader for Idnt {
    const MAGIC_BYTES: [u8; 4] = *b"IDNT";
}

/// Frame clross reference.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Xref {
    /// The file number.
    pub filenumber: u16,
    /// Reserved for future use.
    pub empty: u8,
    /// Frame type bit mask, 0x1 = video, 0x2 = audio.
    pub frame_type: u8,
    /// The file offset at which the frame is stored.
    pub frame_offset: u64,
}

/// The cross reference header optionally added in post processing when out of order data is present.
/// The payload is an array of [`Xref`].
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct XrefHeader {
    /// Frame type bit mask, 0x1 = video, 0x2 = audio.
    pub frame_type: u8,
    /// The number of entries in the payload.
    pub entry_count: u32,
}

impl MlvHeader for XrefHeader {
    const MAGIC_BYTES: [u8; 4] = *b"XREF";
}

/// An user definable info string.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Info;

impl MlvHeader for Info {
    const MAGIC_BYTES: [u8; 4] = *b"INFO";
}

/// Dual ISO information.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DualIso {
    /// Bitmask, 0x1 = off, 0x1 = odd lines, 0x2 = even lines.
    pub dual_mode: u32,
    /// The ISO value.
    pub iso_value: u32,
}

impl MlvHeader for DualIso {
    const MAGIC_BYTES: [u8; 4] = *b"DISO";
}

/// Markers set by the user while recording.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Marker {
    /// The marker type.
    pub mark_type: u32,
}

impl MlvHeader for Marker {
    const MAGIC_BYTES: [u8; 4] = *b"MARK";
}

/// Picture style information.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Style {
    /// Style ID
    pub pic_style_id: u32,
    /// Contrast
    pub contrast: i32,
    /// Sharpness
    pub sharpness: i32,
    /// Saturation
    pub saturation: i32,
    /// Color tone
    pub colortone: i32,
    /// Picture style name C string
    pub pic_style_name: [u8; 16],
}

impl MlvHeader for Style {
    const MAGIC_BYTES: [u8; 4] = *b"STYL";
}

/// Picture style information
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ElectronicLevel {
    /// Degrees x 100
    pub roll: u32,
    /// 10.00 degrees
    pub pitch: u32,
}

impl MlvHeader for ElectronicLevel {
    const MAGIC_BYTES: [u8; 4] = *b"ELVL";
}

/// White balance info
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct WhiteBalance {
    /// White balance mode.
    pub mode: u32,
    /// White balance Kelvin value
    pub kelvin: u32,
    /// Red gain
    pub gain_r: u32,
    /// Green gain
    pub gain_g: u32,
    /// Blue gain
    pub gain_b: u32,
    /// White balance shift
    pub gm: u32,
    /// ?, range: `-9..=9`
    pub ba: u32,
}

impl MlvHeader for WhiteBalance {
    const MAGIC_BYTES: [u8; 4] = *b"WBAL";
}

/// Debug message for development use.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DebugHeader {
    /// Debug data type (0 = text log).
    pub info_type: u32,
    /// Debug message lenght within the payload.
    pub len: u32,
}

impl MlvHeader for DebugHeader {
    const MAGIC_BYTES: [u8; 4] = *b"DEBG";
}

/// Version information.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Version;

impl MlvHeader for Version {
    const MAGIC_BYTES: [u8; 4] = *b"VERS";
}

/// Essential settings active while recording and actual averaged frame data.
#[derive(Clone, Copy, Debug, FromBytes, ToBytes)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Dark {
    /// Number of samples averaged.
    pub samples_averaged: u32,
    /// Camera model.
    pub camera_model: u32,
    /// Dark frame width.
    pub res_x: u16,
    /// Darg frame height.
    pub res_y: u16,
    /// Raw buffer width.
    pub raw_width: u32,
    /// Raw buffer height.
    pub ram_height: u32,
    /// Bits per pixel.
    pub bits_per_pixel: u32,
    /// Autodetected black level.
    pub black_level: u32,
    /// White level.
    pub white_level: u32,
    /// Frames per second.
    pub fps: Fraction,
    /// ISO mode, 0 = manual, 1 = auto
    pub iso_mode: u32,
    /// Camera delivered ISO value.
    pub iso_value: u32,
    /// Value obtained by hardware amplification.
    pub iso_analog: u32,
    /// Digital ISO gain.
    pub digital_gain: u32,
    /// Exposure time in microseconds.
    pub shutter_value: u64,
    /// Column binning.
    pub binning_x: u8,
    /// Column skipping.
    pub skipping_x: u8,
    /// Row binning.
    pub binning_y: u8,
    /// Row skipping.
    pub skipping_y: u8,
}

impl MlvHeader for Dark {
    const MAGIC_BYTES: [u8; 4] = *b"DARK";
}

/// Read the header and decrease its length from the number of remaining bytes.
#[inline]
fn read_head<H: FromBytes, R: io::Read>(reader: &mut R, rem: &mut usize) -> io::Result<H> {
    let headsize = H::Bytes::SIZE;
    if *rem < headsize {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "Frame size too small",
        ));
    }
    *rem -= headsize;
    H::read_packed(reader)
}

impl Frame {
    /// Read the next frame from the reader, along with its timestamp.
    pub fn read<R: io::Read>(reader: &mut R) -> io::Result<(Self, u64)> {
        let mut magic = [0; 4];
        reader.read_exact(&mut magic)?;

        let size = u32::read_packed(reader)? as usize;
        if size < 16 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Frame size too small",
            ));
        }
        let timestamp = u64::read_packed(reader)?;
        // First 16 bytes read as magic bytes, size and timestamp
        let mut rem = size - 16;
        let mut payload_size = None;

        let header = match magic {
            Video::MAGIC_BYTES => {
                let header = read_head::<Video, _>(reader, &mut rem)?.into();
                let frame_space = u32::read_packed(reader)? as usize;
                if (frame_space + 4) > rem {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Video frame space too large",
                    ));
                }
                let mut throwaway = vec![0; frame_space];
                reader.read_exact(&mut throwaway)?;
                rem = rem.saturating_sub(frame_space + 4);
                header
            }
            Audio::MAGIC_BYTES => {
                let header = read_head::<Audio, _>(reader, &mut rem)?.into();
                let frame_space = u32::read_packed(reader)? as usize;
                if (frame_space + 4) > rem {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Audio frame space too large",
                    ));
                }
                let mut throwaway = vec![0; frame_space];
                reader.read_exact(&mut throwaway)?;
                rem = rem.saturating_sub(frame_space + 4);
                header
            }
            RawInfo::MAGIC_BYTES => read_head::<RawInfo, _>(reader, &mut rem)?.into(),
            RawCapture::MAGIC_BYTES => read_head::<RawCapture, _>(reader, &mut rem)?.into(),
            WavInfo::MAGIC_BYTES => read_head::<WavInfo, _>(reader, &mut rem)?.into(),
            Exposure::MAGIC_BYTES => read_head::<Exposure, _>(reader, &mut rem)?.into(),
            Lens::MAGIC_BYTES => read_head::<Lens, _>(reader, &mut rem)?.into(),
            ExtendedLens::MAGIC_BYTES => read_head::<ExtendedLens, _>(reader, &mut rem)?.into(),
            Rtci::MAGIC_BYTES => read_head::<Rtci, _>(reader, &mut rem)?.into(),
            Idnt::MAGIC_BYTES => read_head::<Idnt, _>(reader, &mut rem)?.into(),
            XrefHeader::MAGIC_BYTES => read_head::<XrefHeader, _>(reader, &mut rem)?.into(),
            Info::MAGIC_BYTES => Header::Info,
            DualIso::MAGIC_BYTES => read_head::<DualIso, _>(reader, &mut rem)?.into(),
            Marker::MAGIC_BYTES => read_head::<Marker, _>(reader, &mut rem)?.into(),
            Style::MAGIC_BYTES => read_head::<Style, _>(reader, &mut rem)?.into(),
            ElectronicLevel::MAGIC_BYTES => {
                read_head::<ElectronicLevel, _>(reader, &mut rem)?.into()
            }
            WhiteBalance::MAGIC_BYTES => read_head::<WhiteBalance, _>(reader, &mut rem)?.into(),
            DebugHeader::MAGIC_BYTES => {
                let header = read_head::<Dark, _>(reader, &mut rem)?.into();
                payload_size = Some(u32::read_packed(reader)? as usize);
                rem = rem.saturating_sub(4);
                header
            }
            Version::MAGIC_BYTES => {
                payload_size = Some(u32::read_packed(reader)? as usize);
                rem = rem.saturating_sub(4);
                Header::Version
            }
            Dark::MAGIC_BYTES => read_head::<Dark, _>(reader, &mut rem)?.into(),
            _ => Header::Unknown(magic),
        };

        let payload_size = payload_size.unwrap_or(rem);
        if payload_size > rem {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Declared data length too large",
            ));
        }

        let mut payload = vec![0; payload_size];
        reader.read_exact(&mut payload)?;

        if payload_size < rem {
            let mut r = rem - payload_size;
            // There should be a difference only if the payload is not aligned.
            let mut buf = [0; 4];
            while r > 4 {
                reader.read_exact(&mut buf)?;
                r -= 4;
            }
            reader.read_exact(&mut buf[..r])?;
        }
        Ok((Frame { header, payload }, timestamp))
    }
}

impl Frame<PayloadPosition> {
    /// Read the next frame from the reader, along with its timestamp.
    pub fn read_position<R: io::Read + io::Seek>(reader: &mut R) -> io::Result<(Self, u64)> {
        let mut magic = [0; 4];
        reader.read_exact(&mut magic)?;

        let size = u32::read_packed(reader)? as usize;
        if size < 16 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Frame size too small",
            ));
        }
        let timestamp = u64::read_packed(reader)?;
        // First 16 bytes read as magic bytes, size and timestamp
        let mut rem = size - 16;
        let mut padding_start = 0;
        let mut payload_size = None;

        let header = match magic {
            Video::MAGIC_BYTES => {
                let header = read_head::<Video, _>(reader, &mut rem)?.into();
                let frame_space = u32::read_packed(reader)? as usize;
                if (frame_space + 4) > rem {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Video frame space too large",
                    ));
                }
                rem = rem.saturating_sub(4);
                padding_start = frame_space;
                header
            }
            Audio::MAGIC_BYTES => {
                let header = read_head::<Audio, _>(reader, &mut rem)?.into();
                let frame_space = u32::read_packed(reader)? as usize;
                if (frame_space + 4) > rem {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "Audio frame space too large",
                    ));
                }
                rem = rem.saturating_sub(4);
                padding_start = frame_space;
                header
            }
            RawInfo::MAGIC_BYTES => read_head::<RawInfo, _>(reader, &mut rem)?.into(),
            RawCapture::MAGIC_BYTES => read_head::<RawCapture, _>(reader, &mut rem)?.into(),
            WavInfo::MAGIC_BYTES => read_head::<WavInfo, _>(reader, &mut rem)?.into(),
            Exposure::MAGIC_BYTES => read_head::<Exposure, _>(reader, &mut rem)?.into(),
            Lens::MAGIC_BYTES => read_head::<Lens, _>(reader, &mut rem)?.into(),
            ExtendedLens::MAGIC_BYTES => read_head::<ExtendedLens, _>(reader, &mut rem)?.into(),
            Rtci::MAGIC_BYTES => read_head::<Rtci, _>(reader, &mut rem)?.into(),
            Idnt::MAGIC_BYTES => read_head::<Idnt, _>(reader, &mut rem)?.into(),
            XrefHeader::MAGIC_BYTES => read_head::<XrefHeader, _>(reader, &mut rem)?.into(),
            Info::MAGIC_BYTES => Header::Info,
            DualIso::MAGIC_BYTES => read_head::<DualIso, _>(reader, &mut rem)?.into(),
            Marker::MAGIC_BYTES => read_head::<Marker, _>(reader, &mut rem)?.into(),
            Style::MAGIC_BYTES => read_head::<Style, _>(reader, &mut rem)?.into(),
            ElectronicLevel::MAGIC_BYTES => {
                read_head::<ElectronicLevel, _>(reader, &mut rem)?.into()
            }
            WhiteBalance::MAGIC_BYTES => read_head::<WhiteBalance, _>(reader, &mut rem)?.into(),
            DebugHeader::MAGIC_BYTES => {
                let header = read_head::<Dark, _>(reader, &mut rem)?.into();
                payload_size = Some(u32::read_packed(reader)? as usize);
                rem = rem.saturating_sub(4);
                header
            }
            Version::MAGIC_BYTES => {
                payload_size = Some(u32::read_packed(reader)? as usize);
                rem = rem.saturating_sub(4);
                Header::Version
            }
            Dark::MAGIC_BYTES => read_head::<Dark, _>(reader, &mut rem)?.into(),
            _ => Header::Unknown(magic),
        };

        let payload_size = payload_size.unwrap_or(rem);
        if payload_size > rem {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Declared data length too large",
            ));
        }

        let padding_end = rem - payload_size;
        let full_length = rem;
        let position = reader.stream_position()?;
        let payload = PayloadPosition {
            position,
            full_length,
            padding_start,
            padding_end,
        };
        Ok((Frame { header, payload }, timestamp))
    }
}

/// Write the header and add its length to the number written bytes.
#[inline]
fn write_head<H, W>(h: H, writer: &mut W, size: &mut usize, ts: u64) -> io::Result<()>
where
    H: MlvHeader + ToBytes,
    W: io::Write,
{
    let headsize = H::Bytes::SIZE;
    *size += headsize;
    writer.write_all(&H::MAGIC_BYTES)?;
    (*size as u32).write_packed(writer)?;
    ts.write_packed(writer)?;
    h.write_packed(writer)
}

impl<A: AsRef<[u8]>> Frame<A> {
    /// Write this frame to the writer with the provided timestamp.
    pub fn write<W: io::Write>(&self, writer: &mut W, timestamp: u64) -> io::Result<()> {
        let payload = self.payload.as_ref();
        // payload length + magic bytes + 32-bit size + 64-bit timestamp
        let mut written_size = payload.len() + 16;
        let mut padding_len = 0;

        match self.header {
            Header::Video(h) => {
                let headsize = <Video as ToBytes>::Bytes::SIZE;
                written_size += headsize;
                writer.write_all(&Video::MAGIC_BYTES)?;
                (written_size as u32 + 4).write_packed(writer)?;
                timestamp.write_packed(writer)?;
                // beginning frame space
                h.write_packed(writer)?;
                0_u32.write_packed(writer)?
            }
            Header::Audio(h) => {
                let headsize = <Audio as ToBytes>::Bytes::SIZE;
                written_size += headsize;
                writer.write_all(&Audio::MAGIC_BYTES)?;
                (written_size as u32 + 4).write_packed(writer)?;
                timestamp.write_packed(writer)?;
                // beginning frame space
                h.write_packed(writer)?;
                0_u32.write_packed(writer)?
            }
            Header::RawInfo(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::RawCapture(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::WavInfo(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Exposure(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Lens(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::ExtendedLens(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Rtci(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Idnt(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Xref(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Info => {
                writer.write_all(&Info::MAGIC_BYTES)?;
                (written_size as u32).write_packed(writer)?;
                timestamp.write_packed(writer)?;
            }
            Header::DualIso(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Marker(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Style(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::ElectronicLevel(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::WhiteBalance(h) => write_head(h, writer, &mut written_size, timestamp)?,
            Header::Debug(h) => {
                padding_len = (4 - (written_size % 4)) % 4;
                written_size += padding_len;
                write_head(h, writer, &mut written_size, timestamp)?;
            }
            Header::Version => {
                padding_len = (4 - (written_size % 4)) % 4;
                written_size += padding_len;
                writer.write_all(&Version::MAGIC_BYTES)?;
                (written_size as u32).write_packed(writer)?;
                timestamp.write_packed(writer)?;
            }
            Header::Dark(h) => write_head(h, writer, &mut written_size, timestamp)?,
            _ => {
                writer.write_all(b"NULL")?;
                (written_size as u32).write_packed(writer)?;
                timestamp.write_packed(writer)?;
            }
        };

        writer.write_all(payload)?;
        writer.write_all(&vec![0; padding_len])
    }
}

impl PayloadPosition {
    /// Length of the payload minus the padding.
    pub const fn length(&self) -> usize {
        self.full_length - self.padding_start - self.padding_end
    }

    /// The start of the actual content after the padding.
    pub const fn start(&self) -> u64 {
        self.position + self.padding_start as u64
    }
}

impl Header {
    /// Return the magic bytes corresponding to each variant of the header.
    #[inline]
    pub const fn magic_bytes(&self) -> [u8; 4] {
        match *self {
            Header::Video(_) => Video::MAGIC_BYTES,
            Header::Audio(_) => Audio::MAGIC_BYTES,
            Header::RawInfo(_) => RawInfo::MAGIC_BYTES,
            Header::RawCapture(_) => RawCapture::MAGIC_BYTES,
            Header::WavInfo(_) => WavInfo::MAGIC_BYTES,
            Header::Exposure(_) => Exposure::MAGIC_BYTES,
            Header::Lens(_) => Lens::MAGIC_BYTES,
            Header::ExtendedLens(_) => ExtendedLens::MAGIC_BYTES,
            Header::Rtci(_) => Rtci::MAGIC_BYTES,
            Header::Idnt(_) => Idnt::MAGIC_BYTES,
            Header::Xref(_) => XrefHeader::MAGIC_BYTES,
            Header::Info => Info::MAGIC_BYTES,
            Header::DualIso(_) => DualIso::MAGIC_BYTES,
            Header::Marker(_) => Marker::MAGIC_BYTES,
            Header::Style(_) => Style::MAGIC_BYTES,
            Header::ElectronicLevel(_) => ElectronicLevel::MAGIC_BYTES,
            Header::WhiteBalance(_) => WhiteBalance::MAGIC_BYTES,
            Header::Debug(_) => DebugHeader::MAGIC_BYTES,
            Header::Version => Version::MAGIC_BYTES,
            Header::Dark(_) => Dark::MAGIC_BYTES,
            Header::Unknown(mb) => mb,
        }
    }

    /// The size of the header, excluding the magic bytes, length, timestamp
    /// and possibly 32 bits of size after the header
    #[inline]
    pub const fn size(&self) -> usize {
        match *self {
            Header::Video(_) => <Video as ToBytes>::Bytes::SIZE,
            Header::Audio(_) => <Audio as ToBytes>::Bytes::SIZE,
            Header::RawInfo(_) => <RawInfo as ToBytes>::Bytes::SIZE,
            Header::RawCapture(_) => <RawCapture as ToBytes>::Bytes::SIZE,
            Header::WavInfo(_) => <WavInfo as ToBytes>::Bytes::SIZE,
            Header::Exposure(_) => <Exposure as ToBytes>::Bytes::SIZE,
            Header::Lens(_) => <Lens as ToBytes>::Bytes::SIZE,
            Header::ExtendedLens(_) => <ExtendedLens as ToBytes>::Bytes::SIZE,
            Header::Rtci(_) => <Rtci as ToBytes>::Bytes::SIZE,
            Header::Idnt(_) => <Idnt as ToBytes>::Bytes::SIZE,
            Header::Xref(_) => <XrefHeader as ToBytes>::Bytes::SIZE,
            Header::Info => <Info as ToBytes>::Bytes::SIZE,
            Header::DualIso(_) => <DualIso as ToBytes>::Bytes::SIZE,
            Header::Marker(_) => <Marker as ToBytes>::Bytes::SIZE,
            Header::Style(_) => <Style as ToBytes>::Bytes::SIZE,
            Header::ElectronicLevel(_) => <ElectronicLevel as ToBytes>::Bytes::SIZE,
            Header::WhiteBalance(_) => <WhiteBalance as ToBytes>::Bytes::SIZE,
            Header::Debug(_) => <DebugHeader as ToBytes>::Bytes::SIZE,
            Header::Version => <Version as ToBytes>::Bytes::SIZE,
            Header::Dark(_) => <Dark as ToBytes>::Bytes::SIZE,
            Header::Unknown(_) => 0,
        }
    }
}

impl Video {
    /// Create a frame header with the provided frame number, 0 crop and 0 padding.
    pub const fn from_frame_number(number: u32) -> Self {
        Self {
            number,
            crop_x: 0,
            crop_y: 0,
            pan_x: 0,
            pan_y: 0,
        }
    }
}

impl From<Video> for Header {
    fn from(h: Video) -> Header {
        Header::Video(h)
    }
}

impl From<Audio> for Header {
    fn from(h: Audio) -> Header {
        Header::Audio(h)
    }
}

impl From<RawInfo> for Header {
    fn from(h: RawInfo) -> Header {
        Header::RawInfo(h)
    }
}

impl From<RawCapture> for Header {
    fn from(h: RawCapture) -> Header {
        Header::RawCapture(h)
    }
}

impl From<WavInfo> for Header {
    fn from(h: WavInfo) -> Header {
        Header::WavInfo(h)
    }
}

impl From<Exposure> for Header {
    fn from(h: Exposure) -> Header {
        Header::Exposure(h)
    }
}

impl From<Lens> for Header {
    fn from(h: Lens) -> Header {
        Header::Lens(h)
    }
}

impl From<ExtendedLens> for Header {
    fn from(h: ExtendedLens) -> Header {
        Header::ExtendedLens(h)
    }
}

impl From<Rtci> for Header {
    fn from(h: Rtci) -> Header {
        Header::Rtci(h)
    }
}

impl From<Idnt> for Header {
    fn from(h: Idnt) -> Header {
        Header::Idnt(h)
    }
}

impl From<XrefHeader> for Header {
    fn from(h: XrefHeader) -> Header {
        Header::Xref(h)
    }
}

impl From<DualIso> for Header {
    fn from(h: DualIso) -> Header {
        Header::DualIso(h)
    }
}

impl From<Marker> for Header {
    fn from(h: Marker) -> Header {
        Header::Marker(h)
    }
}

impl From<Style> for Header {
    fn from(h: Style) -> Header {
        Header::Style(h)
    }
}

impl From<ElectronicLevel> for Header {
    fn from(h: ElectronicLevel) -> Header {
        Header::ElectronicLevel(h)
    }
}

impl From<WhiteBalance> for Header {
    fn from(h: WhiteBalance) -> Header {
        Header::WhiteBalance(h)
    }
}

impl From<DebugHeader> for Header {
    fn from(h: DebugHeader) -> Header {
        Header::Debug(h)
    }
}

impl From<Dark> for Header {
    fn from(h: Dark) -> Header {
        Header::Dark(h)
    }
}