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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
// Module for parsing ISO Base Media Format aka video/mp4 streams.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

/// Basic ISO box structure.
pub struct BoxHeader {
    /// Four character box type
    pub name: u32,
    /// Size of the box in bytes
    pub size: u64,
    /// Offset to the start of the contained data (or header size).
    pub offset: u64,
}

/// File type box 'ftyp'.
pub struct FileTypeBox {
    name: u32,
    size: u64,
    major_brand: u32,
    minor_version: u32,
    compatible_brands: Vec<u32>,
}

/// Movie header box 'mvhd'.
pub struct MovieHeaderBox {
    pub name: u32,
    pub size: u64,
    pub timescale: u32,
    pub duration: u64,
    // Ignore other fields.
}

/// Track header box 'tkhd'
pub struct TrackHeaderBox {
    pub name: u32,
    pub size: u64,
    pub track_id: u32,
    pub enabled: bool,
    pub duration: u64,
    pub width: u32,
    pub height: u32,
}

/// Edit list box 'elst'
pub struct EditListBox {
    name: u32,
    size: u64,
    edits: Vec<Edit>,
}

pub struct Edit {
    segment_duration: u64,
    media_time: i64,
    media_rate_integer: i16,
    media_rate_fraction: i16,
}

/// Media header box 'mdhd'
pub struct MediaHeaderBox {
    name: u32,
    size: u64,
    timescale: u32,
    duration: u64,
}

// Chunk offset box 'stco' or 'co64'
pub struct ChunkOffsetBox {
    name: u32,
    size: u64,
    offsets: Vec<u64>,
}

// Sync sample box 'stss'
pub struct SyncSampleBox {
    name: u32,
    size: u64,
    samples: Vec<u32>,
}

// Sample to chunk box 'stsc'
pub struct SampleToChunkBox {
    name: u32,
    size: u64,
    samples: Vec<SampleToChunk>,
}

pub struct SampleToChunk {
    first_chunk: u32,
    samples_per_chunk: u32,
    sample_description_index: u32,
}

// Sample size box 'stsz'
pub struct SampleSizeBox {
    name: u32,
    size: u64,
    sample_size: u32,
    sample_sizes: Vec<u32>,
}

// Time to sample box 'stts'
pub struct TimeToSampleBox {
    name: u32,
    size: u64,
    samples: Vec<Sample>,
}

pub struct Sample {
    sample_count: u32,
    sample_delta: u32,
}

// Handler reference box 'hdlr'
pub struct HandlerBox {
    name: u32,
    size: u64,
    handler_type: u32,
}

// Sample description box 'stsd'
pub struct SampleDescriptionBox {
    name: u32,
    size: u64,
    descriptions: Vec<SampleEntry>,
}

#[allow(dead_code)]
enum SampleEntry {
    Audio {
        data_reference_index: u16,
        channelcount: u16,
        samplesize: u16,
        samplerate: u32,
        esds: ES_Descriptor,
    },
    Video {
        data_reference_index: u16,
        width: u16,
        height: u16,
        avcc: AVCDecoderConfigurationRecord,
    },
}

#[allow(dead_code)]
pub struct AVCDecoderConfigurationRecord {
    data: Vec<u8>,
}

#[allow(non_camel_case_types)]
#[allow(dead_code)]
pub struct ES_Descriptor {
    data: Vec<u8>,
}

/// Internal data structures.
pub struct MediaContext {
    pub tracks: Vec<Track>,
}

enum TrackType {
    Video,
    Audio
}

pub struct Track {
    track_type: TrackType,
}

extern crate byteorder;
use byteorder::{BigEndian, ReadBytesExt};
use std::io::{Read, BufRead, Take};
use std::io::Cursor;
use std::cmp;

/// Parse a box out of a data buffer.
pub fn read_box_header<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<BoxHeader> {
    let size32 = try!(be_u32(src));
    let name = try!(be_u32(src));
    let size = match size32 {
        0 => panic!("unknown box size not implemented"),
        1 => {
            let size64 = try!(be_u64(src));
            assert!(size64 >= 16);
            size64
        },
        2 ... 7 => panic!("invalid box size"),
        _ => size32 as u64,
    };
    let offset = match size32 {
        1 => 4 + 4 + 8,
        _ => 4 + 4,
    };
    assert!(offset <= size);
    Ok(BoxHeader{
      name: name,
      size: size,
      offset: offset,
    })
}

/// Parse the extra header fields for a full box.
fn read_fullbox_extra<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<(u8, u32)> {
    let version = try!(src.read_u8());
    let flags_a = try!(src.read_u8());
    let flags_b = try!(src.read_u8());
    let flags_c = try!(src.read_u8());
    Ok((version, (flags_a as u32) << 16 |
                 (flags_b as u32) <<  8 |
                 (flags_c as u32)))
}

/// Skip over the entire contents of a box.
pub fn skip_box_content<T: BufRead> (src: &mut T, header: &BoxHeader) -> byteorder::Result<usize> {
    skip(src, (header.size - header.offset) as usize)
}

/// Skip over the remaining contents of a box.
pub fn skip_remaining_box_content<T: BufRead> (src: &mut T, header: &BoxHeader) -> byteorder::Result<()> {
    match skip(src, (header.size - header.offset) as usize) {
        Ok(_) | Err(byteorder::Error::UnexpectedEOF) => Ok(()),
        e @ _ => Err(e.err().unwrap())
    }
}

/// Helper to construct a Take over the contents of a box.
fn limit<'a, T: Read>(f: &'a mut T, h: &BoxHeader) -> Take<&'a mut T> {
    f.take(h.size - h.offset)
}

/// Helper to construct a Cursor over the contents of a box.
fn recurse<T: Read>(f: &mut T, h: &BoxHeader, context: &mut MediaContext) -> byteorder::Result<()> {
    use std::error::Error;
    println!("{} -- recursing", h);
    // FIXME: I couldn't figure out how to do this without copying.
    // We use Seek on the Read we return in skip_box_content, but
    // that trait isn't implemented for a Take like our limit()
    // returns. Slurping the buffer and wrapping it in a Cursor
    // functions as a work around.
    let buf: Vec<u8> = f
        .bytes()
        .map(|u| u.unwrap())
        .collect();
    let mut content = Cursor::new(buf);
    loop {
        match read_box(&mut content, context) {
            Ok(_) => {},
            Err(byteorder::Error::UnexpectedEOF) => {
                // byteorder returns EOF at the end of the buffer.
                // This isn't an error for us, just an signal to
                // stop recursion.
                println!("Caught byteorder::Error::UnexpectedEOF");
                break;
            },
            Err(byteorder::Error::Io(e)) => {
                println!("I/O Error '{:?}' reading box: {}",
                         e.kind(), e.description());
                return Err(byteorder::Error::Io(e));
            },
        }
    }
    assert!(content.position() == h.size - h.offset);
    println!("{} -- end", h);
    Ok(())
}

/// Read the contents of a box, including sub boxes.
/// Metadata is accumulated in the passed-through MediaContext struct.
pub fn read_box<T: BufRead>(f: &mut T, context: &mut MediaContext) -> byteorder::Result<()> {
    read_box_header(f).and_then(|h| {
        let mut content = limit(f, &h);
        match &fourcc_to_string(h.name)[..] {
            "ftyp" => {
                let ftyp = try!(read_ftyp(&mut content, &h));
                println!("{}", ftyp);
            },
            "moov" => try!(recurse(&mut content, &h, context)),
            "mvhd" => {
                let mvhd = try!(read_mvhd(&mut content, &h));
                println!("  {}", mvhd);
            },
            "trak" => try!(recurse(&mut content, &h, context)),
            "tkhd" => {
                let tkhd = try!(read_tkhd(&mut content, &h));
                println!("  {}", tkhd);
            },
            "edts" => try!(recurse(&mut content, &h, context)),
            "elst" => {
                let elst = try!(read_elst(&mut content, &h));
                println!("  {}", elst);
            },
            "mdia" => try!(recurse(&mut content, &h, context)),
            "mdhd" => {
                let mdhd = try!(read_mdhd(&mut content, &h));
                println!("  {}", mdhd);
            },
            "minf" => try!(recurse(&mut content, &h, context)),
            "stbl" => try!(recurse(&mut content, &h, context)),
            "stco" => {
                let stco = try!(read_stco(&mut content, &h));
                println!("  {}", stco);
            },
            "co64" => {
                let co64 = try!(read_co64(&mut content, &h));
                println!("  {}", co64);
            },
            "stss" => {
                let stss = try!(read_stss(&mut content, &h));
                println!("  {}", stss);
            },
            "stsc" => {
                let stsc = try!(read_stsc(&mut content, &h));
                println!("  {}", stsc);
            },
            "stsz" => {
                let stsz = try!(read_stsz(&mut content, &h));
                println!("  {}", stsz);
            },
            "stts" => {
                let stts = try!(read_stts(&mut content, &h));
                println!("  {}", stts);
            },
            "hdlr" => {
                let hdlr = try!(read_hdlr(&mut content, &h));
                let track_type = match &fourcc_to_string(hdlr.handler_type)[..] {
                    "vide" => Some(TrackType::Video),
                    "soun" => Some(TrackType::Audio),
                    _ => None
                };
                // Save track types with recognized types.
                match track_type {
                    Some(track_type) =>
                         context.tracks.push(Track { track_type: track_type }),
                    None => println!("unknown track type!"),
                };
            },
            "stsd" => {
                let track = &context.tracks[context.tracks.len() - 1];
                let stsd = try!(read_stsd(&mut content, &h, &track));
                println!("  {}", stsd);
            },
            _ => {
                // Skip the contents of unknown chunks.
                println!("{} (skipped)", h);
                try!(skip_box_content(&mut content, &h));
            },
        };
        assert!(content.limit() == 0);
        println!("read_box context: {}", context);
        Ok(()) // and_then needs a Result to return.
    })
}

/// Entry point for C language callers.
/// Take a buffer and call read_box() on it,
/// returning the number of detected tracks.
#[no_mangle]
pub extern fn read_box_from_buffer(buffer: *const u8, size: usize) -> i32 {
    use std::slice;
    use std::thread;
    use std::i32;

    // Validate arguments from C.
    if buffer.is_null() || size < 8 {
        return -1;
    }

    // Wrap the buffer we've been give in a slice.
    let b = unsafe { slice::from_raw_parts(buffer, size) };
    let mut c = Cursor::new(b);

    // Parse in a subthread.
    let task = thread::spawn(move || {
        let mut context = MediaContext { tracks: Vec::new() };
        loop {
            match read_box(&mut c, &mut context) {
                Ok(_) => {},
                Err(byteorder::Error::UnexpectedEOF) => { break },
                Err(e) => { panic!(e) },
            }
        }
        // Make sure the track count fits in an i32 so we can use
        // negative values for failure.
        assert!(context.tracks.len() < i32::MAX as usize);
        context.tracks.len() as i32
    });
    // Catch any panics.
    task.join().unwrap_or(-1)
}

/// Parse an ftyp box.
pub fn read_ftyp<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<FileTypeBox> {
    let major = try!(be_u32(src));
    let minor = try!(be_u32(src));
    let brand_count = (head.size - 8 - 8) / 4;
    let mut brands = Vec::new();
    for _ in 0..brand_count {
        brands.push(try!(be_u32(src)));
    }
    Ok(FileTypeBox{
        name: head.name,
        size: head.size,
        major_brand: major,
        minor_version: minor,
        compatible_brands: brands,
    })
}

/// Parse an mvhd box.
pub fn read_mvhd<T: ReadBytesExt + BufRead>(src: &mut T, head: &BoxHeader) -> byteorder::Result<MovieHeaderBox> {
    let (version, _) = try!(read_fullbox_extra(src));
    match version {
        // 64 bit creation and modification times.
        1 => { try!(skip(src, 16)); },
        // 32 bit creation and modification times.
        0 => { try!(skip(src, 8)); },
        _ => panic!("invalid mhdr version"),
    }
    let timescale = try!(be_u32(src));
    let duration = match version {
        1 => try!(be_u64(src)),
        0 => try!(be_u32(src)) as u64,
        _ => panic!("invalid mhdr version"),
    };
    // Skip remaining fields.
    try!(skip(src, 80));
    Ok(MovieHeaderBox {
        name: head.name,
        size: head.size,
        timescale: timescale,
        duration: duration,
    })
}

/// Parse a tkhd box.
pub fn read_tkhd<T: ReadBytesExt + BufRead>(src: &mut T, head: &BoxHeader) -> byteorder::Result<TrackHeaderBox> {
    let (version, flags) = try!(read_fullbox_extra(src));
    let disabled = flags & 0x1u32 == 0 || flags & 0x2u32 == 0;
    match version {
        // 64 bit creation and modification times.
        1 => { try!(skip(src, 16)); },
        // 32 bit creation and modification times.
        0 => { try!(skip(src, 8)); },
        _ => panic!("invalid tkhd version"),
    }
    let track_id = try!(be_u32(src));
    try!(skip(src, 4));
    let duration = match version {
        1 => try!(be_u64(src)),
        0 => try!(be_u32(src)) as u64,
        _ => panic!("invalid tkhd version"),
    };
    // Skip uninteresting fields.
    try!(skip(src, 52));
    let width = try!(be_u32(src));
    let height = try!(be_u32(src));
    Ok(TrackHeaderBox {
        name: head.name,
        size: head.size,
        track_id: track_id,
        enabled: !disabled,
        duration: duration,
        width: width,
        height: height,
    })
}

/// Parse a elst box.
pub fn read_elst<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<EditListBox> {
    let (version, _) = try!(read_fullbox_extra(src));
    let edit_count = try!(be_u32(src));
    let mut edits = Vec::new();
    for _ in 0..edit_count {
        let (segment_duration, media_time) = match version {
            1 => {
                // 64 bit segment duration and media times.
                (try!(be_u64(src)),
                 try!(be_i64(src)))
            },
            0 => {
                // 32 bit segment duration and media times.
                (try!(be_u32(src)) as u64,
                 try!(be_i32(src)) as i64)
            },
            _ => panic!("invalid elst version"),
        };
        let media_rate_integer = try!(be_i16(src));
        let media_rate_fraction = try!(be_i16(src));
        edits.push(Edit{
            segment_duration: segment_duration,
            media_time: media_time,
            media_rate_integer: media_rate_integer,
            media_rate_fraction: media_rate_fraction,
        })
    }

    Ok(EditListBox{
        name: head.name,
        size: head.size,
        edits: edits
    })
}

/// Parse a mdhd box.
pub fn read_mdhd<T: ReadBytesExt + BufRead>(src: &mut T, head: &BoxHeader) -> byteorder::Result<MediaHeaderBox> {
    let (version, _) = try!(read_fullbox_extra(src));
    let (timescale, duration) = match version {
        1 => {
            // Skip 64-bit creation and modification times.
            try!(skip(src, 16));

            // 64 bit duration.
            (try!(be_u32(src)),
             try!(be_u64(src)))
        },
        0 => {
            // Skip 32-bit creation and modification times.
            try!(skip(src, 8));

            // 32 bit duration.
            (try!(be_u32(src)),
             try!(be_u32(src)) as u64)
        },
        _ => panic!("invalid mdhd version"),
    };

    // Skip uninteresting fields.
    try!(skip(src, 4));

    Ok(MediaHeaderBox{
        name: head.name,
        size: head.size,
        timescale: timescale,
        duration: duration,
    })
}

/// Parse a stco box.
pub fn read_stco<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<ChunkOffsetBox> {
    let (_, _) = try!(read_fullbox_extra(src));
    let offset_count = try!(be_u32(src));
    let mut offsets = Vec::new();
    for _ in 0..offset_count {
        offsets.push(try!(be_u32(src)) as u64);
    }

    Ok(ChunkOffsetBox{
        name: head.name,
        size: head.size,
        offsets: offsets,
    })
}

/// Parse a stco box.
pub fn read_co64<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<ChunkOffsetBox> {
    let (_, _) = try!(read_fullbox_extra(src));
    let offset_count = try!(be_u32(src));
    let mut offsets = Vec::new();
    for _ in 0..offset_count {
        offsets.push(try!(be_u64(src)));
    }

    Ok(ChunkOffsetBox{
        name: head.name,
        size: head.size,
        offsets: offsets,
    })
}

/// Parse a stss box.
pub fn read_stss<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<SyncSampleBox> {
    let (_, _) = try!(read_fullbox_extra(src));
    let sample_count = try!(be_u32(src));
    let mut samples = Vec::new();
    for _ in 0..sample_count {
        samples.push(try!(be_u32(src)));
    }

    Ok(SyncSampleBox{
        name: head.name,
        size: head.size,
        samples: samples,
    })
}

/// Parse a stsc box.
pub fn read_stsc<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<SampleToChunkBox> {
    let (_, _) = try!(read_fullbox_extra(src));
    let sample_count = try!(be_u32(src));
    let mut samples = Vec::new();
    for _ in 0..sample_count {
        let first_chunk = try!(be_u32(src));
        let samples_per_chunk = try!(be_u32(src));
        let sample_description_index = try!(be_u32(src));
        samples.push(SampleToChunk{
            first_chunk: first_chunk,
            samples_per_chunk: samples_per_chunk,
            sample_description_index: sample_description_index
        });
    }

    Ok(SampleToChunkBox{
        name: head.name,
        size: head.size,
        samples: samples,
    })
}

/// Parse a stsz box.
pub fn read_stsz<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<SampleSizeBox> {
    let (_, _) = try!(read_fullbox_extra(src));
    let sample_size = try!(be_u32(src));
    let sample_count = try!(be_u32(src));
    let mut sample_sizes = Vec::new();
    if sample_size == 0 {
        for _ in 0..sample_count {
            sample_sizes.push(try!(be_u32(src)));
        }
    }

    Ok(SampleSizeBox{
        name: head.name,
        size: head.size,
        sample_size: sample_size,
        sample_sizes: sample_sizes,
    })
}

/// Parse a stts box.
pub fn read_stts<T: ReadBytesExt>(src: &mut T, head: &BoxHeader) -> byteorder::Result<TimeToSampleBox> {
    let (_, _) = try!(read_fullbox_extra(src));
    let sample_count = try!(be_u32(src));
    let mut samples = Vec::new();
    for _ in 0..sample_count {
        let sample_count = try!(be_u32(src));
        let sample_delta = try!(be_u32(src));
        samples.push(Sample{
            sample_count: sample_count,
            sample_delta: sample_delta,
        });
    }

    Ok(TimeToSampleBox{
        name: head.name,
        size: head.size,
        samples: samples,
    })
}

/// Parse a hdlr box.
pub fn read_hdlr<T: ReadBytesExt + BufRead>(src: &mut T, head: &BoxHeader) -> byteorder::Result<HandlerBox> {
    let (_, _) = try!(read_fullbox_extra(src));

    // Skip uninteresting fields.
    try!(skip(src, 4));

    let handler_type = try!(be_u32(src));

    // Skip uninteresting fields.
    try!(skip(src, 12));

    // TODO(kinetik): Find a copy of ISO/IEC 14496-1 to work out how strings are encoded.
    // As a hack, just consume the rest of the box.
    try!(skip_remaining_box_content(src, head));

    Ok(HandlerBox{
        name: head.name,
        size: head.size,
        handler_type: handler_type,
    })
}

/// Parse a stsd box.
pub fn read_stsd<T: ReadBytesExt + BufRead>(src: &mut T, head: &BoxHeader, track: &Track) -> byteorder::Result<SampleDescriptionBox> {
    let (_, _) = try!(read_fullbox_extra(src));

    let description_count = try!(be_u32(src));
    let mut descriptions = Vec::new();

    for _ in 0..description_count {
        let description = match track.track_type {
            TrackType::Video => {
                let h = try!(read_box_header(src));
                // TODO(kinetik): avc3 and encv here also?
                if fourcc_to_string(h.name) != "avc1" {
                    panic!("unsupported SampleEntry::Video subtype");
                }

                // Skip uninteresting fields.
                try!(skip(src, 6));

                let data_reference_index = try!(be_u16(src));

                // Skip uninteresting fields.
                try!(skip(src, 16));

                let width = try!(be_u16(src));
                let height = try!(be_u16(src));

                // Skip uninteresting fields.
                try!(skip(src, 50));

                // TODO(kinetik): Parse avcC atom?  For now we just stash the data.
                let h = try!(read_box_header(src));
                if fourcc_to_string(h.name) != "avcC" {
                    panic!("expected avcC atom inside avc1");
                }
                let mut data: Vec<u8> = vec![0; (h.size - h.offset) as usize];
                let r = try!(src.read(&mut data));
                assert!(r == data.len());
                let avcc = AVCDecoderConfigurationRecord { data: data };

                try!(skip_remaining_box_content(src, head));

                SampleEntry::Video {
                    data_reference_index: data_reference_index,
                    width: width,
                    height: height,
                    avcc: avcc,
                }
            },
            TrackType::Audio => {
                let h = try!(read_box_header(src));
                // TODO(kinetik): enca here also?
                if fourcc_to_string(h.name) != "mp4a" {
                    panic!("unsupported SampleEntry::Audio subtype");
                }

                // Skip uninteresting fields.
                try!(skip(src, 6));

                let data_reference_index = try!(be_u16(src));

                // Skip uninteresting fields.
                try!(skip(src, 8));

                let channelcount = try!(be_u16(src));
                let samplesize = try!(be_u16(src));

                // Skip uninteresting fields.
                try!(skip(src, 4));

                let samplerate = try!(be_u32(src));

                // TODO(kinetik): Parse esds atom?  For now we just stash the data.
                let h = try!(read_box_header(src));
                if fourcc_to_string(h.name) != "esds" {
                    panic!("expected esds atom inside mp4a");
                }
                let (_, _) = try!(read_fullbox_extra(src));
                let mut data: Vec<u8> = vec![0; (h.size - h.offset - 4) as usize];
                let r = try!(src.read(&mut data));
                assert!(r == data.len());
                let esds = ES_Descriptor { data: data };

                SampleEntry::Audio {
                    data_reference_index: data_reference_index,
                    channelcount: channelcount,
                    samplesize: samplesize,
                    samplerate: samplerate,
                    esds: esds,
                }
            },
        };
        descriptions.push(description);
    }

    Ok(SampleDescriptionBox{
        name: head.name,
        size: head.size,
        descriptions: descriptions,
    })
}

/// Convert the iso box type or other 4-character value to a string.
fn fourcc_to_string(name: u32) -> String {
    let u32_to_vec = |u| {
        vec!((u >> 24 & 0xffu32) as u8,
             (u >> 16 & 0xffu32) as u8,
             (u >>  8 & 0xffu32) as u8,
             (u & 0xffu32) as u8)
    };
    let name_bytes = u32_to_vec(name);
    String::from_utf8_lossy(&name_bytes).into_owned()
}

/// Skip a number of bytes that we don't care to parse.
fn skip<T: BufRead>(src: &mut T, bytes: usize) -> byteorder::Result<usize> {
    let mut bytes_to_skip = bytes;
    while bytes_to_skip > 0 {
        let len = {
            let buf = src.fill_buf().unwrap();
            buf.len()
        };
        if len == 0 {
            return Err(byteorder::Error::UnexpectedEOF)
        }
        let discard = cmp::min(len, bytes_to_skip);
        src.consume(discard);
        bytes_to_skip -= discard;
    }
    assert!(bytes_to_skip == 0);
    Ok(bytes)
}

fn be_i16<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<i16> {
    src.read_i16::<BigEndian>()
}

fn be_i32<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<i32> {
    src.read_i32::<BigEndian>()
}

fn be_i64<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<i64> {
    src.read_i64::<BigEndian>()
}

fn be_u16<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<u16> {
    src.read_u16::<BigEndian>()
}

fn be_u32<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<u32> {
    src.read_u32::<BigEndian>()
}

fn be_u64<T: ReadBytesExt>(src: &mut T) -> byteorder::Result<u64> {
    src.read_u64::<BigEndian>()
}

use std::fmt;
impl fmt::Display for BoxHeader {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "'{}' {} bytes", fourcc_to_string(self.name), self.size)
    }
}

impl fmt::Display for FileTypeBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let name = fourcc_to_string(self.name);
        let brand = fourcc_to_string(self.major_brand);
        let mut compat = String::from("compatible with");
        for brand in &self.compatible_brands {
            let brand_string = fourcc_to_string(*brand);
            compat.push(' ');
            compat.push_str(&brand_string);
        }
        write!(f, "'{}' {} bytes '{}' v{}\n {}",
               name, self.size, brand, self.minor_version, compat)
    }
}

impl fmt::Display for MovieHeaderBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let name = fourcc_to_string(self.name);
        write!(f, "'{}' {} bytes duration {}s", name, self.size,
               (self.duration as f64)/(self.timescale as f64))
    }
}

impl fmt::Display for MediaContext {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Found {} tracks.", self.tracks.len())
    }
}

use std::u16;
impl fmt::Display for TrackHeaderBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let name = fourcc_to_string(self.name);
        // Dimensions are 16.16 fixed-point.
        let base = u16::MAX as f64 + 1.0;
        let width = (self.width as f64) / base;
        let height = (self.height as f64) / base;
        let disabled = if self.enabled { "" } else { " (disabled)" };
        write!(f, "'{}' {} bytes duration {} id {} {}x{}{}",
               name, self.size, self.duration, self.track_id,
               width, height, disabled)
    }
}

impl fmt::Display for EditListBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut entries = String::new();
        for entry in &self.edits {
            entries.push_str(&format!("\n  duration {} time {} rate {}/{}",
                                      entry.segment_duration, entry.media_time,
                                      entry.media_rate_integer, entry.media_rate_fraction));
        }
        write!(f, "'{}' {} bytes {}", fourcc_to_string(self.name), self.size, entries)
    }
}

impl fmt::Display for MediaHeaderBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "'{}' {} bytes timescale {} duration {}",
               fourcc_to_string(self.name), self.size, self.timescale, self.duration)
    }
}

impl fmt::Display for ChunkOffsetBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut entries = String::new();
        for entry in &self.offsets {
            entries.push_str(&format!("\n  offset {}", entry));
        }
        write!(f, "'{}' {} bytes {}",
               fourcc_to_string(self.name), self.size, entries)
    }
}

impl fmt::Display for SyncSampleBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut entries = String::new();
        for entry in &self.samples {
            entries.push_str(&format!("\n  sample {}", entry));
        }
        write!(f, "'{}' {} bytes {}",
               fourcc_to_string(self.name), self.size, entries)
    }
}

impl fmt::Display for SampleToChunkBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut entries = String::new();
        for entry in &self.samples {
            entries.push_str(&format!("\n  sample chunk {} {} {}",
                                      entry.first_chunk, entry.samples_per_chunk, entry.sample_description_index));
        }
        write!(f, "'{}' {} bytes {}",
               fourcc_to_string(self.name), self.size, entries)
    }
}

impl fmt::Display for SampleSizeBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut entries = String::new();
        for entry in &self.sample_sizes {
            entries.push_str(&format!("\n  sample size {}", entry));
        }
        write!(f, "'{}' {} bytes sample size {} {}",
               fourcc_to_string(self.name), self.size, self.sample_size, entries)
    }
}

impl fmt::Display for TimeToSampleBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut entries = String::new();
        for entry in &self.samples {
            entries.push_str(&format!("\n  sample count {} delta {}", entry.sample_count, entry.sample_delta));
        }
        write!(f, "'{}' {} bytes sample {}",
               fourcc_to_string(self.name), self.size, entries)
    }
}

impl fmt::Display for HandlerBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "'{}' {} bytes handler_type '{}'",
               fourcc_to_string(self.name), self.size, fourcc_to_string(self.handler_type))
    }
}

impl fmt::Display for SampleDescriptionBox {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "'{}' {} bytes descriptions {}",
               fourcc_to_string(self.name), self.size, self.descriptions.len())
    }
}

#[test]
fn test_read_box_header() {
    use std::io::Cursor;
    use std::io::Write;
    let mut test: Vec<u8> = vec![0, 0, 0, 8]; // minimal box length
    write!(&mut test, "test").unwrap(); // box type
    let mut stream = Cursor::new(test);
    let parsed = read_box_header(&mut stream).unwrap();
    assert_eq!(parsed.name, 1952805748);
    assert_eq!(parsed.size, 8);
    println!("box {}", parsed);
}

#[test]
fn test_read_box_header_long() {
    use std::io::Cursor;
    let mut test: Vec<u8> = vec![0, 0, 0, 1]; // long box extension code
    test.extend("long".to_string().into_bytes()); // box type
    test.extend(vec![0, 0, 0, 0, 0, 0, 16, 0]); // 64 bit size
    // Skip generating box content.
    let mut stream = Cursor::new(test);
    let parsed = read_box_header(&mut stream).unwrap();
    assert_eq!(parsed.name, 1819242087);
    assert_eq!(parsed.size, 4096);
    println!("box {}", parsed);
}

#[test]
fn test_read_ftyp() {
    use std::io::Cursor;
    use std::io::Write;
    let mut test: Vec<u8> = vec![0, 0, 0, 24]; // size
    write!(&mut test, "ftyp").unwrap(); // type
    write!(&mut test, "mp42").unwrap(); // major brand
    test.extend(vec![0, 0, 0, 0]);      // minor version
    write!(&mut test, "isom").unwrap(); // compatible brands...
    write!(&mut test, "mp42").unwrap();
    assert_eq!(test.len(), 24);

    let mut stream = Cursor::new(test);
    let header = read_box_header(&mut stream).unwrap();
    let parsed = read_ftyp(&mut stream, &header).unwrap();
    assert_eq!(parsed.name, 1718909296);
    assert_eq!(parsed.size, 24);
    assert_eq!(parsed.major_brand, 1836069938);
    assert_eq!(parsed.minor_version, 0);
    assert_eq!(parsed.compatible_brands.len(), 2);
    assert_eq!(parsed.compatible_brands[0], 1769172845);
    assert_eq!(fourcc_to_string(parsed.compatible_brands[1]), "mp42");
    println!("box {}", parsed);
}

#[test]
fn test_read_elst_v0() {
    use std::io::Cursor;
    use std::io::Write;
    let mut test: Vec<u8> = vec![0, 0, 0, 28]; // size
    write!(&mut test, "elst").unwrap(); // type
    test.extend(vec![0, 0, 0, 0]); // fullbox
    test.extend(vec![0, 0, 0, 1]); // count
    test.extend(vec![1, 2, 3, 4,
                     5, 6, 7, 8,
                     9, 10,
                     11, 12]);
    assert_eq!(test.len(), 28);

    let mut stream = Cursor::new(test);
    let header = read_box_header(&mut stream).unwrap();
    let parsed = read_elst(&mut stream, &header).unwrap();
    assert_eq!(parsed.name, 1701606260);
    assert_eq!(parsed.size, 28);
    assert_eq!(parsed.edits.len(), 1);
    assert_eq!(parsed.edits[0].segment_duration, 16909060);
    assert_eq!(parsed.edits[0].media_time, 84281096);
    assert_eq!(parsed.edits[0].media_rate_integer, 2314);
    assert_eq!(parsed.edits[0].media_rate_fraction, 2828);
    println!("box {}", parsed);
}

#[test]
fn test_read_elst_v1() {
    use std::io::Cursor;
    use std::io::Write;
    let mut test: Vec<u8> = vec![0, 0, 0, 56]; // size
    write!(&mut test, "elst").unwrap(); // type
    test.extend(vec![1, 0, 0, 0]); // fullbox
    test.extend(vec![0, 0, 0, 2]); // count
    test.extend(vec![1, 2, 3, 4, 1, 2, 3, 4,
                     5, 6, 7, 8, 5, 6, 7, 8,
                     9, 10,
                     11, 12]);
    test.extend(vec![1, 2, 3, 4, 1, 2, 3, 4,
                     5, 6, 7, 8, 5, 6, 7, 8,
                     9, 10,
                     11, 12]);
    assert_eq!(test.len(), 56);

    let mut stream = Cursor::new(test);
    let header = read_box_header(&mut stream).unwrap();
    let parsed = read_elst(&mut stream, &header).unwrap();
    assert_eq!(parsed.name, 1701606260);
    assert_eq!(parsed.size, 56);
    assert_eq!(parsed.edits.len(), 2);
    assert_eq!(parsed.edits[1].segment_duration, 72623859723010820);
    assert_eq!(parsed.edits[1].media_time, 361984551075317512);
    assert_eq!(parsed.edits[1].media_rate_integer, 2314);
    assert_eq!(parsed.edits[1].media_rate_fraction, 2828);
    println!("box {}", parsed);
}

#[test]
fn test_read_mdhd_v0() {
    use std::io::Cursor;
    use std::io::Write;
    let mut test: Vec<u8> = vec![0, 0, 0, 32]; // size
    write!(&mut test, "mdhd").unwrap(); // type
    test.extend(vec![0, 0, 0, 0]); // fullbox
    test.extend(vec![0, 0, 0, 0,
                     0, 0, 0, 0,
                     1, 2, 3, 4,
                     5, 6, 7, 8,
                     0, 0, 0, 0]);
    assert_eq!(test.len(), 32);

    let mut stream = Cursor::new(test);
    let header = read_box_header(&mut stream).unwrap();
    let parsed = read_mdhd(&mut stream, &header).unwrap();
    assert_eq!(parsed.name, 1835296868);
    assert_eq!(parsed.size, 32);
    assert_eq!(parsed.timescale, 16909060);
    assert_eq!(parsed.duration, 84281096);
    println!("box {}", parsed);
}

#[test]
fn test_read_mdhd_v1() {
    use std::io::Cursor;
    use std::io::Write;
    let mut test: Vec<u8> = vec![0, 0, 0, 44]; // size
    write!(&mut test, "mdhd").unwrap(); // type
    test.extend(vec![1, 0, 0, 0]); // fullbox
    test.extend(vec![0, 0, 0, 0, 0, 0, 0, 0,
                     0, 0, 0, 0, 0, 0, 0, 0,
                     1, 2, 3, 4,
                     5, 6, 7, 8, 5, 6, 7, 8,
                     0, 0, 0, 0]);
    assert_eq!(test.len(), 44);

    let mut stream = Cursor::new(test);
    let header = read_box_header(&mut stream).unwrap();
    let parsed = read_mdhd(&mut stream, &header).unwrap();
    assert_eq!(parsed.name, 1835296868);
    assert_eq!(parsed.size, 44);
    assert_eq!(parsed.timescale, 16909060);
    assert_eq!(parsed.duration, 361984551075317512);
    println!("box {}", parsed);
}