package arrange import ( "encoding/binary" "errors" "fmt" "io" "time" ) // epoch1904 is where QuickTime/MP4 timestamps count from. var epoch1904 = time.Date(1904, 1, 1, 0, 0, 0, 0, time.UTC) var errNoAtom = errors.New("atom not found") // quickTimeCreated reads the creation time from the movie header (moov/mvhd) // of a QuickTime or ISO-BMFF (mp4, m4v, 3gp) file. func quickTimeCreated(r io.ReadSeeker) (time.Time, error) { end, err := r.Seek(0, io.SeekEnd) if err != nil { return time.Time{}, err } moov, moovEnd, err := findAtom(r, 0, end, "moov") if err != nil { return time.Time{}, err } mvhd, _, err := findAtom(r, moov, moovEnd, "mvhd") if err != nil { return time.Time{}, err } if _, err := r.Seek(mvhd, io.SeekStart); err != nil { return time.Time{}, err } // version(1) flags(3) creation_time(4 or 8) var hdr [12]byte if _, err := io.ReadFull(r, hdr[:]); err != nil { return time.Time{}, fmt.Errorf("short mvhd: %v", err) } var secs uint64 switch hdr[0] { case 0: secs = uint64(binary.BigEndian.Uint32(hdr[4:8])) case 1: secs = binary.BigEndian.Uint64(hdr[4:12]) default: return time.Time{}, fmt.Errorf("unknown mvhd version %d", hdr[0]) } if secs == 0 { return time.Time{}, errors.New("mvhd has no creation time") } t := epoch1904.Add(time.Duration(secs) * time.Second) if !plausible(t) || t.After(time.Now().Add(24*time.Hour)) { return time.Time{}, fmt.Errorf("implausible mvhd creation time %v", t) } return t, nil } // findAtom scans the sibling atoms in [start, end) for one named typ, and // returns the offsets of its payload. func findAtom(r io.ReadSeeker, start, end int64, typ string) (int64, int64, error) { for off := start; off+8 <= end; { if _, err := r.Seek(off, io.SeekStart); err != nil { return 0, 0, err } var hdr [16]byte if _, err := io.ReadFull(r, hdr[:8]); err != nil { return 0, 0, err } size := int64(binary.BigEndian.Uint32(hdr[:4])) name := string(hdr[4:8]) body := off + 8 switch size { case 0: // runs to the end of the container size = end - off case 1: // 64-bit size follows the name if _, err := io.ReadFull(r, hdr[8:16]); err != nil { return 0, 0, err } size = int64(binary.BigEndian.Uint64(hdr[8:16])) body += 8 } if size < body-off || off+size > end { return 0, 0, fmt.Errorf("bad size %d for atom %q at %d", size, name, off) } if name == typ { return body, off + size, nil } off += size } return 0, 0, errNoAtom }