diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-02-13 11:24:24 +0100 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-02-13 11:28:45 +0100 |
| commit | f4b35bb7f4475db77fa6969eb42964824f616fb0 (patch) | |
| tree | 54046849b6606d8160b563077234c3ff284a96a7 | |
| parent | 8502816a943bb33705a7775838c760ed72046ae8 (diff) | |
| download | mp4-f4b35bb7f4475db77fa6969eb42964824f616fb0.tar.gz mp4-f4b35bb7f4475db77fa6969eb42964824f616fb0.zip | |
v2
| -rw-r--r-- | box.go | 507 | ||||
| -rw-r--r-- | cmd/mp4dump/main.go | 344 | ||||
| -rw-r--r-- | codec.go | 1196 | ||||
| -rw-r--r-- | descriptor.go | 174 | ||||
| -rw-r--r-- | iter.go | 524 | ||||
| -rw-r--r-- | reader.go | 310 | ||||
| -rw-r--r-- | scanner.go | 169 | ||||
| -rw-r--r-- | writer.go | 463 |
8 files changed, 1857 insertions, 1830 deletions
@@ -1,17 +1,6 @@ // Package mp4 implements encoding and decoding of ISO Base Media File Format (MP4) boxes. package mp4 -import ( - "encoding/binary" - "errors" - "fmt" - "math" -) - -var be = binary.BigEndian - -const uint32Max = math.MaxUint32 - // BoxType is a 4-byte box type identifier. type BoxType [4]byte @@ -19,426 +8,94 @@ func (t BoxType) String() string { return string(t[:]) } -// newBoxType creates a BoxType from a 4-character string. -func newBoxType(s string) BoxType { - var t BoxType - copy(t[:], s) - return t -} - // Known box types. var ( - TypeFtyp = newBoxType("ftyp") - TypeMoov = newBoxType("moov") - TypeMvhd = newBoxType("mvhd") - TypeTrak = newBoxType("trak") - TypeTkhd = newBoxType("tkhd") - TypeTref = newBoxType("tref") - TypeTrgr = newBoxType("trgr") - TypeEdts = newBoxType("edts") - TypeElst = newBoxType("elst") - TypeMdia = newBoxType("mdia") - TypeMdhd = newBoxType("mdhd") - TypeHdlr = newBoxType("hdlr") - TypeElng = newBoxType("elng") - TypeMinf = newBoxType("minf") - TypeVmhd = newBoxType("vmhd") - TypeSmhd = newBoxType("smhd") - TypeHmhd = newBoxType("hmhd") - TypeSthd = newBoxType("sthd") - TypeNmhd = newBoxType("nmhd") - TypeDinf = newBoxType("dinf") - TypeDref = newBoxType("dref") - TypeStbl = newBoxType("stbl") - TypeStsd = newBoxType("stsd") - TypeStts = newBoxType("stts") - TypeCtts = newBoxType("ctts") - TypeCslg = newBoxType("cslg") - TypeStsc = newBoxType("stsc") - TypeStsz = newBoxType("stsz") - TypeStz2 = newBoxType("stz2") - TypeStco = newBoxType("stco") - TypeCo64 = newBoxType("co64") - TypeStss = newBoxType("stss") - TypeStsh = newBoxType("stsh") - TypePadb = newBoxType("padb") - TypeStdp = newBoxType("stdp") - TypeSdtp = newBoxType("sdtp") - TypeSbgp = newBoxType("sbgp") - TypeSgpd = newBoxType("sgpd") - TypeSubs = newBoxType("subs") - TypeSaiz = newBoxType("saiz") - TypeSaio = newBoxType("saio") - TypeMvex = newBoxType("mvex") - TypeMehd = newBoxType("mehd") - TypeTrex = newBoxType("trex") - TypeLeva = newBoxType("leva") - TypeMoof = newBoxType("moof") - TypeMfhd = newBoxType("mfhd") - TypeTraf = newBoxType("traf") - TypeTfhd = newBoxType("tfhd") - TypeTfdt = newBoxType("tfdt") - TypeTrun = newBoxType("trun") - TypeMeta = newBoxType("meta") - TypeUdta = newBoxType("udta") - TypeMdat = newBoxType("mdat") - TypeAvc1 = newBoxType("avc1") - TypeAvcC = newBoxType("avcC") - TypeMp4a = newBoxType("mp4a") - TypeEsds = newBoxType("esds") + TypeFtyp = BoxType{'f', 't', 'y', 'p'} + TypeMoov = BoxType{'m', 'o', 'o', 'v'} + TypeMvhd = BoxType{'m', 'v', 'h', 'd'} + TypeTrak = BoxType{'t', 'r', 'a', 'k'} + TypeTkhd = BoxType{'t', 'k', 'h', 'd'} + TypeTref = BoxType{'t', 'r', 'e', 'f'} + TypeTrgr = BoxType{'t', 'r', 'g', 'r'} + TypeEdts = BoxType{'e', 'd', 't', 's'} + TypeElst = BoxType{'e', 'l', 's', 't'} + TypeMdia = BoxType{'m', 'd', 'i', 'a'} + TypeMdhd = BoxType{'m', 'd', 'h', 'd'} + TypeHdlr = BoxType{'h', 'd', 'l', 'r'} + TypeElng = BoxType{'e', 'l', 'n', 'g'} + TypeMinf = BoxType{'m', 'i', 'n', 'f'} + TypeVmhd = BoxType{'v', 'm', 'h', 'd'} + TypeSmhd = BoxType{'s', 'm', 'h', 'd'} + TypeHmhd = BoxType{'h', 'm', 'h', 'd'} + TypeSthd = BoxType{'s', 't', 'h', 'd'} + TypeNmhd = BoxType{'n', 'm', 'h', 'd'} + TypeDinf = BoxType{'d', 'i', 'n', 'f'} + TypeDref = BoxType{'d', 'r', 'e', 'f'} + TypeStbl = BoxType{'s', 't', 'b', 'l'} + TypeStsd = BoxType{'s', 't', 's', 'd'} + TypeStts = BoxType{'s', 't', 't', 's'} + TypeCtts = BoxType{'c', 't', 't', 's'} + TypeCslg = BoxType{'c', 's', 'l', 'g'} + TypeStsc = BoxType{'s', 't', 's', 'c'} + TypeStsz = BoxType{'s', 't', 's', 'z'} + TypeStz2 = BoxType{'s', 't', 'z', '2'} + TypeStco = BoxType{'s', 't', 'c', 'o'} + TypeCo64 = BoxType{'c', 'o', '6', '4'} + TypeStss = BoxType{'s', 't', 's', 's'} + TypeStsh = BoxType{'s', 't', 's', 'h'} + TypePadb = BoxType{'p', 'a', 'd', 'b'} + TypeStdp = BoxType{'s', 't', 'd', 'p'} + TypeSdtp = BoxType{'s', 'd', 't', 'p'} + TypeSbgp = BoxType{'s', 'b', 'g', 'p'} + TypeSgpd = BoxType{'s', 'g', 'p', 'd'} + TypeSubs = BoxType{'s', 'u', 'b', 's'} + TypeSaiz = BoxType{'s', 'a', 'i', 'z'} + TypeSaio = BoxType{'s', 'a', 'i', 'o'} + TypeMvex = BoxType{'m', 'v', 'e', 'x'} + TypeMehd = BoxType{'m', 'e', 'h', 'd'} + TypeTrex = BoxType{'t', 'r', 'e', 'x'} + TypeLeva = BoxType{'l', 'e', 'v', 'a'} + TypeMoof = BoxType{'m', 'o', 'o', 'f'} + TypeMfhd = BoxType{'m', 'f', 'h', 'd'} + TypeTraf = BoxType{'t', 'r', 'a', 'f'} + TypeTfhd = BoxType{'t', 'f', 'h', 'd'} + TypeTfdt = BoxType{'t', 'f', 'd', 't'} + TypeTrun = BoxType{'t', 'r', 'u', 'n'} + TypeMeta = BoxType{'m', 'e', 't', 'a'} + TypeUdta = BoxType{'u', 'd', 't', 'a'} + TypeMdat = BoxType{'m', 'd', 'a', 't'} + TypeFree = BoxType{'f', 'r', 'e', 'e'} + TypeSkip = BoxType{'s', 'k', 'i', 'p'} + TypeAvc1 = BoxType{'a', 'v', 'c', '1'} + TypeAvcC = BoxType{'a', 'v', 'c', 'C'} + TypeMp4a = BoxType{'m', 'p', '4', 'a'} + TypeEsds = BoxType{'e', 's', 'd', 's'} ) -// containerChild describes a child slot in a container box. -// If array is true, the key in the container is the plural form (e.g. "traks") -// and multiple children of this type can appear. -type containerChild struct { - Type BoxType - Array bool -} - -// containerDef defines which children a container box expects. -var containerDef = map[BoxType][]containerChild{ - TypeMoov: {{TypeMvhd, false}, {TypeMeta, false}, {TypeTrak, true}, {TypeMvex, false}}, - TypeTrak: {{TypeTkhd, false}, {TypeTref, false}, {TypeTrgr, false}, {TypeEdts, false}, {TypeMeta, false}, {TypeMdia, false}, {TypeUdta, false}}, - TypeEdts: {{TypeElst, false}}, - TypeMdia: {{TypeMdhd, false}, {TypeHdlr, false}, {TypeElng, false}, {TypeMinf, false}}, - TypeMinf: {{TypeVmhd, false}, {TypeSmhd, false}, {TypeHmhd, false}, {TypeSthd, false}, {TypeNmhd, false}, {TypeDinf, false}, {TypeStbl, false}}, - TypeDinf: {{TypeDref, false}}, - TypeStbl: { - {TypeStsd, false}, {TypeStts, false}, {TypeCtts, false}, {TypeCslg, false}, - {TypeStsc, false}, {TypeStsz, false}, {TypeStz2, false}, {TypeStco, false}, - {TypeCo64, false}, {TypeStss, false}, {TypeStsh, false}, {TypePadb, false}, - {TypeStdp, false}, {TypeSdtp, false}, {TypeSbgp, true}, {TypeSgpd, true}, - {TypeSubs, true}, {TypeSaiz, true}, {TypeSaio, true}, - }, - TypeMvex: {{TypeMehd, false}, {TypeTrex, true}, {TypeLeva, false}}, - TypeMoof: {{TypeMfhd, false}, {TypeMeta, false}, {TypeTraf, true}}, - TypeTraf: {{TypeTfhd, false}, {TypeTfdt, false}, {TypeTrun, false}, {TypeSbgp, true}, {TypeSgpd, true}, {TypeSubs, true}, {TypeSaiz, true}, {TypeSaio, true}, {TypeMeta, false}}, -} - -// isContainer returns the container definition for a type, or nil. -func isContainer(t BoxType) []containerChild { - return containerDef[t] -} - -// fullBoxes is the set of box types that have version+flags in their header. -var fullBoxes = map[BoxType]bool{ - TypeMvhd: true, TypeTkhd: true, TypeMdhd: true, TypeVmhd: true, TypeSmhd: true, - TypeStsd: true, TypeEsds: true, TypeStsz: true, TypeStco: true, TypeCo64: true, - TypeStss: true, TypeStts: true, TypeCtts: true, TypeStsc: true, TypeDref: true, - TypeElst: true, TypeHdlr: true, TypeMehd: true, TypeTrex: true, TypeMfhd: true, - TypeTfhd: true, TypeTfdt: true, TypeTrun: true, -} - -// Box represents an MP4 box (atom). -type Box struct { - Type BoxType - Size uint64 // total size including header - Version uint8 - Flags uint32 - HasFullBox bool - - // Container children (keyed by type). For array children, use Children. - Children map[BoxType][]*Box - // OtherBoxes holds children not recognized by the container definition. - OtherBoxes []*Box - - // Raw buffer for unknown box types. - Buffer []byte - - // Typed payload: only one of these is non-nil for leaf boxes. - Ftyp *Ftyp - Mvhd *Mvhd - Tkhd *Tkhd - Mdhd *Mdhd - Vmhd *Vmhd - Smhd *Smhd - Stsd *Stsd - Stsz *Stsz - Stco *Stco // also used for stss - Co64 *Co64 - Stts *Stts - Ctts *Ctts - Stsc *Stsc - Dref *DrefBox - Elst *Elst - Hdlr *Hdlr - Mehd *Mehd - Trex *Trex - Mfhd *Mfhd - Tfhd *Tfhd - Tfdt *Tfdt - Trun *Trun - Mdat *Mdat - AvcC *AvcC - Visual *VisualSampleEntry - Audio *AudioSampleEntry - Esds *Esds -} - -// Child returns the first child box of the given type, or nil. -func (b *Box) Child(t BoxType) *Box { - if b.Children == nil { - return nil - } - cs := b.Children[t] - if len(cs) == 0 { - return nil +// IsFullBox returns true if the box type has version and flags fields. +func IsFullBox(t BoxType) bool { + switch t { + case TypeMvhd, TypeTkhd, TypeMdhd, TypeHdlr, + TypeVmhd, TypeSmhd, TypeDref, TypeStsd, + TypeStts, TypeCtts, TypeStsc, TypeStsz, + TypeStco, TypeCo64, TypeStss, TypeElst, + TypeMeta, TypeEsds, TypeMehd, TypeTrex, + TypeMfhd, TypeTfhd, TypeTfdt, TypeTrun, + TypeSbgp, TypeSgpd, TypeSaiz, TypeSaio, + TypeCslg, TypeSdtp: + return true } - return cs[0] + return false } -// ChildList returns all child boxes of the given type. -func (b *Box) ChildList(t BoxType) []*Box { - if b.Children == nil { - return nil +// IsContainerBox returns true if the box type is a container that holds child boxes. +func IsContainerBox(t BoxType) bool { + switch t { + case TypeMoov, TypeTrak, TypeEdts, TypeMdia, + TypeMinf, TypeDinf, TypeStbl, TypeUdta, + TypeMeta, TypeMvex, TypeMoof, TypeTraf, + TypeTref, TypeTrgr: + return true } - return b.Children[t] -} - -// Headers holds parsed box header information. -type Headers struct { - Size uint64 - HeaderSize int - ContentLen int - Type BoxType - Version uint8 - Flags uint32 -} - -// ReadHeaders parses box headers from buf[start:end]. -// Returns the headers and nil error, or if not enough data, returns an error. -func ReadHeaders(buf []byte, start, end int) (Headers, error) { - if end-start < 8 { - return Headers{}, errors.New("need at least 8 bytes") - } - - size := uint64(be.Uint32(buf[start:])) - var t BoxType - copy(t[:], buf[start+4:]) - ptr := start + 8 - - if size == 1 { - if end-start < 16 { - return Headers{}, errors.New("need at least 16 bytes for extended size") - } - size = be.Uint64(buf[ptr:]) - ptr += 8 - } - - var version uint8 - var flags uint32 - if fullBoxes[t] { - if end-ptr < 4 { - return Headers{}, errors.New("need 4 more bytes for full box header") - } - vf := be.Uint32(buf[ptr:]) - version = uint8(vf >> 24) - flags = vf & 0x00ffffff - ptr += 4 - } - - hdrSize := ptr - start - return Headers{ - Size: size, - HeaderSize: hdrSize, - ContentLen: int(size) - hdrSize, - Type: t, - Version: version, - Flags: flags, - }, nil -} - -// Decode decodes a box from buf[start:end]. -func Decode(buf []byte, start, end int) (*Box, error) { - h, err := ReadHeaders(buf, start, end) - if err != nil { - return nil, err - } - if int(h.Size) > end-start { - return nil, fmt.Errorf("box %s: data too short (need %d, have %d)", h.Type, h.Size, end-start) - } - return decodeBody(h, buf, start+h.HeaderSize, start+int(h.Size)) -} - -func decodeBody(h Headers, buf []byte, start, end int) (*Box, error) { - box := &Box{ - Type: h.Type, - Size: h.Size, - Version: h.Version, - Flags: h.Flags, - HasFullBox: fullBoxes[h.Type], - } - - if def := isContainer(h.Type); def != nil { - box.Children = make(map[BoxType][]*Box) - // Build lookup: which types are expected and whether they're arrays - expected := make(map[BoxType]bool, len(def)) // true = array - for _, c := range def { - expected[c.Type] = c.Array - } - - ptr := start - for end-ptr >= 8 { - child, err := Decode(buf, ptr, end) - if err != nil { - return nil, fmt.Errorf("in container %s: %w", h.Type, err) - } - ptr += int(child.Size) - - isArr, known := expected[child.Type] - if known { - if isArr { - box.Children[child.Type] = append(box.Children[child.Type], child) - } else { - box.Children[child.Type] = []*Box{child} - } - } else { - box.OtherBoxes = append(box.OtherBoxes, child) - } - } - } else if codec := getCodec(h.Type); codec != nil { - if err := codec.decode(box, buf, start, end); err != nil { - return nil, fmt.Errorf("decoding %s: %w", h.Type, err) - } - } else { - // Unknown box: store raw data - box.Buffer = make([]byte, end-start) - copy(box.Buffer, buf[start:end]) - } - - return box, nil -} - -// EncodingLength computes the total encoded size of the box; populates Size fields. -func EncodingLength(box *Box) uint64 { - var size uint64 = 8 - if fullBoxes[box.Type] { - size += 4 - } - - if def := isContainer(box.Type); def != nil { - for _, cd := range def { - children := box.Children[cd.Type] - for _, child := range children { - child.Type = cd.Type - size += EncodingLength(child) - } - } - for _, child := range box.OtherBoxes { - size += EncodingLength(child) - } - } else if codec := getCodec(box.Type); codec != nil { - size += uint64(codec.encodingLength(box)) - } else if box.Buffer != nil { - size += uint64(len(box.Buffer)) - } - - if size > uint32Max { - size += 8 // extended size field - } - - box.Size = size - return size -} - -// Encode encodes the box into buf starting at offset. -// Returns the number of bytes written. -func Encode(box *Box, buf []byte, offset int) (int, error) { - EncodingLength(box) - return encodeBox(box, buf, offset) -} - -func encodeBox(box *Box, buf []byte, offset int) (int, error) { - sz := box.Size - hdrSz := uint32(sz) - if sz > uint32Max { - hdrSz = 1 - } - - be.PutUint32(buf[offset:], hdrSz) - copy(buf[offset+4:], box.Type[:]) - ptr := offset + 8 - - if hdrSz == 1 { - be.PutUint64(buf[ptr:], sz) - ptr += 8 - } - - if fullBoxes[box.Type] { - vf := (uint32(box.Version) << 24) | (box.Flags & 0x00ffffff) - be.PutUint32(buf[ptr:], vf) - ptr += 4 - } - - if def := isContainer(box.Type); def != nil { - for _, cd := range def { - children := box.Children[cd.Type] - for _, child := range children { - n, err := encodeBox(child, buf, ptr) - if err != nil { - return 0, err - } - ptr += n - } - } - for _, child := range box.OtherBoxes { - n, err := encodeBox(child, buf, ptr) - if err != nil { - return 0, err - } - ptr += n - } - } else if codec := getCodec(box.Type); codec != nil { - n := codec.encode(box, buf, ptr) - ptr += n - } else if box.Buffer != nil { - copy(buf[ptr:], box.Buffer) - ptr += len(box.Buffer) - } - - return ptr - offset, nil -} - -// EncodeToBytes is a convenience that allocates a buffer and encodes the box. -func EncodeToBytes(box *Box) ([]byte, error) { - sz := EncodingLength(box) - buf := make([]byte, sz) - _, err := encodeBox(box, buf, 0) - if err != nil { - return nil, err - } - return buf, nil -} - -// EncodeToBuf encodes the box into the provided buffer slice. -// The buffer will be grown if needed. Returns the slice containing the encoded data. -func EncodeToBuf(box *Box, buf []byte) ([]byte, error) { - sz := int(EncodingLength(box)) - if cap(buf) < sz { - buf = make([]byte, sz) - } else { - buf = buf[:sz] - } - _, err := encodeBox(box, buf, 0) - if err != nil { - return nil, err - } - return buf, nil -} - -func readString(buf []byte, offset, maxLen int) string { - end := offset - limit := offset + maxLen - if limit > len(buf) { - limit = len(buf) - } - for end < limit && buf[end] != 0 { - end++ - } - return string(buf[offset:end]) -} - -func clearBytes(buf []byte, start, end int) { - clear(buf[start:end]) + return false } diff --git a/cmd/mp4dump/main.go b/cmd/mp4dump/main.go index ac3c66c..0d42d18 100644 --- a/cmd/mp4dump/main.go +++ b/cmd/mp4dump/main.go @@ -15,155 +15,255 @@ func main() { os.Exit(1) } - data, err := os.ReadFile(os.Args[1]) + f, err := os.Open(os.Args[1]) if err != nil { - fmt.Fprintf(os.Stderr, "error reading file: %v\n", err) + fmt.Fprintf(os.Stderr, "error opening file: %v\n", err) os.Exit(1) } + defer f.Close() - boxes, err := decodeAll(data) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } + sc := mp4.NewScanner(f) + for sc.Next() { + e := sc.Entry() + fmt.Printf("[%s] size=%d\n", e.Type, e.Size) - for _, box := range boxes { - printBox(box, 0) + // Only load metadata boxes into memory for deep parsing + if e.Type == mp4.TypeMoov || e.Type == mp4.TypeMoof { + buf := make([]byte, e.DataSize()) + if err := sc.ReadBody(buf); err != nil { + fmt.Fprintf(os.Stderr, "error reading %s: %v\n", e.Type, err) + continue + } + r := mp4.NewReader(buf) + walk(&r, 1) + } else if e.Type == mp4.TypeFtyp { + buf := make([]byte, e.DataSize()) + if err := sc.ReadBody(buf); err != nil { + fmt.Fprintf(os.Stderr, "error reading ftyp: %v\n", err) + continue + } + f := mp4.ReadFtyp(buf) + fmt.Printf(" brand=%s ver=%d", string(f.MajorBrand[:]), f.MinorVersion) + if len(f.Compatible) > 0 { + fmt.Printf(" compat=[") + for i, c := range f.Compatible { + if i > 0 { + fmt.Printf(",") + } + fmt.Printf("%s", string(c[:])) + } + fmt.Printf("]") + } + fmt.Println() + } else if e.Type == mp4.TypeMdat { + fmt.Printf(" dataLen=%d\n", e.DataSize()) + } + } + if err := sc.Err(); err != nil { + fmt.Fprintf(os.Stderr, "scan error: %v\n", err) + os.Exit(1) } } -func decodeAll(data []byte) ([]*mp4.Box, error) { - var boxes []*mp4.Box - ptr := 0 - for ptr < len(data) { - if len(data)-ptr < 8 { - break +func walk(r *mp4.Reader, depth int) { + for r.Next() { + indent := strings.Repeat(" ", depth) + + fmt.Printf("%s[%s] size=%d", indent, r.Type(), r.Size()) + + if mp4.IsFullBox(r.Type()) { + fmt.Printf(" v=%d flags=0x%06x", r.Version(), r.Flags()) } - box, err := mp4.Decode(data, ptr, len(data)) - if err != nil { - return nil, fmt.Errorf("at offset %d: %w", ptr, err) + + printBoxInfo(r) + fmt.Println() + + // Descend into containers + if mp4.IsContainerBox(r.Type()) { + r.Enter() + walk(r, depth+1) + r.Exit() + continue } - boxes = append(boxes, box) - ptr += int(box.Size) - } - return boxes, nil -} -var containerChildren = map[mp4.BoxType][]mp4.BoxType{ - mp4.TypeMoov: {mp4.TypeMvhd, mp4.TypeMeta, mp4.TypeTrak, mp4.TypeMvex}, - mp4.TypeTrak: {mp4.TypeTkhd, mp4.TypeTref, mp4.TypeTrgr, mp4.TypeEdts, mp4.TypeMeta, mp4.TypeMdia, mp4.TypeUdta}, - mp4.TypeEdts: {mp4.TypeElst}, - mp4.TypeMdia: {mp4.TypeMdhd, mp4.TypeHdlr, mp4.TypeElng, mp4.TypeMinf}, - mp4.TypeMinf: {mp4.TypeVmhd, mp4.TypeSmhd, mp4.TypeHmhd, mp4.TypeSthd, mp4.TypeNmhd, mp4.TypeDinf, mp4.TypeStbl}, - mp4.TypeDinf: {mp4.TypeDref}, - mp4.TypeStbl: {mp4.TypeStsd, mp4.TypeStts, mp4.TypeCtts, mp4.TypeCslg, mp4.TypeStsc, mp4.TypeStsz, mp4.TypeStz2, mp4.TypeStco, mp4.TypeCo64, mp4.TypeStss, mp4.TypeStsh, mp4.TypePadb, mp4.TypeStdp, mp4.TypeSdtp, mp4.TypeSbgp, mp4.TypeSgpd, mp4.TypeSubs, mp4.TypeSaiz, mp4.TypeSaio}, - mp4.TypeMvex: {mp4.TypeMehd, mp4.TypeTrex, mp4.TypeLeva}, - mp4.TypeMoof: {mp4.TypeMfhd, mp4.TypeMeta, mp4.TypeTraf}, - mp4.TypeTraf: {mp4.TypeTfhd, mp4.TypeTfdt, mp4.TypeTrun, mp4.TypeSbgp, mp4.TypeSgpd, mp4.TypeSubs, mp4.TypeSaiz, mp4.TypeSaio, mp4.TypeMeta}, + // Handle stsd: entry count + sub-boxes + if r.Type() == mp4.TypeStsd { + r.Enter() + r.Skip(4) // skip entry count + for r.Next() { + printSampleEntry(r, depth+1) + } + r.Exit() + continue + } + } } -func printBox(box *mp4.Box, depth int) { +func printSampleEntry(r *mp4.Reader, depth int) { indent := strings.Repeat(" ", depth) - sizeStr := fmt.Sprintf("%d", box.Size) - extra := boxInfo(box) + switch r.Type() { + case mp4.TypeAvc1: + v := mp4.ReadVisualSampleEntry(r.Data()) + fmt.Printf("%s[%s] size=%d %dx%d compressor=%q\n", indent, r.Type(), r.Size(), v.Width, v.Height, v.CompressorName) + // Enter to find avcC and other children + r.Enter() + r.Skip(v.ChildOffset) + for r.Next() { + childIndent := strings.Repeat(" ", depth+1) + if mp4.IsFullBox(r.Type()) { + fmt.Printf("%s[%s] size=%d v=%d flags=0x%06x", childIndent, r.Type(), r.Size(), r.Version(), r.Flags()) + } else { + fmt.Printf("%s[%s] size=%d", childIndent, r.Type(), r.Size()) + } + if r.Type() == mp4.TypeAvcC { + codec := mp4.ReadAvcC(r.Data()) + fmt.Printf(" codec=%s", codec) + } + fmt.Println() + } + r.Exit() - vf := "" - if box.HasFullBox { - vf = fmt.Sprintf(" v=%d flags=0x%06x", box.Version, box.Flags) - } + case mp4.TypeMp4a: + a := mp4.ReadAudioSampleEntry(r.Data()) + fmt.Printf("%s[%s] size=%d ch=%d sampleSize=%d sampleRate=%d\n", indent, r.Type(), r.Size(), a.ChannelCount, a.SampleSize, a.SampleRate>>16) + // Enter to find esds and other children + r.Enter() + r.Skip(a.ChildOffset) + for r.Next() { + childIndent := strings.Repeat(" ", depth+1) + if mp4.IsFullBox(r.Type()) { + fmt.Printf("%s[%s] size=%d v=%d flags=0x%06x", childIndent, r.Type(), r.Size(), r.Version(), r.Flags()) + } else { + fmt.Printf("%s[%s] size=%d", childIndent, r.Type(), r.Size()) + } + if r.Type() == mp4.TypeEsds { + codec := mp4.ReadEsdsCodec(r.Data()) + fmt.Printf(" codec=%s", codec) + } + fmt.Println() + } + r.Exit() - fmt.Printf("%s[%s] size=%s%s%s\n", indent, box.Type, sizeStr, vf, extra) + default: + fmt.Printf("%s[%s] size=%d", indent, r.Type(), r.Size()) + if mp4.IsFullBox(r.Type()) { + fmt.Printf(" v=%d flags=0x%06x", r.Version(), r.Flags()) + } + fmt.Printf(" (raw %d bytes)\n", len(r.Data())) + } +} - // Container children in defined order - if box.Children != nil { - if order, ok := containerChildren[box.Type]; ok { - for _, t := range order { - for _, child := range box.ChildList(t) { - printBox(child, depth+1) +func printBoxInfo(r *mp4.Reader) { + switch r.Type() { + case mp4.TypeFtyp: + f := mp4.ReadFtyp(r.Data()) + fmt.Printf(" brand=%s ver=%d", string(f.MajorBrand[:]), f.MinorVersion) + if len(f.Compatible) > 0 { + fmt.Printf(" compat=[") + for i, c := range f.Compatible { + if i > 0 { + fmt.Printf(",") } + fmt.Printf("%s", string(c[:])) } + fmt.Printf("]") } - for _, child := range box.OtherBoxes { - printBox(child, depth+1) - } - } - // Stsd entries - if box.Stsd != nil { - for _, entry := range box.Stsd.Entries { - printBox(entry, depth+1) + case mp4.TypeMvhd: + ts, dur, ntid := r.ReadMvhd() + fmt.Printf(" timescale=%d duration=%d nextTrackId=%d", ts, dur, ntid) + + case mp4.TypeTkhd: + tid, dur, w, h := r.ReadTkhd() + fmt.Printf(" trackId=%d duration=%d size=%dx%d", tid, dur, w>>16, h>>16) + + case mp4.TypeMdhd: + ts, dur, lang := r.ReadMdhd() + fmt.Printf(" timescale=%d duration=%d lang=%d", ts, dur, lang) + + case mp4.TypeHdlr: + ht := r.ReadHdlr() + name := r.ReadHdlrName() + fmt.Printf(" type=%s name=%q", string(ht[:]), name) + + case mp4.TypeStsd: + if len(r.Data()) >= 4 { + fmt.Printf(" entries=%d", r.EntryCount()) } - } - // Visual/audio children - if box.Visual != nil { - for _, child := range box.Visual.Children { - printBox(child, depth+1) + case mp4.TypeStsz: + it := mp4.NewStszIter(r.Data()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeStco, mp4.TypeStss: + it := mp4.NewUint32Iter(r.Data()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeCo64: + it := mp4.NewCo64Iter(r.Data()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeStts: + it := mp4.NewSttsIter(r.Data()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeCtts: + it := mp4.NewCttsIter(r.Data()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeStsc: + it := mp4.NewStscIter(r.Data()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeElst: + it := mp4.NewElstIter(r.Data(), r.Version()) + fmt.Printf(" entries=%d", it.Count()) + + case mp4.TypeDref: + if len(r.Data()) >= 4 { + fmt.Printf(" entries=%d", r.EntryCount()) } - } - if box.Audio != nil { - for _, child := range box.Audio.Children { - printBox(child, depth+1) + + case mp4.TypeMehd: + dur := r.ReadMehd() + fmt.Printf(" fragmentDuration=%d", dur) + + case mp4.TypeTrex: + tid, _, _, _, _ := r.ReadTrex() + fmt.Printf(" trackId=%d", tid) + + case mp4.TypeMfhd: + seq := r.ReadMfhd() + fmt.Printf(" seq=%d", seq) + + case mp4.TypeTfhd: + tid := r.ReadTfhd() + fmt.Printf(" trackId=%d", tid) + + case mp4.TypeTfdt: + bt := r.ReadTfdt() + fmt.Printf(" baseMediaDecodeTime=%d", bt) + + case mp4.TypeTrun: + it := mp4.NewTrunIter(r.Data(), r.Flags()) + fmt.Printf(" entries=%d", it.Count()) + if r.Flags()&mp4.TrunDataOffsetPresent != 0 { + fmt.Printf(" dataOffset=%d", it.DataOffset()) } - } -} -func boxInfo(box *mp4.Box) string { - switch { - case box.Ftyp != nil: - f := box.Ftyp - brands := make([]string, len(f.CompatibleBrands)) - for i, b := range f.CompatibleBrands { - brands[i] = string(b[:]) + case mp4.TypeMdat: + fmt.Printf(" dataLen=%d", len(r.Data())) + + case mp4.TypeVmhd: + // graphicsMode and opcolor + case mp4.TypeSmhd: + // balance + default: + if !mp4.IsContainerBox(r.Type()) { + if len(r.Data()) > 0 { + fmt.Printf(" (%d bytes)", len(r.Data())) + } } - return fmt.Sprintf(" brand=%s ver=%d compat=[%s]", string(f.Brand[:]), f.BrandVersion, strings.Join(brands, ",")) - case box.Mvhd != nil: - m := box.Mvhd - return fmt.Sprintf(" timescale=%d duration=%d nextTrackId=%d", m.TimeScale, m.Duration, m.NextTrackId) - case box.Tkhd != nil: - t := box.Tkhd - return fmt.Sprintf(" trackId=%d duration=%d size=%dx%d", t.TrackId, t.Duration, t.TrackWidth>>16, t.TrackHeight>>16) - case box.Mdhd != nil: - m := box.Mdhd - return fmt.Sprintf(" timescale=%d duration=%d lang=%d", m.TimeScale, m.Duration, m.Language) - case box.Hdlr != nil: - h := box.Hdlr - return fmt.Sprintf(" type=%s name=%q", string(h.HandlerType[:]), h.Name) - case box.Stsd != nil: - return fmt.Sprintf(" entries=%d", len(box.Stsd.Entries)) - case box.Stsz != nil: - return fmt.Sprintf(" entries=%d", len(box.Stsz.Entries)) - case box.Stco != nil: - return fmt.Sprintf(" entries=%d", len(box.Stco.Entries)) - case box.Co64 != nil: - return fmt.Sprintf(" entries=%d", len(box.Co64.Entries)) - case box.Stts != nil: - return fmt.Sprintf(" entries=%d", len(box.Stts.Entries)) - case box.Ctts != nil: - return fmt.Sprintf(" entries=%d", len(box.Ctts.Entries)) - case box.Stsc != nil: - return fmt.Sprintf(" entries=%d", len(box.Stsc.Entries)) - case box.Elst != nil: - return fmt.Sprintf(" entries=%d", len(box.Elst.Entries)) - case box.Dref != nil: - return fmt.Sprintf(" entries=%d", len(box.Dref.Entries)) - case box.Visual != nil: - v := box.Visual - return fmt.Sprintf(" %dx%d compressor=%q children=%d", v.Width, v.Height, v.CompressorName, len(v.Children)) - case box.Audio != nil: - a := box.Audio - return fmt.Sprintf(" ch=%d sampleSize=%d sampleRate=%d children=%d", a.ChannelCount, a.SampleSize, a.SampleRate, len(a.Children)) - case box.AvcC != nil: - return fmt.Sprintf(" mimeCodec=%s bufLen=%d", box.AvcC.MimeCodec, len(box.AvcC.Buffer)) - case box.Esds != nil: - return fmt.Sprintf(" mimeCodec=%s bufLen=%d", box.Esds.MimeCodec, len(box.Esds.Buffer)) - case box.Mdat != nil: - return fmt.Sprintf(" dataLen=%d", len(box.Mdat.Buffer)) - case box.Mfhd != nil: - return fmt.Sprintf(" seq=%d", box.Mfhd.SequenceNumber) - case box.Buffer != nil: - return fmt.Sprintf(" (raw %d bytes)", len(box.Buffer)) } - return "" } diff --git a/codec.go b/codec.go deleted file mode 100644 index be78577..0000000 --- a/codec.go +++ /dev/null @@ -1,1196 +0,0 @@ -package mp4 - -import ( - "encoding/binary" - "fmt" -) - -// Codec types for each known box. - -// Ftyp represents the file type box. -type Ftyp struct { - Brand [4]byte - BrandVersion uint32 - CompatibleBrands [][4]byte -} - -// Mvhd represents the movie header box. -type Mvhd struct { - CTime [4]byte // raw 4-byte date - MTime [4]byte - TimeScale uint32 - Duration uint32 - PreferredRate [4]byte // raw 16.16 fixed - PreferredVolume [2]byte // raw 8.8 fixed - Matrix [36]byte - PreviewTime uint32 - PreviewDuration uint32 - PosterTime uint32 - SelectionTime uint32 - SelectionDuration uint32 - CurrentTime uint32 - NextTrackId uint32 -} - -// Tkhd represents the track header box. -type Tkhd struct { - CTime [4]byte - MTime [4]byte - TrackId uint32 - Duration uint32 - Layer uint16 - AlternateGroup uint16 - Volume uint16 - Matrix [36]byte - TrackWidth uint32 - TrackHeight uint32 -} - -// Mdhd represents the media header box. -type Mdhd struct { - CTime [8]byte // 4 or 8 bytes depending on version - MTime [8]byte - TimeScale uint32 - Duration uint64 - Language uint16 - Quality uint16 - V1 bool // true if version 1 -} - -// Vmhd represents the video media header box. -type Vmhd struct { - GraphicsMode uint16 - Opcolor [3]uint16 -} - -// Smhd represents the sound media header box. -type Smhd struct { - Balance uint16 -} - -// Stsd represents the sample description box. -type Stsd struct { - Entries []*Box -} - -// VisualSampleEntry represents a visual sample entry (e.g. avc1). -type VisualSampleEntry struct { - DataReferenceIndex uint16 - Width uint16 - Height uint16 - HResolution uint32 - VResolution uint32 - FrameCount uint16 - CompressorName string - Depth uint16 - Children []*Box -} - -// AvcC represents the AVC configuration box. -type AvcC struct { - MimeCodec string - Buffer []byte -} - -// AudioSampleEntry represents an audio sample entry (e.g. mp4a). -type AudioSampleEntry struct { - DataReferenceIndex uint16 - ChannelCount uint16 - SampleSize uint16 - SampleRate uint32 - Children []*Box -} - -// Esds represents the elementary stream descriptor box. -type Esds struct { - MimeCodec string - Buffer []byte -} - -// Stsz represents the sample size box. -type Stsz struct { - SampleSize uint32 - Entries []uint32 -} - -// Stco represents the chunk offset box (also used for stss). -type Stco struct { - Entries []uint32 -} - -// Co64 represents the 64-bit chunk offset box. -type Co64 struct { - Entries []uint64 -} - -// STTSEntry is a time-to-sample entry. -type STTSEntry struct { - Count uint32 - Duration uint32 -} - -// Stts represents the time-to-sample box. -type Stts struct { - Entries []STTSEntry -} - -// CTTSEntry is a composition offset entry. -type CTTSEntry struct { - Count uint32 - CompositionOffset int32 -} - -// Ctts represents the composition offset box. -type Ctts struct { - Entries []CTTSEntry -} - -// STSCEntry is a sample-to-chunk entry. -type STSCEntry struct { - FirstChunk uint32 - SamplesPerChunk uint32 - SampleDescriptionId uint32 -} - -// Stsc represents the sample-to-chunk box. -type Stsc struct { - Entries []STSCEntry -} - -// DrefEntry is a data reference entry. -type DrefEntry struct { - Type [4]byte - Buf []byte -} - -// DrefBox represents the data reference box. -type DrefBox struct { - Entries []DrefEntry -} - -// ElstEntry is an edit list entry. -type ElstEntry struct { - TrackDuration uint32 - MediaTime int32 - MediaRate [4]byte // raw fixed 16.16 -} - -// Elst represents the edit list box. -type Elst struct { - Entries []ElstEntry -} - -// Hdlr represents the handler reference box. -type Hdlr struct { - HandlerType [4]byte - Name string -} - -// Mehd represents the movie extends header box. -type Mehd struct { - FragmentDuration uint32 -} - -// Trex represents the track extends box. -type Trex struct { - TrackId uint32 - DefaultSampleDescriptionIndex uint32 - DefaultSampleDuration uint32 - DefaultSampleSize uint32 - DefaultSampleFlags uint32 -} - -// Mfhd represents the movie fragment header box. -type Mfhd struct { - SequenceNumber uint32 -} - -// Tfhd represents the track fragment header box. -type Tfhd struct { - TrackId uint32 -} - -// Tfdt represents the track fragment decode time box. -type Tfdt struct { - BaseMediaDecodeTime uint32 -} - -// TrunEntry is a track run entry. -type TrunEntry struct { - SampleDuration uint32 - SampleSize uint32 - SampleFlags uint32 - SampleCompositionTimeOffset int32 -} - -// Trun represents the track run box. -type Trun struct { - DataOffset int32 - Entries []TrunEntry -} - -// Mdat represents the media data box. -type Mdat struct { - Buffer []byte - ContentLength int -} - -// codec is an internal interface for box-specific encoding/decoding. -type codec struct { - decode func(box *Box, buf []byte, start, end int) error - encode func(box *Box, buf []byte, offset int) int - encodingLength func(box *Box) int -} - -var codecs = map[BoxType]*codec{} - -func getCodec(t BoxType) *codec { - return codecs[t] -} - -func init() { - codecs[TypeFtyp] = &codec{decodeFtyp, encodeFtyp, encodingLengthFtyp} - codecs[TypeMvhd] = &codec{decodeMvhd, encodeMvhd, encodingLengthMvhd} - codecs[TypeTkhd] = &codec{decodeTkhd, encodeTkhd, encodingLengthTkhd} - codecs[TypeMdhd] = &codec{decodeMdhd, encodeMdhd, encodingLengthMdhd} - codecs[TypeVmhd] = &codec{decodeVmhd, encodeVmhd, encodingLengthVmhd} - codecs[TypeSmhd] = &codec{decodeSmhd, encodeSmhd, encodingLengthSmhd} - codecs[TypeStsd] = &codec{decodeStsd, encodeStsd, encodingLengthStsd} - codecs[TypeAvc1] = &codec{decodeVisual, encodeVisual, encodingLengthVisual} - codecs[TypeAvcC] = &codec{decodeAvcC, encodeAvcC, encodingLengthAvcC} - codecs[TypeMp4a] = &codec{decodeAudio, encodeAudio, encodingLengthAudio} - codecs[TypeEsds] = &codec{decodeEsds, encodeEsds, encodingLengthEsds} - codecs[TypeStsz] = &codec{decodeStsz, encodeStsz, encodingLengthStsz} - codecs[TypeStco] = &codec{decodeStco, encodeStco, encodingLengthStco} - codecs[TypeStss] = &codec{decodeStco, encodeStco, encodingLengthStco} // same format as stco - codecs[TypeCo64] = &codec{decodeCo64, encodeCo64, encodingLengthCo64} - codecs[TypeStts] = &codec{decodeStts, encodeStts, encodingLengthStts} - codecs[TypeCtts] = &codec{decodeCtts, encodeCtts, encodingLengthCtts} - codecs[TypeStsc] = &codec{decodeStsc, encodeStsc, encodingLengthStsc} - codecs[TypeDref] = &codec{decodeDref, encodeDref, encodingLengthDref} - codecs[TypeElst] = &codec{decodeElst, encodeElst, encodingLengthElst} - codecs[TypeHdlr] = &codec{decodeHdlr, encodeHdlr, encodingLengthHdlr} - codecs[TypeMehd] = &codec{decodeMehd, encodeMehd, encodingLengthMehd} - codecs[TypeTrex] = &codec{decodeTrex, encodeTrex, encodingLengthTrex} - codecs[TypeMfhd] = &codec{decodeMfhd, encodeMfhd, encodingLengthMfhd} - codecs[TypeTfhd] = &codec{decodeTfhd, encodeTfhd, encodingLengthTfhd} - codecs[TypeTfdt] = &codec{decodeTfdt, encodeTfdt, encodingLengthTfdt} - codecs[TypeTrun] = &codec{decodeTrun, encodeTrun, encodingLengthTrun} - codecs[TypeMdat] = &codec{decodeMdat, encodeMdat, encodingLengthMdat} -} - -// --- ftyp --- - -func decodeFtyp(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - if len(b) < 8 { - return fmt.Errorf("ftyp too short") - } - f := &Ftyp{} - copy(f.Brand[:], b[0:4]) - f.BrandVersion = be.Uint32(b[4:8]) - for i := 8; i+4 <= len(b); i += 4 { - var brand [4]byte - copy(brand[:], b[i:i+4]) - f.CompatibleBrands = append(f.CompatibleBrands, brand) - } - box.Ftyp = f - return nil -} - -func encodeFtyp(box *Box, buf []byte, offset int) int { - f := box.Ftyp - b := buf[offset:] - copy(b[0:4], f.Brand[:]) - be.PutUint32(b[4:8], f.BrandVersion) - for i, brand := range f.CompatibleBrands { - copy(b[8+i*4:], brand[:]) - } - return 8 + len(f.CompatibleBrands)*4 -} - -func encodingLengthFtyp(box *Box) int { - return 8 + len(box.Ftyp.CompatibleBrands)*4 -} - -// --- mvhd --- - -func decodeMvhd(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - m := &Mvhd{} - copy(m.CTime[:], b[0:4]) - copy(m.MTime[:], b[4:8]) - m.TimeScale = be.Uint32(b[8:12]) - m.Duration = be.Uint32(b[12:16]) - copy(m.PreferredRate[:], b[16:20]) - copy(m.PreferredVolume[:], b[20:22]) - copy(m.Matrix[:], b[32:68]) - m.PreviewTime = be.Uint32(b[68:72]) - m.PreviewDuration = be.Uint32(b[72:76]) - m.PosterTime = be.Uint32(b[76:80]) - m.SelectionTime = be.Uint32(b[80:84]) - m.SelectionDuration = be.Uint32(b[84:88]) - m.CurrentTime = be.Uint32(b[88:92]) - m.NextTrackId = be.Uint32(b[92:96]) - box.Mvhd = m - return nil -} - -func encodeMvhd(box *Box, buf []byte, offset int) int { - b := buf[offset:] - m := box.Mvhd - copy(b[0:4], m.CTime[:]) - copy(b[4:8], m.MTime[:]) - be.PutUint32(b[8:12], m.TimeScale) - be.PutUint32(b[12:16], m.Duration) - copy(b[16:20], m.PreferredRate[:]) - copy(b[20:22], m.PreferredVolume[:]) - clearBytes(b, 22, 32) - copy(b[32:68], m.Matrix[:]) - be.PutUint32(b[68:72], m.PreviewTime) - be.PutUint32(b[72:76], m.PreviewDuration) - be.PutUint32(b[76:80], m.PosterTime) - be.PutUint32(b[80:84], m.SelectionTime) - be.PutUint32(b[84:88], m.SelectionDuration) - be.PutUint32(b[88:92], m.CurrentTime) - be.PutUint32(b[92:96], m.NextTrackId) - return 96 -} - -func encodingLengthMvhd(_ *Box) int { return 96 } - -// --- tkhd --- - -func decodeTkhd(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - t := &Tkhd{} - copy(t.CTime[:], b[0:4]) - copy(t.MTime[:], b[4:8]) - t.TrackId = be.Uint32(b[8:12]) - t.Duration = be.Uint32(b[16:20]) - t.Layer = be.Uint16(b[28:30]) - t.AlternateGroup = be.Uint16(b[30:32]) - t.Volume = be.Uint16(b[32:34]) - copy(t.Matrix[:], b[36:72]) - t.TrackWidth = be.Uint32(b[72:76]) - t.TrackHeight = be.Uint32(b[76:80]) - box.Tkhd = t - return nil -} - -func encodeTkhd(box *Box, buf []byte, offset int) int { - b := buf[offset:] - t := box.Tkhd - copy(b[0:4], t.CTime[:]) - copy(b[4:8], t.MTime[:]) - be.PutUint32(b[8:12], t.TrackId) - clearBytes(b, 12, 16) - be.PutUint32(b[16:20], t.Duration) - clearBytes(b, 20, 28) - be.PutUint16(b[28:30], t.Layer) - be.PutUint16(b[30:32], t.AlternateGroup) - be.PutUint16(b[32:34], t.Volume) - clearBytes(b, 34, 36) - copy(b[36:72], t.Matrix[:]) - be.PutUint32(b[72:76], t.TrackWidth) - be.PutUint32(b[76:80], t.TrackHeight) - return 80 -} - -func encodingLengthTkhd(_ *Box) int { return 80 } - -// --- mdhd --- - -func decodeMdhd(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - m := &Mdhd{} - contentLen := end - start - - if contentLen != 20 { - // version 1: 8-byte times - m.V1 = true - copy(m.CTime[:], b[0:8]) - copy(m.MTime[:], b[8:16]) - m.TimeScale = be.Uint32(b[16:20]) - // Read 6 bytes for duration (48-bit) - m.Duration = uint64(b[20])<<40 | uint64(b[21])<<32 | uint64(b[22])<<24 | - uint64(b[23])<<16 | uint64(b[24])<<8 | uint64(b[25]) - m.Language = be.Uint16(b[28:30]) - m.Quality = be.Uint16(b[30:32]) - } else { - copy(m.CTime[:4], b[0:4]) - copy(m.MTime[:4], b[4:8]) - m.TimeScale = be.Uint32(b[8:12]) - m.Duration = uint64(be.Uint32(b[12:16])) - m.Language = be.Uint16(b[16:18]) - m.Quality = be.Uint16(b[18:20]) - } - box.Mdhd = m - return nil -} - -func encodeMdhd(box *Box, buf []byte, offset int) int { - b := buf[offset:] - m := box.Mdhd - - if m.V1 { - copy(b[0:8], m.CTime[:]) - copy(b[8:16], m.MTime[:]) - be.PutUint32(b[16:20], m.TimeScale) - // Write 6 bytes for duration - b[20] = byte(m.Duration >> 40) - b[21] = byte(m.Duration >> 32) - b[22] = byte(m.Duration >> 24) - b[23] = byte(m.Duration >> 16) - b[24] = byte(m.Duration >> 8) - b[25] = byte(m.Duration) - clearBytes(b, 26, 28) - be.PutUint16(b[28:30], m.Language) - be.PutUint16(b[30:32], m.Quality) - return 32 - } - - copy(b[0:4], m.CTime[:4]) - copy(b[4:8], m.MTime[:4]) - be.PutUint32(b[8:12], m.TimeScale) - be.PutUint32(b[12:16], uint32(m.Duration)) - be.PutUint16(b[16:18], m.Language) - be.PutUint16(b[18:20], m.Quality) - return 20 -} - -func encodingLengthMdhd(box *Box) int { - if box.Mdhd.V1 { - return 32 - } - return 20 -} - -// --- vmhd --- - -func decodeVmhd(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - box.Vmhd = &Vmhd{ - GraphicsMode: be.Uint16(b[0:2]), - Opcolor: [3]uint16{be.Uint16(b[2:4]), be.Uint16(b[4:6]), be.Uint16(b[6:8])}, - } - return nil -} - -func encodeVmhd(box *Box, buf []byte, offset int) int { - b := buf[offset:] - v := box.Vmhd - be.PutUint16(b[0:2], v.GraphicsMode) - be.PutUint16(b[2:4], v.Opcolor[0]) - be.PutUint16(b[4:6], v.Opcolor[1]) - be.PutUint16(b[6:8], v.Opcolor[2]) - return 8 -} - -func encodingLengthVmhd(_ *Box) int { return 8 } - -// --- smhd --- - -func decodeSmhd(box *Box, buf []byte, start, _ int) error { - box.Smhd = &Smhd{Balance: be.Uint16(buf[start:])} - return nil -} - -func encodeSmhd(box *Box, buf []byte, offset int) int { - be.PutUint16(buf[offset:], box.Smhd.Balance) - clearBytes(buf, offset+2, offset+4) - return 4 -} - -func encodingLengthSmhd(_ *Box) int { return 4 } - -// --- stsd --- - -func decodeStsd(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - num := int(be.Uint32(b[0:4])) - s := &Stsd{Entries: make([]*Box, num)} - ptr := 4 - for i := 0; i < num; i++ { - entry, err := Decode(buf, start+ptr, end) - if err != nil { - return err - } - s.Entries[i] = entry - ptr += int(entry.Size) - } - box.Stsd = s - return nil -} - -func encodeStsd(box *Box, buf []byte, offset int) int { - s := box.Stsd - be.PutUint32(buf[offset:], uint32(len(s.Entries))) - ptr := offset + 4 - for _, entry := range s.Entries { - n, _ := encodeBox(entry, buf, ptr) - ptr += n - } - return ptr - offset -} - -func encodingLengthStsd(box *Box) int { - total := 4 - for _, entry := range box.Stsd.Entries { - total += int(EncodingLength(entry)) - } - return total -} - -// --- avc1 / VisualSampleEntry --- - -func decodeVisual(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - length := end - start - nameLen := int(b[42]) - if nameLen > 31 { - nameLen = 31 - } - v := &VisualSampleEntry{ - DataReferenceIndex: be.Uint16(b[6:8]), - Width: be.Uint16(b[24:26]), - Height: be.Uint16(b[26:28]), - HResolution: be.Uint32(b[28:32]), - VResolution: be.Uint32(b[32:36]), - FrameCount: be.Uint16(b[40:42]), - CompressorName: string(b[43 : 43+nameLen]), - Depth: be.Uint16(b[74:76]), - } - - ptr := 78 - for length-ptr >= 8 { - child, err := Decode(buf, start+ptr, end) - if err != nil { - return err - } - v.Children = append(v.Children, child) - ptr += int(child.Size) - } - box.Visual = v - return nil -} - -func encodeVisual(box *Box, buf []byte, offset int) int { - b := buf[offset:] - v := box.Visual - clearBytes(b, 0, 6) - be.PutUint16(b[6:8], v.DataReferenceIndex) - clearBytes(b, 8, 24) - be.PutUint16(b[24:26], v.Width) - be.PutUint16(b[26:28], v.Height) - hRes := v.HResolution - if hRes == 0 { - hRes = 0x480000 - } - be.PutUint32(b[28:32], hRes) - vRes := v.VResolution - if vRes == 0 { - vRes = 0x480000 - } - be.PutUint32(b[32:36], vRes) - clearBytes(b, 36, 40) - fc := v.FrameCount - if fc == 0 { - fc = 1 - } - be.PutUint16(b[40:42], fc) - nameLen := len(v.CompressorName) - if nameLen > 31 { - nameLen = 31 - } - b[42] = byte(nameLen) - copy(b[43:], v.CompressorName[:nameLen]) - clearBytes(b, 43+nameLen, 74) - depth := v.Depth - if depth == 0 { - depth = 0x18 - } - be.PutUint16(b[74:76], depth) - binary.BigEndian.PutUint16(b[76:78], 0xffff) // -1 as int16 - - ptr := 78 - for _, child := range v.Children { - n, _ := encodeBox(child, buf, offset+ptr) - ptr += n - } - return ptr -} - -func encodingLengthVisual(box *Box) int { - n := 78 - for _, child := range box.Visual.Children { - n += int(EncodingLength(child)) - } - return n -} - -// --- avcC --- - -func decodeAvcC(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - a := &AvcC{ - Buffer: make([]byte, len(b)), - } - copy(a.Buffer, b) - if len(b) >= 4 { - a.MimeCodec = fmt.Sprintf("%02x%02x%02x", b[1], b[2], b[3]) - } - box.AvcC = a - return nil -} - -func encodeAvcC(box *Box, buf []byte, offset int) int { - copy(buf[offset:], box.AvcC.Buffer) - return len(box.AvcC.Buffer) -} - -func encodingLengthAvcC(box *Box) int { return len(box.AvcC.Buffer) } - -// --- mp4a / AudioSampleEntry --- - -func decodeAudio(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - length := end - start - a := &AudioSampleEntry{ - DataReferenceIndex: be.Uint16(b[6:8]), - ChannelCount: be.Uint16(b[16:18]), - SampleSize: be.Uint16(b[18:20]), - SampleRate: be.Uint32(b[24:28]), - } - - ptr := 28 - for length-ptr >= 8 { - child, err := Decode(buf, start+ptr, end) - if err != nil { - return err - } - a.Children = append(a.Children, child) - ptr += int(child.Size) - } - box.Audio = a - return nil -} - -func encodeAudio(box *Box, buf []byte, offset int) int { - b := buf[offset:] - a := box.Audio - clearBytes(b, 0, 6) - be.PutUint16(b[6:8], a.DataReferenceIndex) - clearBytes(b, 8, 16) - cc := a.ChannelCount - if cc == 0 { - cc = 2 - } - be.PutUint16(b[16:18], cc) - ss := a.SampleSize - if ss == 0 { - ss = 16 - } - be.PutUint16(b[18:20], ss) - clearBytes(b, 20, 24) - be.PutUint32(b[24:28], a.SampleRate) - - ptr := 28 - for _, child := range a.Children { - n, _ := encodeBox(child, buf, offset+ptr) - ptr += n - } - return ptr -} - -func encodingLengthAudio(box *Box) int { - n := 28 - for _, child := range box.Audio.Children { - n += int(EncodingLength(child)) - } - return n -} - -// --- esds --- - -func decodeEsds(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - e := &Esds{ - Buffer: make([]byte, len(b)), - } - copy(e.Buffer, b) - - // Parse descriptor for mimeCodec - desc := decodeDescriptor(b, 0, len(b)) - if desc != nil && desc.tagName == "ESDescriptor" { - if dcd, ok := desc.children["DecoderConfigDescriptor"]; ok { - oti := dcd.oti - if oti != 0 { - e.MimeCodec = fmt.Sprintf("%x", oti) - if dsi, ok := dcd.children["DecoderSpecificInfo"]; ok && len(dsi.buffer) > 0 { - audioConfig := (dsi.buffer[0] & 0xf8) >> 3 - if audioConfig != 0 { - e.MimeCodec += fmt.Sprintf(".%d", audioConfig) - } - } - } - } - } - box.Esds = e - return nil -} - -func encodeEsds(box *Box, buf []byte, offset int) int { - copy(buf[offset:], box.Esds.Buffer) - return len(box.Esds.Buffer) -} - -func encodingLengthEsds(box *Box) int { return len(box.Esds.Buffer) } - -// --- stsz --- - -func decodeStsz(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - sampleSize := be.Uint32(b[0:4]) - num := int(be.Uint32(b[4:8])) - entries := make([]uint32, num) - for i := 0; i < num; i++ { - if sampleSize == 0 { - entries[i] = be.Uint32(b[8+i*4:]) - } else { - entries[i] = sampleSize - } - } - box.Stsz = &Stsz{SampleSize: sampleSize, Entries: entries} - return nil -} - -func encodeStsz(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Stsz - be.PutUint32(b[0:4], 0) - be.PutUint32(b[4:8], uint32(len(s.Entries))) - for i, e := range s.Entries { - be.PutUint32(b[8+i*4:], e) - } - return 8 + len(s.Entries)*4 -} - -func encodingLengthStsz(box *Box) int { - return 8 + len(box.Stsz.Entries)*4 -} - -// --- stco / stss --- - -func decodeStco(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]uint32, num) - for i := 0; i < num; i++ { - entries[i] = be.Uint32(b[4+i*4:]) - } - box.Stco = &Stco{Entries: entries} - return nil -} - -func encodeStco(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Stco - be.PutUint32(b[0:4], uint32(len(s.Entries))) - for i, e := range s.Entries { - be.PutUint32(b[4+i*4:], e) - } - return 4 + len(s.Entries)*4 -} - -func encodingLengthStco(box *Box) int { - return 4 + len(box.Stco.Entries)*4 -} - -// --- co64 --- - -func decodeCo64(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]uint64, num) - for i := 0; i < num; i++ { - entries[i] = be.Uint64(b[4+i*8:]) - } - box.Co64 = &Co64{Entries: entries} - return nil -} - -func encodeCo64(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Co64 - be.PutUint32(b[0:4], uint32(len(s.Entries))) - for i, e := range s.Entries { - be.PutUint64(b[4+i*8:], e) - } - return 4 + len(s.Entries)*8 -} - -func encodingLengthCo64(box *Box) int { - return 4 + len(box.Co64.Entries)*8 -} - -// --- stts --- - -func decodeStts(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]STTSEntry, num) - for i := 0; i < num; i++ { - ptr := 4 + i*8 - entries[i] = STTSEntry{ - Count: be.Uint32(b[ptr:]), - Duration: be.Uint32(b[ptr+4:]), - } - } - box.Stts = &Stts{Entries: entries} - return nil -} - -func encodeStts(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Stts - be.PutUint32(b[0:4], uint32(len(s.Entries))) - for i, e := range s.Entries { - ptr := 4 + i*8 - be.PutUint32(b[ptr:], e.Count) - be.PutUint32(b[ptr+4:], e.Duration) - } - return 4 + len(s.Entries)*8 -} - -func encodingLengthStts(box *Box) int { - return 4 + len(box.Stts.Entries)*8 -} - -// --- ctts --- - -func decodeCtts(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]CTTSEntry, num) - for i := 0; i < num; i++ { - ptr := 4 + i*8 - entries[i] = CTTSEntry{ - Count: be.Uint32(b[ptr:]), - CompositionOffset: int32(be.Uint32(b[ptr+4:])), - } - } - box.Ctts = &Ctts{Entries: entries} - return nil -} - -func encodeCtts(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Ctts - be.PutUint32(b[0:4], uint32(len(s.Entries))) - for i, e := range s.Entries { - ptr := 4 + i*8 - be.PutUint32(b[ptr:], e.Count) - be.PutUint32(b[ptr+4:], uint32(e.CompositionOffset)) - } - return 4 + len(s.Entries)*8 -} - -func encodingLengthCtts(box *Box) int { - return 4 + len(box.Ctts.Entries)*8 -} - -// --- stsc --- - -func decodeStsc(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]STSCEntry, num) - for i := 0; i < num; i++ { - ptr := 4 + i*12 - entries[i] = STSCEntry{ - FirstChunk: be.Uint32(b[ptr:]), - SamplesPerChunk: be.Uint32(b[ptr+4:]), - SampleDescriptionId: be.Uint32(b[ptr+8:]), - } - } - box.Stsc = &Stsc{Entries: entries} - return nil -} - -func encodeStsc(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Stsc - be.PutUint32(b[0:4], uint32(len(s.Entries))) - for i, e := range s.Entries { - ptr := 4 + i*12 - be.PutUint32(b[ptr:], e.FirstChunk) - be.PutUint32(b[ptr+4:], e.SamplesPerChunk) - be.PutUint32(b[ptr+8:], e.SampleDescriptionId) - } - return 4 + len(s.Entries)*12 -} - -func encodingLengthStsc(box *Box) int { - return 4 + len(box.Stsc.Entries)*12 -} - -// --- dref --- - -func decodeDref(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]DrefEntry, num) - ptr := 4 - for i := 0; i < num; i++ { - size := int(be.Uint32(b[ptr:])) - var t [4]byte - copy(t[:], b[ptr+4:ptr+8]) - dataBuf := make([]byte, size-8) - copy(dataBuf, b[ptr+8:ptr+size]) - entries[i] = DrefEntry{Type: t, Buf: dataBuf} - ptr += size - } - box.Dref = &DrefBox{Entries: entries} - return nil -} - -func encodeDref(box *Box, buf []byte, offset int) int { - b := buf[offset:] - d := box.Dref - be.PutUint32(b[0:4], uint32(len(d.Entries))) - ptr := 4 - for _, e := range d.Entries { - size := 8 + len(e.Buf) - be.PutUint32(b[ptr:], uint32(size)) - copy(b[ptr+4:], e.Type[:]) - copy(b[ptr+8:], e.Buf) - ptr += size - } - return ptr -} - -func encodingLengthDref(box *Box) int { - total := 4 - for _, e := range box.Dref.Entries { - total += 8 + len(e.Buf) - } - return total -} - -// --- elst --- - -func decodeElst(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - entries := make([]ElstEntry, num) - for i := 0; i < num; i++ { - ptr := 4 + i*12 - var mr [4]byte - copy(mr[:], b[ptr+8:ptr+12]) - entries[i] = ElstEntry{ - TrackDuration: be.Uint32(b[ptr:]), - MediaTime: int32(be.Uint32(b[ptr+4:])), - MediaRate: mr, - } - } - box.Elst = &Elst{Entries: entries} - return nil -} - -func encodeElst(box *Box, buf []byte, offset int) int { - b := buf[offset:] - s := box.Elst - be.PutUint32(b[0:4], uint32(len(s.Entries))) - for i, e := range s.Entries { - ptr := 4 + i*12 - be.PutUint32(b[ptr:], e.TrackDuration) - be.PutUint32(b[ptr+4:], uint32(e.MediaTime)) - copy(b[ptr+8:ptr+12], e.MediaRate[:]) - } - return 4 + len(s.Entries)*12 -} - -func encodingLengthElst(box *Box) int { - return 4 + len(box.Elst.Entries)*12 -} - -// --- hdlr --- - -func decodeHdlr(box *Box, buf []byte, start, end int) error { - b := buf[start:end] - h := &Hdlr{} - copy(h.HandlerType[:], b[4:8]) - h.Name = readString(b, 20, end-start) - box.Hdlr = h - return nil -} - -func encodeHdlr(box *Box, buf []byte, offset int) int { - b := buf[offset:] - h := box.Hdlr - nameLen := len(h.Name) - total := 21 + nameLen - clearBytes(b, 0, total) - copy(b[4:8], h.HandlerType[:]) - copy(b[20:], h.Name) - b[20+nameLen] = 0 - return total -} - -func encodingLengthHdlr(box *Box) int { - return 21 + len(box.Hdlr.Name) -} - -// --- mehd --- - -func decodeMehd(box *Box, buf []byte, start, _ int) error { - box.Mehd = &Mehd{FragmentDuration: be.Uint32(buf[start:])} - return nil -} - -func encodeMehd(box *Box, buf []byte, offset int) int { - be.PutUint32(buf[offset:], box.Mehd.FragmentDuration) - return 4 -} - -func encodingLengthMehd(_ *Box) int { return 4 } - -// --- trex --- - -func decodeTrex(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - box.Trex = &Trex{ - TrackId: be.Uint32(b[0:4]), - DefaultSampleDescriptionIndex: be.Uint32(b[4:8]), - DefaultSampleDuration: be.Uint32(b[8:12]), - DefaultSampleSize: be.Uint32(b[12:16]), - DefaultSampleFlags: be.Uint32(b[16:20]), - } - return nil -} - -func encodeTrex(box *Box, buf []byte, offset int) int { - b := buf[offset:] - t := box.Trex - be.PutUint32(b[0:4], t.TrackId) - be.PutUint32(b[4:8], t.DefaultSampleDescriptionIndex) - be.PutUint32(b[8:12], t.DefaultSampleDuration) - be.PutUint32(b[12:16], t.DefaultSampleSize) - be.PutUint32(b[16:20], t.DefaultSampleFlags) - return 20 -} - -func encodingLengthTrex(_ *Box) int { return 20 } - -// --- mfhd --- - -func decodeMfhd(box *Box, buf []byte, start, _ int) error { - box.Mfhd = &Mfhd{SequenceNumber: be.Uint32(buf[start:])} - return nil -} - -func encodeMfhd(box *Box, buf []byte, offset int) int { - be.PutUint32(buf[offset:], box.Mfhd.SequenceNumber) - return 4 -} - -func encodingLengthMfhd(_ *Box) int { return 4 } - -// --- tfhd --- - -func decodeTfhd(box *Box, buf []byte, start, _ int) error { - box.Tfhd = &Tfhd{TrackId: be.Uint32(buf[start:])} - return nil -} - -func encodeTfhd(box *Box, buf []byte, offset int) int { - be.PutUint32(buf[offset:], box.Tfhd.TrackId) - return 4 -} - -func encodingLengthTfhd(_ *Box) int { return 4 } - -// --- tfdt --- - -func decodeTfdt(box *Box, buf []byte, start, _ int) error { - box.Tfdt = &Tfdt{BaseMediaDecodeTime: be.Uint32(buf[start:])} - return nil -} - -func encodeTfdt(box *Box, buf []byte, offset int) int { - be.PutUint32(buf[offset:], box.Tfdt.BaseMediaDecodeTime) - return 4 -} - -func encodingLengthTfdt(_ *Box) int { return 4 } - -// --- trun --- - -func decodeTrun(box *Box, buf []byte, start, _ int) error { - b := buf[start:] - num := int(be.Uint32(b[0:4])) - t := &Trun{ - DataOffset: int32(be.Uint32(b[4:8])), - Entries: make([]TrunEntry, num), - } - ptr := 8 - for i := 0; i < num; i++ { - e := TrunEntry{ - SampleDuration: be.Uint32(b[ptr:]), - SampleSize: be.Uint32(b[ptr+4:]), - SampleFlags: be.Uint32(b[ptr+8:]), - SampleCompositionTimeOffset: int32(be.Uint32(b[ptr+12:])), - } - t.Entries[i] = e - ptr += 16 - } - box.Trun = t - return nil -} - -func encodeTrun(box *Box, buf []byte, offset int) int { - b := buf[offset:] - t := box.Trun - be.PutUint32(b[0:4], uint32(len(t.Entries))) - be.PutUint32(b[4:8], uint32(t.DataOffset)) - ptr := 8 - for _, e := range t.Entries { - be.PutUint32(b[ptr:], e.SampleDuration) - be.PutUint32(b[ptr+4:], e.SampleSize) - be.PutUint32(b[ptr+8:], e.SampleFlags) - be.PutUint32(b[ptr+12:], uint32(e.SampleCompositionTimeOffset)) - ptr += 16 - } - return ptr -} - -func encodingLengthTrun(box *Box) int { - return 8 + len(box.Trun.Entries)*16 -} - -// --- mdat --- - -func decodeMdat(box *Box, buf []byte, start, end int) error { - b := make([]byte, end-start) - copy(b, buf[start:end]) - box.Mdat = &Mdat{Buffer: b} - return nil -} - -func encodeMdat(box *Box, buf []byte, offset int) int { - m := box.Mdat - if m.Buffer != nil { - copy(buf[offset:], m.Buffer) - return len(m.Buffer) - } - return m.ContentLength -} - -func encodingLengthMdat(box *Box) int { - m := box.Mdat - if m.Buffer != nil { - return len(m.Buffer) - } - return m.ContentLength -} diff --git a/descriptor.go b/descriptor.go index a2574bf..746bec1 100644 --- a/descriptor.go +++ b/descriptor.go @@ -1,110 +1,110 @@ package mp4 -// descriptor implements MPEG-4 descriptor parsing for esds boxes. +import "strconv" -var tagToName = map[byte]string{ - 0x03: "ESDescriptor", - 0x04: "DecoderConfigDescriptor", - 0x05: "DecoderSpecificInfo", - 0x06: "SLConfigDescriptor", -} +// ReadEsdsCodec extracts the MIME codec string from esds box data. +// It parses the MPEG-4 descriptor chain to find the OTI (Object Type Indication) +// and audio configuration. Returns a string like "40.2" for AAC-LC. +func ReadEsdsCodec(data []byte) string { + if len(data) < 2 { + return "" + } -type descriptor struct { - tag byte - tagName string - length int - oti byte - buffer []byte - children map[string]*descriptor -} + // Expect ESDescriptor (tag 0x03) + ptr, end := 0, len(data) + if data[ptr] != 0x03 { + return "" + } + ptr++ -func decodeDescriptor(buf []byte, start, end int) *descriptor { - if start >= end { - return nil + // Skip length bytes (variable-length encoding) + ptr = skipDescriptorLength(data, ptr, end) + if ptr < 0 || ptr+3 > end { + return "" } - tag := buf[start] - ptr := start + 1 - length := 0 - for ptr < end { - lenByte := buf[ptr] - ptr++ - length = (length << 7) | int(lenByte&0x7f) - if lenByte&0x80 == 0 { - break + + // ES_ID (2 bytes) + stream dependency flags (1 byte) + flags := data[ptr+2] + ptr += 3 + + // Skip optional fields based on flags + if flags&0x80 != 0 { // streamDependenceFlag + ptr += 2 + } + if flags&0x40 != 0 { // URL_Flag + if ptr >= end { + return "" } + urlLen := int(data[ptr]) + ptr += 1 + urlLen } - - tagName := tagToName[tag] - d := &descriptor{ - tag: tag, - tagName: tagName, - length: (ptr - start) + length, - children: make(map[string]*descriptor), + if flags&0x20 != 0 { // OCRstreamFlag + ptr += 2 } - switch tagName { - case "ESDescriptor": - decodeESDescriptor(d, buf, ptr, end) - case "DecoderConfigDescriptor": - decodeDecoderConfigDescriptor(d, buf, ptr, end) - case "DecoderSpecificInfo": - dEnd := ptr + length - if dEnd > end { - dEnd = end - } - d.buffer = buf[ptr:dEnd] - default: - dEnd := min(ptr+length, end) - d.buffer = buf[ptr:dEnd] + if ptr >= end { + return "" } - return d -} + // Expect DecoderConfigDescriptor (tag 0x04) + if data[ptr] != 0x04 { + return "" + } + ptr++ + ptr = skipDescriptorLength(data, ptr, end) + if ptr < 0 || ptr+13 > end { + return "" + } -func decodeDescriptorArray(buf []byte, start, end int) map[string]*descriptor { - m := make(map[string]*descriptor) - ptr := start - for ptr+2 <= end { - desc := decodeDescriptor(buf, ptr, end) - if desc == nil { - break - } - ptr += desc.length - name := desc.tagName - if name == "" { - continue - } - m[name] = desc + oti := data[ptr] + if oti == 0 { + return "" } - return m -} -func decodeESDescriptor(d *descriptor, buf []byte, start, end int) { - if start+3 > end { - return + // Format OTI as hex + otiStr := hexByte(oti) + + // Skip to DecoderSpecificInfo: OTI(1)+streamType(1)+bufferSizeDB(3)+maxBitrate(4)+avgBitrate(4) = 13 + ptr += 13 + + if ptr >= end || data[ptr] != 0x05 { + // No DecoderSpecificInfo, return just OTI + return otiStr } - flags := buf[start+2] - ptr := start + 3 - if flags&0x80 != 0 { - ptr += 2 + ptr++ + ptr = skipDescriptorLength(data, ptr, end) + if ptr < 0 || ptr >= end { + return otiStr } - if flags&0x40 != 0 { - if ptr >= end { - return - } - l := int(buf[ptr]) - ptr += l + 1 + + // Extract audio object type from first byte + audioConfig := (data[ptr] & 0xf8) >> 3 + if audioConfig == 0 { + return otiStr } - if flags&0x20 != 0 { - ptr += 2 + return otiStr + "." + strconv.Itoa(int(audioConfig)) +} + +// hexByte formats a byte as a lowercase hex string without leading zeros beyond one digit. +func hexByte(b byte) string { + if b < 16 { + return string(hexDigit(b)) } - d.children = decodeDescriptorArray(buf, ptr, end) + var buf [2]byte + buf[0] = hexDigit(b >> 4) + buf[1] = hexDigit(b & 0x0f) + return string(buf[:]) } -func decodeDecoderConfigDescriptor(d *descriptor, buf []byte, start, end int) { - if start >= end { - return +// skipDescriptorLength skips the variable-length descriptor length field. +// Returns the new position, or -1 on error. +func skipDescriptorLength(data []byte, ptr, end int) int { + for ptr < end { + b := data[ptr] + ptr++ + if b&0x80 == 0 { + return ptr + } } - d.oti = buf[start] - d.children = decodeDescriptorArray(buf, start+13, end) + return -1 } @@ -0,0 +1,524 @@ +package mp4 + +import ( + "encoding/binary" + "math" +) + +var be = binary.BigEndian + +const uint32Max = math.MaxUint32 + +// StszIter iterates over sample sizes in an stsz box. +type StszIter struct { + buf []byte + sampleSize uint32 + count uint32 + index uint32 +} + +// NewStszIter creates an iterator from stsz box data. +func NewStszIter(data []byte) StszIter { + if len(data) < 8 { + return StszIter{} + } + return StszIter{ + buf: data, + sampleSize: be.Uint32(data[0:4]), + count: be.Uint32(data[4:8]), + } +} + +// Count returns the total number of samples. +func (it *StszIter) Count() uint32 { return it.count } + +// Next returns the next sample size. Returns (0, false) when done. +func (it *StszIter) Next() (uint32, bool) { + if it.index >= it.count { + return 0, false + } + var size uint32 + if it.sampleSize != 0 { + size = it.sampleSize + } else { + offset := 8 + int(it.index)*4 + if offset+4 > len(it.buf) { + return 0, false + } + size = be.Uint32(it.buf[offset:]) + } + it.index++ + return size, true +} + +// Co64Iter iterates over uint64 chunk offsets in a co64 box. +type Co64Iter struct { + buf []byte + count uint32 + index uint32 +} + +// NewCo64Iter creates an iterator from co64 box data. +func NewCo64Iter(data []byte) Co64Iter { + if len(data) < 4 { + return Co64Iter{} + } + return Co64Iter{ + buf: data, + count: be.Uint32(data[0:4]), + } +} + +// Count returns the total number of entries. +func (it *Co64Iter) Count() uint32 { return it.count } + +// Next returns the next chunk offset. Returns (0, false) when done. +func (it *Co64Iter) Next() (uint64, bool) { + if it.index >= it.count { + return 0, false + } + offset := 4 + int(it.index)*8 + if offset+8 > len(it.buf) { + return 0, false + } + v := be.Uint64(it.buf[offset:]) + it.index++ + return v, true +} + +// SttsEntry is a time-to-sample entry. +type SttsEntry struct { + Count uint32 + Duration uint32 +} + +// SttsIter iterates over stts entries. +type SttsIter struct { + buf []byte + count uint32 + index uint32 +} + +// NewSttsIter creates an iterator from stts box data. +func NewSttsIter(data []byte) SttsIter { + if len(data) < 4 { + return SttsIter{} + } + return SttsIter{ + buf: data, + count: be.Uint32(data[0:4]), + } +} + +// Count returns the total number of entries. +func (it *SttsIter) Count() uint32 { return it.count } + +// Next returns the next entry. Returns false when done. +func (it *SttsIter) Next() (SttsEntry, bool) { + if it.index >= it.count { + return SttsEntry{}, false + } + offset := 4 + int(it.index)*8 + if offset+8 > len(it.buf) { + return SttsEntry{}, false + } + e := SttsEntry{ + Count: be.Uint32(it.buf[offset:]), + Duration: be.Uint32(it.buf[offset+4:]), + } + it.index++ + return e, true +} + +// CttsEntry is a composition offset entry. +type CttsEntry struct { + Count uint32 + Offset int32 +} + +// CttsIter iterates over ctts entries. +type CttsIter struct { + buf []byte + count uint32 + index uint32 +} + +// NewCttsIter creates an iterator from ctts box data. +func NewCttsIter(data []byte) CttsIter { + if len(data) < 4 { + return CttsIter{} + } + return CttsIter{ + buf: data, + count: be.Uint32(data[0:4]), + } +} + +// Count returns the total number of entries. +func (it *CttsIter) Count() uint32 { return it.count } + +// Next returns the next entry. Returns false when done. +func (it *CttsIter) Next() (CttsEntry, bool) { + if it.index >= it.count { + return CttsEntry{}, false + } + offset := 4 + int(it.index)*8 + if offset+8 > len(it.buf) { + return CttsEntry{}, false + } + e := CttsEntry{ + Count: be.Uint32(it.buf[offset:]), + Offset: int32(be.Uint32(it.buf[offset+4:])), + } + it.index++ + return e, true +} + +// StscEntry is a sample-to-chunk entry. +type StscEntry struct { + FirstChunk uint32 + SamplesPerChunk uint32 + SampleDescriptionId uint32 +} + +// StscIter iterates over stsc entries. +type StscIter struct { + buf []byte + count uint32 + index uint32 +} + +// NewStscIter creates an iterator from stsc box data. +func NewStscIter(data []byte) StscIter { + if len(data) < 4 { + return StscIter{} + } + return StscIter{ + buf: data, + count: be.Uint32(data[0:4]), + } +} + +// Count returns the total number of entries. +func (it *StscIter) Count() uint32 { return it.count } + +// Next returns the next entry. Returns false when done. +func (it *StscIter) Next() (StscEntry, bool) { + if it.index >= it.count { + return StscEntry{}, false + } + offset := 4 + int(it.index)*12 + if offset+12 > len(it.buf) { + return StscEntry{}, false + } + e := StscEntry{ + FirstChunk: be.Uint32(it.buf[offset:]), + SamplesPerChunk: be.Uint32(it.buf[offset+4:]), + SampleDescriptionId: be.Uint32(it.buf[offset+8:]), + } + it.index++ + return e, true +} + +// ElstEntry is an edit list entry. +type ElstEntry struct { + SegmentDuration uint64 + MediaTime int64 + MediaRateInt int16 + MediaRateFrac int16 +} + +// ElstIter iterates over elst entries. +type ElstIter struct { + buf []byte + count uint32 + index uint32 + version uint8 +} + +// NewElstIter creates an iterator from elst box data with the given version. +func NewElstIter(data []byte, version uint8) ElstIter { + if len(data) < 4 { + return ElstIter{} + } + return ElstIter{ + buf: data, + count: be.Uint32(data[0:4]), + version: version, + } +} + +// Count returns the total number of entries. +func (it *ElstIter) Count() uint32 { return it.count } + +// Next returns the next entry. Returns false when done. +func (it *ElstIter) Next() (ElstEntry, bool) { + if it.index >= it.count { + return ElstEntry{}, false + } + var e ElstEntry + if it.version == 1 { + stride := 20 + offset := 4 + int(it.index)*stride + if offset+stride > len(it.buf) { + return ElstEntry{}, false + } + e.SegmentDuration = be.Uint64(it.buf[offset:]) + e.MediaTime = int64(be.Uint64(it.buf[offset+8:])) + e.MediaRateInt = int16(be.Uint16(it.buf[offset+16:])) + e.MediaRateFrac = int16(be.Uint16(it.buf[offset+18:])) + } else { + stride := 12 + offset := 4 + int(it.index)*stride + if offset+stride > len(it.buf) { + return ElstEntry{}, false + } + e.SegmentDuration = uint64(be.Uint32(it.buf[offset:])) + e.MediaTime = int64(int32(be.Uint32(it.buf[offset+4:]))) + e.MediaRateInt = int16(be.Uint16(it.buf[offset+8:])) + e.MediaRateFrac = int16(be.Uint16(it.buf[offset+10:])) + } + it.index++ + return e, true +} + +// TrunEntry is a track run sample entry. +type TrunEntry struct { + Duration uint32 + Size uint32 + Flags uint32 + CompositionTimeOffset int32 +} + +// Trun flags. +const ( + TrunDataOffsetPresent = 0x000001 + TrunFirstSampleFlagsPresent = 0x000004 + TrunSampleDurationPresent = 0x000100 + TrunSampleSizePresent = 0x000200 + TrunSampleFlagsPresent = 0x000400 + TrunSampleCompositionTimeOffsetPresent = 0x000800 +) + +// TrunIter iterates over trun entries. +type TrunIter struct { + buf []byte + flags uint32 + count uint32 + index uint32 + dataOffset int32 + firstSampleFlags uint32 + stride int + entriesStart int +} + +// NewTrunIter creates an iterator from trun box data with the given flags. +func NewTrunIter(data []byte, flags uint32) TrunIter { + if len(data) < 4 { + return TrunIter{} + } + it := TrunIter{ + buf: data, + flags: flags, + count: be.Uint32(data[0:4]), + } + ptr := 4 + if flags&TrunDataOffsetPresent != 0 { + if ptr+4 > len(data) { + return TrunIter{} + } + it.dataOffset = int32(be.Uint32(data[ptr:])) + ptr += 4 + } + if flags&TrunFirstSampleFlagsPresent != 0 { + if ptr+4 > len(data) { + return TrunIter{} + } + it.firstSampleFlags = be.Uint32(data[ptr:]) + ptr += 4 + } + it.entriesStart = ptr + + if flags&TrunSampleDurationPresent != 0 { + it.stride += 4 + } + if flags&TrunSampleSizePresent != 0 { + it.stride += 4 + } + if flags&TrunSampleFlagsPresent != 0 { + it.stride += 4 + } + if flags&TrunSampleCompositionTimeOffsetPresent != 0 { + it.stride += 4 + } + return it +} + +// Count returns the total number of samples. +func (it *TrunIter) Count() uint32 { return it.count } + +// DataOffset returns the trun data offset. +func (it *TrunIter) DataOffset() int32 { return it.dataOffset } + +// FirstSampleFlags returns the first sample flags, if present. +func (it *TrunIter) FirstSampleFlags() uint32 { return it.firstSampleFlags } + +// Next returns the next sample entry. Returns false when done. +func (it *TrunIter) Next() (TrunEntry, bool) { + if it.index >= it.count { + return TrunEntry{}, false + } + offset := it.entriesStart + int(it.index)*it.stride + if offset+it.stride > len(it.buf) { + return TrunEntry{}, false + } + var e TrunEntry + p := offset + if it.flags&TrunSampleDurationPresent != 0 { + e.Duration = be.Uint32(it.buf[p:]) + p += 4 + } + if it.flags&TrunSampleSizePresent != 0 { + e.Size = be.Uint32(it.buf[p:]) + p += 4 + } + if it.flags&TrunSampleFlagsPresent != 0 { + e.Flags = be.Uint32(it.buf[p:]) + p += 4 + } + if it.flags&TrunSampleCompositionTimeOffsetPresent != 0 { + e.CompositionTimeOffset = int32(be.Uint32(it.buf[p:])) + } + it.index++ + return e, true +} + +// Uint32Iter iterates over uint32 entries (stco, stss). +type Uint32Iter struct { + buf []byte + count uint32 + index uint32 +} + +// NewUint32Iter creates an iterator from box data containing a count + uint32 entries. +func NewUint32Iter(data []byte) Uint32Iter { + if len(data) < 4 { + return Uint32Iter{} + } + return Uint32Iter{ + buf: data, + count: be.Uint32(data[0:4]), + } +} + +// Count returns the total number of entries. +func (it *Uint32Iter) Count() uint32 { return it.count } + +// Next returns the next entry. Returns (0, false) when done. +func (it *Uint32Iter) Next() (uint32, bool) { + if it.index >= it.count { + return 0, false + } + offset := 4 + int(it.index)*4 + if offset+4 > len(it.buf) { + return 0, false + } + v := be.Uint32(it.buf[offset:]) + it.index++ + return v, true +} + +// FtypInfo holds parsed fields from an ftyp box. +type FtypInfo struct { + MajorBrand [4]byte + MinorVersion uint32 + Compatible [][4]byte +} + +// ReadFtyp parses an ftyp box. +func ReadFtyp(data []byte) FtypInfo { + f := FtypInfo{ + MinorVersion: be.Uint32(data[4:8]), + } + copy(f.MajorBrand[:], data[0:4]) + for i := 8; i+4 <= len(data); i += 4 { + var b [4]byte + copy(b[:], data[i:i+4]) + f.Compatible = append(f.Compatible, b) + } + return f +} + +// VisualSampleEntry holds parsed fields from a visual sample entry (e.g. avc1). +type VisualSampleEntry struct { + DataReferenceIndex uint16 + Width uint16 + Height uint16 + HResolution uint32 // 16.16 fixed point + VResolution uint32 // 16.16 fixed point + FrameCount uint16 + CompressorName string + Depth uint16 + ChildOffset int // byte offset within data where child boxes begin +} + +// ReadVisualSampleEntry parses a visual sample entry from box data. +// Child boxes (e.g. avcC) start at ChildOffset within the data. +func ReadVisualSampleEntry(data []byte) VisualSampleEntry { + nameLen := min(int(data[42]), 31) + return VisualSampleEntry{ + DataReferenceIndex: be.Uint16(data[6:8]), + Width: be.Uint16(data[24:26]), + Height: be.Uint16(data[26:28]), + HResolution: be.Uint32(data[28:32]), + VResolution: be.Uint32(data[32:36]), + FrameCount: be.Uint16(data[40:42]), + CompressorName: string(data[43 : 43+nameLen]), + Depth: be.Uint16(data[74:76]), + ChildOffset: 78, + } +} + +// AudioSampleEntry holds parsed fields from an audio sample entry (e.g. mp4a). +type AudioSampleEntry struct { + DataReferenceIndex uint16 + ChannelCount uint16 + SampleSize uint16 + SampleRate uint32 // 16.16 fixed point + ChildOffset int // byte offset within data where child boxes begin +} + +// ReadAudioSampleEntry parses an audio sample entry from box data. +// Child boxes (e.g. esds) start at ChildOffset within the data. +func ReadAudioSampleEntry(data []byte) AudioSampleEntry { + return AudioSampleEntry{ + DataReferenceIndex: be.Uint16(data[6:8]), + ChannelCount: be.Uint16(data[16:18]), + SampleSize: be.Uint16(data[18:20]), + SampleRate: be.Uint32(data[24:28]), + ChildOffset: 28, + } +} + +// ReadAvcC extracts the codec profile string from avcC box data. +// Returns a string like "64001f" for use in MIME type codec parameters. +func ReadAvcC(data []byte) string { + if len(data) < 4 { + return "" + } + var buf [6]byte + buf[0] = hexDigit(data[1] >> 4) + buf[1] = hexDigit(data[1] & 0x0f) + buf[2] = hexDigit(data[2] >> 4) + buf[3] = hexDigit(data[2] & 0x0f) + buf[4] = hexDigit(data[3] >> 4) + buf[5] = hexDigit(data[3] & 0x0f) + return string(buf[:]) +} + +const hexChars = "0123456789abcdef" + +// hexDigit returns the lowercase hex character for a 4-bit nibble. +func hexDigit(b byte) byte { + return hexChars[b&0x0f] +} diff --git a/reader.go b/reader.go new file mode 100644 index 0000000..f9531b5 --- /dev/null +++ b/reader.go @@ -0,0 +1,310 @@ +package mp4 + +// maxDepth limits the reader/writer nesting stack. +const maxDepth = 16 + +// readerFrame stores parent state when entering a container box. +type readerFrame struct { + end int // parent's iteration end boundary + boxEnd int // position to resume after exiting this container +} + +// Reader provides streaming parsing of MP4 boxes. +type Reader struct { + buf []byte + pos int // next position to parse from + end int // iteration end boundary + + // Current box state + boxType BoxType + boxSize uint64 + boxStart int + boxEnd int + dataStart int + + // Full box fields + version uint8 + flags uint32 + + // Nesting stack + stack [maxDepth]readerFrame + depth int +} + +// NewReader creates a Reader for the given buffer. +func NewReader(buf []byte) Reader { + return Reader{ + buf: buf, + end: len(buf), + } +} + +// Next advances to the next sibling box. Returns false if no more boxes. +func (r *Reader) Next() bool { + // Skip past current box + if r.boxEnd > r.pos { + r.pos = r.boxEnd + } + + if r.end-r.pos < 8 { + return false + } + + r.boxStart = r.pos + size := uint64(be.Uint32(r.buf[r.pos:])) + copy(r.boxType[:], r.buf[r.pos+4:r.pos+8]) + ptr := r.pos + 8 + + // Extended size + if size == 1 { + if r.end-r.pos < 16 { + return false + } + size = be.Uint64(r.buf[ptr:]) + ptr += 8 + } + + // Size 0 means box extends to end of data + if size == 0 { + size = uint64(r.end - r.pos) + } + + r.boxSize = size + r.boxEnd = r.boxStart + int(size) + + if r.boxEnd > r.end { + return false + } + + // Parse full box header if applicable + if IsFullBox(r.boxType) { + if r.boxEnd-ptr < 4 { + return false + } + vf := be.Uint32(r.buf[ptr:]) + r.version = uint8(vf >> 24) + r.flags = vf & 0x00ffffff + ptr += 4 + } else { + r.version = 0 + r.flags = 0 + } + + r.dataStart = ptr + return true +} + +// Type returns the current box's type. +func (r *Reader) Type() BoxType { return r.boxType } + +// Size returns the current box's total size including header. +func (r *Reader) Size() uint64 { return r.boxSize } + +// Version returns the version field for full boxes. +func (r *Reader) Version() uint8 { return r.version } + +// Flags returns the flags field for full boxes. +func (r *Reader) Flags() uint32 { return r.flags } + +// Offset returns the byte offset of the current box's start in the buffer. +func (r *Reader) Offset() int { return r.boxStart } + +// DataOffset returns the byte offset where the current box's data begins. +func (r *Reader) DataOffset() int { return r.dataStart } + +// HeaderSize returns the size of the current box's header in bytes. +func (r *Reader) HeaderSize() int { return r.dataStart - r.boxStart } + +// Data returns the current box's data (after all headers). +// Note that, the returned slice points into the original buffer. +func (r *Reader) Data() []byte { + return r.buf[r.dataStart:r.boxEnd] +} + +// RawBox returns the entire current box including headers. +// Note that, the returned slice points into the original buffer. +func (r *Reader) RawBox() []byte { + return r.buf[r.boxStart:r.boxEnd] +} + +// Depth returns the current nesting depth (0 at top level). +func (r *Reader) Depth() int { return r.depth } + +// Enter descends into the current container box to iterate its children. +// After Enter, call Next to advance to the first child box. +// Call Exit when done to return to the parent level. +// +// For boxes like stsd or dref that have an entry count before child boxes, +// call Skip(4) after Enter to skip past the count field. +// +// For sample entry boxes like avc1 (78 bytes) or mp4a (28 bytes), +// call Skip with the fixed header size after Enter to reach child boxes. +func (r *Reader) Enter() { + r.stack[r.depth] = readerFrame{ + end: r.end, + boxEnd: r.boxEnd, + } + r.depth++ + r.end = r.boxEnd + r.pos = r.dataStart + r.boxEnd = r.dataStart // prevent Next from skipping +} + +// Exit returns to the parent container level. +// After Exit, the next call to Next will advance to the next sibling. +func (r *Reader) Exit() { + r.depth-- + f := r.stack[r.depth] + r.end = f.end + r.pos = f.boxEnd + r.boxEnd = f.boxEnd +} + +// Skip advances the data position by n bytes within the current container. +// Use after Enter to skip fixed-size headers before child boxes. +func (r *Reader) Skip(n int) { + r.pos += n + r.boxEnd = r.pos +} + +// EntryCount reads the uint32 entry count at the start of box data. +// Used for boxes like stsd and dref that begin with a count field. +func (r *Reader) EntryCount() uint32 { + data := r.Data() + return be.Uint32(data[0:4]) +} + +// ReadMvhd extracts key fields from an mvhd box. +// Returns timescale, duration, and nextTrackId. +func (r *Reader) ReadMvhd() (timescale uint32, duration uint64, nextTrackId uint32) { + data := r.Data() + version := r.Version() + if version == 1 { + // v1: ctime(8)+mtime(8)+timescale(4)+duration(8)+rate(4)+volume(2)+reserved(10)+matrix(36)+predefined(24)+nextTrackId(4) = 108 + timescale = be.Uint32(data[16:20]) + duration = be.Uint64(data[20:28]) + nextTrackId = be.Uint32(data[104:108]) + } else { + // v0: ctime(4)+mtime(4)+timescale(4)+duration(4)+rate(4)+volume(2)+reserved(10)+matrix(36)+predefined(24)+nextTrackId(4) = 96 + timescale = be.Uint32(data[8:12]) + duration = uint64(be.Uint32(data[12:16])) + nextTrackId = be.Uint32(data[92:96]) + } + return +} + +// ReadTkhd extracts key fields from a tkhd box. +// Returns trackId, duration, width, height. +// Width and height are 16.16 fixed-point values; shift right by 16 for pixels. +func (r *Reader) ReadTkhd() (trackId uint32, duration uint64, width, height uint32) { + data := r.Data() + version := r.Version() + if version == 1 { + // v1: ctime(8)+mtime(8)+trackId(4)+reserved(4)+duration(8) + trackId = be.Uint32(data[16:20]) + duration = be.Uint64(data[24:32]) + // +reserved(8)+layer(2)+altGroup(2)+volume(2)+reserved(2)+matrix(36)+width(4)+height(4) + width = be.Uint32(data[84:88]) + height = be.Uint32(data[88:92]) + } else { + // v0: ctime(4)+mtime(4)+trackId(4)+reserved(4)+duration(4) + trackId = be.Uint32(data[8:12]) + duration = uint64(be.Uint32(data[16:20])) + // +reserved(8)+layer(2)+altGroup(2)+volume(2)+reserved(2)+matrix(36)+width(4)+height(4) + width = be.Uint32(data[72:76]) + height = be.Uint32(data[76:80]) + } + return +} + +// ReadMdhd extracts key fields from an mdhd box. +// Returns timescale, duration, and language code. +func (r *Reader) ReadMdhd() (timescale uint32, duration uint64, language uint16) { + data := r.Data() + version := r.Version() + if version == 1 { + // v1: ctime(8)+mtime(8)+timescale(4)+duration(8)+lang(2)+quality(2) + timescale = be.Uint32(data[16:20]) + duration = be.Uint64(data[20:28]) + language = be.Uint16(data[28:30]) + } else { + // v0: ctime(4)+mtime(4)+timescale(4)+duration(4)+lang(2)+quality(2) + timescale = be.Uint32(data[8:12]) + duration = uint64(be.Uint32(data[12:16])) + language = be.Uint16(data[16:18]) + } + return +} + +// ReadHdlr extracts the handler type from an hdlr box. +// Returns the 4-byte handler type string. +func (r *Reader) ReadHdlr() [4]byte { + data := r.Data() + var t [4]byte + copy(t[:], data[4:8]) + return t +} + +// ReadHdlrName extracts the handler name from an hdlr box. +func (r *Reader) ReadHdlrName() string { + data := r.Data() + if len(data) <= 20 { + return "" + } + end := 20 + for end < len(data) && data[end] != 0 { + end++ + } + return string(data[20:end]) +} + +// ReadMehd extracts the fragment duration from an mehd box. +func (r *Reader) ReadMehd() (fragmentDuration uint64) { + data := r.Data() + version := r.Version() + if version == 1 { + fragmentDuration = be.Uint64(data[0:8]) + } else { + fragmentDuration = uint64(be.Uint32(data[0:4])) + } + return +} + +// ReadTrex extracts fields from a trex box. +// Returns trackId, default sample description index, default sample duration, +// default sample size, and default sample flags. +func (r *Reader) ReadTrex() (trackId, defSampleDescIdx, defSampleDuration, defSampleSize, defSampleFlags uint32) { + data := r.Data() + trackId = be.Uint32(data[0:4]) + defSampleDescIdx = be.Uint32(data[4:8]) + defSampleDuration = be.Uint32(data[8:12]) + defSampleSize = be.Uint32(data[12:16]) + defSampleFlags = be.Uint32(data[16:20]) + return +} + +// ReadMfhd extracts the sequence number from an mfhd box. +func (r *Reader) ReadMfhd() (sequenceNumber uint32) { + data := r.Data() + sequenceNumber = be.Uint32(data[0:4]) + return +} + +// ReadTfhd extracts the track ID from a tfhd box. +func (r *Reader) ReadTfhd() (trackId uint32) { + data := r.Data() + trackId = be.Uint32(data[0:4]) + return +} + +// ReadTfdt extracts the base media decode time from a tfdt box. +func (r *Reader) ReadTfdt() (baseMediaDecodeTime uint64) { + data := r.Data() + version := r.Version() + if version == 1 { + baseMediaDecodeTime = be.Uint64(data[0:8]) + } else { + baseMediaDecodeTime = uint64(be.Uint32(data[0:4])) + } + return +} diff --git a/scanner.go b/scanner.go new file mode 100644 index 0000000..4466dc7 --- /dev/null +++ b/scanner.go @@ -0,0 +1,169 @@ +package mp4 + +import "io" + +// ScanEntry represents a top-level box discovered by the Scanner. +type ScanEntry struct { + Type BoxType + Size int64 // total box size including header + Offset int64 // byte offset from start of stream + HeaderSize int // header size (8 or 16 bytes) +} + +// DataSize returns the size of the box data (excluding the header). +func (e ScanEntry) DataSize() int64 { + return e.Size - int64(e.HeaderSize) +} + +// Scanner reads top-level box headers from an io.ReadSeeker without +// loading box contents into memory. This lets callers discover box +// positions and sizes, then selectively read only the boxes they need +// (e.g. moov) into a buffer for parsing with NewReader. +// +// Typical usage: +// +// f, _ := os.Open("video.mp4") +// sc := mp4.NewScanner(f) +// for sc.Next() { +// e := sc.Entry() +// if e.Type == mp4.TypeMoov { +// buf := make([]byte, e.DataSize()) +// sc.ReadBody(buf) +// r := mp4.NewReader(buf) +// // parse moov contents... +// } +// } +// if err := sc.Err(); err != nil { ... } +type Scanner struct { + rs io.ReadSeeker + hdr [16]byte // reusable header buffer + entry ScanEntry + err error + pos int64 // current position in stream +} + +// NewScanner creates a Scanner that reads box headers from rs. +func NewScanner(rs io.ReadSeeker) Scanner { + return Scanner{rs: rs} +} + +// Next advances to the next top-level box. Returns false when there +// are no more boxes or an error occurs. Check Err() after the loop. +func (s *Scanner) Next() bool { + // Read the minimum 8-byte header + _, err := io.ReadFull(s.rs, s.hdr[:8]) + if err != nil { + if err != io.EOF && err != io.ErrUnexpectedEOF { + s.err = err + } + return false + } + + boxStart := s.pos + size := int64(be.Uint32(s.hdr[:4])) + var t BoxType + copy(t[:], s.hdr[4:8]) + + headerSize := 8 + + if size == 1 { + // Extended 64-bit size + _, err = io.ReadFull(s.rs, s.hdr[8:16]) + if err != nil { + s.err = err + return false + } + size = int64(be.Uint64(s.hdr[8:16])) + headerSize = 16 + } + + if size == 0 { + // Box extends to end of file; determine remaining size + cur, err := s.rs.Seek(0, io.SeekCurrent) + if err != nil { + s.err = err + return false + } + end, err := s.rs.Seek(0, io.SeekEnd) + if err != nil { + s.err = err + return false + } + size = end - boxStart + // Seek back to where we were + if _, err := s.rs.Seek(cur, io.SeekStart); err != nil { + s.err = err + return false + } + } + + s.entry = ScanEntry{ + Type: t, + Size: size, + Offset: boxStart, + HeaderSize: headerSize, + } + + // Skip past this box's data to position for the next call + dataSize := size - int64(headerSize) + if dataSize > 0 { + if _, err := s.rs.Seek(dataSize, io.SeekCurrent); err != nil { + s.err = err + return false + } + } + s.pos = boxStart + size + + return true +} + +// Entry returns the current box entry. Only valid after Next returns true. +func (s *Scanner) Entry() ScanEntry { + return s.entry +} + +// Err returns the first non-EOF error encountered by the Scanner. +func (s *Scanner) Err() error { + return s.err +} + +// ReadBody reads the current box's data (excluding header) into buf. +// buf must be exactly DataSize() bytes. The scanner seeks to the data +// position, reads, then seeks back so that subsequent Next calls work correctly. +func (s *Scanner) ReadBody(buf []byte) error { + dataOffset := s.entry.Offset + int64(s.entry.HeaderSize) + + // Save current position (which is past this box) + saved := s.pos + + if _, err := s.rs.Seek(dataOffset, io.SeekStart); err != nil { + return err + } + if _, err := io.ReadFull(s.rs, buf); err != nil { + return err + } + + // Restore position + if _, err := s.rs.Seek(saved, io.SeekStart); err != nil { + return err + } + return nil +} + +// ReadBox reads the current box's full data (including header) into buf. +// buf must be exactly Size bytes. +func (s *Scanner) ReadBox(buf []byte) error { + saved := s.pos + + if _, err := s.rs.Seek(s.entry.Offset, io.SeekStart); err != nil { + return err + } + if _, err := io.ReadFull(s.rs, buf); err != nil { + return err + } + + if _, err := s.rs.Seek(saved, io.SeekStart); err != nil { + return err + } + return nil +} diff --git a/writer.go b/writer.go new file mode 100644 index 0000000..1adfac2 --- /dev/null +++ b/writer.go @@ -0,0 +1,463 @@ +package mp4 + +// writerFrame tracks the start offset of a box for size backpatching. +type writerFrame struct { + offset int +} + +// Writer builds MP4 data into a caller-provided fixed-size byte buffer. +type Writer struct { + buf []byte + pos int + stack [maxDepth]writerFrame + depth int +} + +// NewWriter creates a Writer that writes into buf. +func NewWriter(buf []byte) Writer { + return Writer{buf: buf[:cap(buf)]} +} + +// Bytes returns the written data. +func (w *Writer) Bytes() []byte { + return w.buf[:w.pos] +} + +// Len returns the number of bytes written. +func (w *Writer) Len() int { return w.pos } + +// Write appends raw bytes. Implements io.Writer. +func (w *Writer) Write(p []byte) (int, error) { + copy(w.buf[w.pos:], p) + w.pos += len(p) + return len(p), nil +} + +// putUint8 appends a single byte. +func (w *Writer) putUint8(v byte) { + w.buf[w.pos] = v + w.pos++ +} + +// putUint16 appends a big-endian uint16. +func (w *Writer) putUint16(v uint16) { + be.PutUint16(w.buf[w.pos:], v) + w.pos += 2 +} + +// putUint32 appends a big-endian uint32. +func (w *Writer) putUint32(v uint32) { + be.PutUint32(w.buf[w.pos:], v) + w.pos += 4 +} + +// putUint64 appends a big-endian uint64. +func (w *Writer) putUint64(v uint64) { + be.PutUint64(w.buf[w.pos:], v) + w.pos += 8 +} + +// putInt32 appends a big-endian int32. +func (w *Writer) putInt32(v int32) { + w.putUint32(uint32(v)) +} + +// putZeros appends n zero bytes. +func (w *Writer) putZeros(n int) { + clear(w.buf[w.pos : w.pos+n]) + w.pos += n +} + +// putBytes appends raw bytes. +func (w *Writer) putBytes(p []byte) { + copy(w.buf[w.pos:], p) + w.pos += len(p) +} + +// putFixedString writes a fixed-length string field with null padding. +func (w *Writer) putFixedString(s string, length int) { + n := copy(w.buf[w.pos:w.pos+length], s) + clear(w.buf[w.pos+n : w.pos+length]) + w.pos += length +} + +// Reset resets the writer position to 0. +func (w *Writer) Reset() { + w.pos = 0 + w.depth = 0 +} + +// StartBox begins a new box. Write content, then call EndBox. +func (w *Writer) StartBox(t BoxType) { + w.stack[w.depth] = writerFrame{offset: w.pos} + w.depth++ + w.putUint32(0) // placeholder size + w.putBytes(t[:]) +} + +// StartFullBox begins a new full box with version and flags. +func (w *Writer) StartFullBox(t BoxType, version uint8, flags uint32) { + w.StartBox(t) + vf := (uint32(version) << 24) | (flags & 0x00ffffff) + w.putUint32(vf) +} + +// EndBox finishes the current box by backpatching its size. +func (w *Writer) EndBox() { + w.depth-- + f := w.stack[w.depth] + size := uint32(w.pos - f.offset) + be.PutUint32(w.buf[f.offset:], size) +} + +// WriteFtyp writes a complete ftyp box. +func (w *Writer) WriteFtyp(brand [4]byte, brandVersion uint32, compat [][4]byte) { + w.StartBox(TypeFtyp) + w.putBytes(brand[:]) + w.putUint32(brandVersion) + for _, c := range compat { + w.putBytes(c[:]) + } + w.EndBox() +} + +// WriteMvhd writes a complete mvhd box. +func (w *Writer) WriteMvhd(timescale uint32, duration uint64, nextTrackId uint32) { + if duration > uint32Max { + w.StartFullBox(TypeMvhd, 1, 0) + w.putUint64(0) // creation time + w.putUint64(0) // modification time + w.putUint32(timescale) + w.putUint64(duration) + } else { + w.StartFullBox(TypeMvhd, 0, 0) + w.putUint32(0) // creation time + w.putUint32(0) // modification time + w.putUint32(timescale) + w.putUint32(uint32(duration)) + } + w.putUint32(0x00010000) // rate 1.0 + w.putUint16(0x0100) // volume 1.0 + w.putZeros(10) // reserved + // Identity matrix + w.putUint32(0x00010000) + w.putZeros(4) + w.putZeros(4) + w.putZeros(4) + w.putUint32(0x00010000) + w.putZeros(4) + w.putZeros(4) + w.putZeros(4) + w.putUint32(0x40000000) + w.putZeros(24) // predefined + w.putUint32(nextTrackId) + w.EndBox() +} + +// WriteTkhd writes a complete tkhd box. +func (w *Writer) WriteTkhd(flags uint32, trackId uint32, duration uint64, width, height uint32) { + if duration > uint32Max { + w.StartFullBox(TypeTkhd, 1, flags) + w.putUint64(0) // creation time + w.putUint64(0) // modification time + w.putUint32(trackId) + w.putUint32(0) // reserved + w.putUint64(duration) + } else { + w.StartFullBox(TypeTkhd, 0, flags) + w.putUint32(0) // creation time + w.putUint32(0) // modification time + w.putUint32(trackId) + w.putUint32(0) // reserved + w.putUint32(uint32(duration)) + } + w.putZeros(8) // reserved + w.putUint16(0) // layer + w.putUint16(0) // alternate group + w.putUint16(0) // volume + w.putUint16(0) // reserved + // Identity matrix + w.putUint32(0x00010000) + w.putZeros(4) + w.putZeros(4) + w.putZeros(4) + w.putUint32(0x00010000) + w.putZeros(4) + w.putZeros(4) + w.putZeros(4) + w.putUint32(0x40000000) + w.putUint32(width) + w.putUint32(height) + w.EndBox() +} + +// WriteMdhd writes a complete mdhd box. +func (w *Writer) WriteMdhd(timescale uint32, duration uint64, language uint16) { + if duration > uint32Max { + w.StartFullBox(TypeMdhd, 1, 0) + w.putUint64(0) // creation time + w.putUint64(0) // modification time + w.putUint32(timescale) + w.putUint64(duration) + } else { + w.StartFullBox(TypeMdhd, 0, 0) + w.putUint32(0) // creation time + w.putUint32(0) // modification time + w.putUint32(timescale) + w.putUint32(uint32(duration)) + } + w.putUint16(language) + w.putUint16(0) // quality + w.EndBox() +} + +// WriteHdlr writes a complete hdlr box. +func (w *Writer) WriteHdlr(handlerType [4]byte, name string) { + w.StartFullBox(TypeHdlr, 0, 0) + w.putUint32(0) // predefined + w.putBytes(handlerType[:]) + w.putZeros(12) // reserved + w.putBytes([]byte(name)) + w.putUint8(0) // null terminator + w.EndBox() +} + +// WriteVmhd writes a complete vmhd box. +func (w *Writer) WriteVmhd() { + w.StartFullBox(TypeVmhd, 0, 1) + w.putUint16(0) // graphicsmode + w.putZeros(6) // opcolor + w.EndBox() +} + +// WriteSmhd writes a complete smhd box. +func (w *Writer) WriteSmhd() { + w.StartFullBox(TypeSmhd, 0, 0) + w.putUint16(0) // balance + w.putUint16(0) // reserved + w.EndBox() +} + +// WriteDref writes a dref box with a single self-referencing url entry. +func (w *Writer) WriteDref() { + w.StartFullBox(TypeDref, 0, 0) + w.putUint32(1) // entry count + // url entry: self-contained + w.StartFullBox(BoxType{'u', 'r', 'l', ' '}, 0, 1) + w.EndBox() + w.EndBox() +} + +// WriteStsz writes a complete stsz box from an iterator or raw entries. +func (w *Writer) WriteStsz(sampleSize uint32, entries []uint32) { + w.StartFullBox(TypeStsz, 0, 0) + w.putUint32(sampleSize) + w.putUint32(uint32(len(entries))) + if sampleSize == 0 { + for _, e := range entries { + w.putUint32(e) + } + } + w.EndBox() +} + +// WriteStco writes a complete stco box. +func (w *Writer) WriteStco(entries []uint32) { + w.StartFullBox(TypeStco, 0, 0) + w.putUint32(uint32(len(entries))) + for _, e := range entries { + w.putUint32(e) + } + w.EndBox() +} + +// WriteCo64 writes a complete co64 box. +func (w *Writer) WriteCo64(entries []uint64) { + w.StartFullBox(TypeCo64, 0, 0) + w.putUint32(uint32(len(entries))) + for _, e := range entries { + w.putUint64(e) + } + w.EndBox() +} + +// WriteStss writes a complete stss box. +func (w *Writer) WriteStss(entries []uint32) { + w.StartFullBox(TypeStss, 0, 0) + w.putUint32(uint32(len(entries))) + for _, e := range entries { + w.putUint32(e) + } + w.EndBox() +} + +// WriteStts writes a complete stts box. +func (w *Writer) WriteStts(entries []SttsEntry) { + w.StartFullBox(TypeStts, 0, 0) + w.putUint32(uint32(len(entries))) + for _, e := range entries { + w.putUint32(e.Count) + w.putUint32(e.Duration) + } + w.EndBox() +} + +// WriteCtts writes a complete ctts box. +func (w *Writer) WriteCtts(entries []CttsEntry) { + w.StartFullBox(TypeCtts, 0, 0) + w.putUint32(uint32(len(entries))) + for _, e := range entries { + w.putUint32(e.Count) + w.putUint32(uint32(e.Offset)) + } + w.EndBox() +} + +// WriteStsc writes a complete stsc box. +func (w *Writer) WriteStsc(entries []StscEntry) { + w.StartFullBox(TypeStsc, 0, 0) + w.putUint32(uint32(len(entries))) + for _, e := range entries { + w.putUint32(e.FirstChunk) + w.putUint32(e.SamplesPerChunk) + w.putUint32(e.SampleDescriptionId) + } + w.EndBox() +} + +// WriteElst writes a complete elst box. +func (w *Writer) WriteElst(entries []ElstEntry) { + // Determine if v1 is needed + v1 := false + for _, e := range entries { + if e.SegmentDuration > uint32Max || e.MediaTime > int64(int32(e.MediaTime)) { + v1 = true + break + } + } + if v1 { + w.StartFullBox(TypeElst, 1, 0) + } else { + w.StartFullBox(TypeElst, 0, 0) + } + w.putUint32(uint32(len(entries))) + for _, e := range entries { + if v1 { + w.putUint64(e.SegmentDuration) + w.putUint64(uint64(e.MediaTime)) + } else { + w.putUint32(uint32(e.SegmentDuration)) + w.putUint32(uint32(e.MediaTime)) + } + w.putUint16(uint16(e.MediaRateInt)) + w.putUint16(uint16(e.MediaRateFrac)) + } + w.EndBox() +} + +// WriteMehd writes a complete mehd box. +func (w *Writer) WriteMehd(fragmentDuration uint64) { + if fragmentDuration > uint32Max { + w.StartFullBox(TypeMehd, 1, 0) + w.putUint64(fragmentDuration) + } else { + w.StartFullBox(TypeMehd, 0, 0) + w.putUint32(uint32(fragmentDuration)) + } + w.EndBox() +} + +// WriteTrex writes a complete trex box. +func (w *Writer) WriteTrex(trackId, descIdx, defDuration, defSize, defFlags uint32) { + w.StartFullBox(TypeTrex, 0, 0) + w.putUint32(trackId) + w.putUint32(descIdx) + w.putUint32(defDuration) + w.putUint32(defSize) + w.putUint32(defFlags) + w.EndBox() +} + +// WriteMfhd writes a complete mfhd box. +func (w *Writer) WriteMfhd(sequenceNumber uint32) { + w.StartFullBox(TypeMfhd, 0, 0) + w.putUint32(sequenceNumber) + w.EndBox() +} + +// WriteTfhd writes a complete tfhd box. +func (w *Writer) WriteTfhd(flags uint32, trackId uint32) { + w.StartFullBox(TypeTfhd, 0, flags) + w.putUint32(trackId) + w.EndBox() +} + +// WriteTfdt writes a complete tfdt box. +func (w *Writer) WriteTfdt(baseMediaDecodeTime uint64) { + if baseMediaDecodeTime > uint32Max { + w.StartFullBox(TypeTfdt, 1, 0) + w.putUint64(baseMediaDecodeTime) + } else { + w.StartFullBox(TypeTfdt, 0, 0) + w.putUint32(uint32(baseMediaDecodeTime)) + } + w.EndBox() +} + +// WriteTrun writes a complete trun box. +func (w *Writer) WriteTrun(flags uint32, dataOffset int32, entries []TrunEntry) { + w.StartFullBox(TypeTrun, 0, flags) + w.putUint32(uint32(len(entries))) + if flags&TrunDataOffsetPresent != 0 { + w.putInt32(dataOffset) + } + for _, e := range entries { + if flags&TrunSampleDurationPresent != 0 { + w.putUint32(e.Duration) + } + if flags&TrunSampleSizePresent != 0 { + w.putUint32(e.Size) + } + if flags&TrunSampleFlagsPresent != 0 { + w.putUint32(e.Flags) + } + if flags&TrunSampleCompositionTimeOffsetPresent != 0 { + w.putInt32(e.CompositionTimeOffset) + } + } + w.EndBox() +} + +// WriteVisualSampleEntry writes the 78-byte visual sample entry header. +// The caller must start the box (e.g. avc1) and end it after writing children. +func (w *Writer) WriteVisualSampleEntry(dataRefIdx, width, height, frameCount, depth uint16, compressor string) { + w.putZeros(6) // reserved + w.putUint16(dataRefIdx) // data reference index + w.putZeros(16) // predefined + reserved + w.putUint16(width) // width + w.putUint16(height) // height + w.putUint32(0x00480000) // hresolution 72 dpi + w.putUint32(0x00480000) // vresolution 72 dpi + w.putZeros(4) // reserved + w.putUint16(frameCount) // frame count + nameLen := len(compressor) + if nameLen > 31 { + nameLen = 31 + } + w.putUint8(byte(nameLen)) + w.putFixedString(compressor, 31) + w.putUint16(depth) // depth + w.putUint16(0xffff) // predefined = -1 +} + +// WriteAudioSampleEntry writes the 28-byte audio sample entry header. +// The caller must start the box (e.g. mp4a) and end it after writing children. +func (w *Writer) WriteAudioSampleEntry(dataRefIdx, channelCount, sampleSize uint16, sampleRate uint32) { + w.putZeros(6) // reserved + w.putUint16(dataRefIdx) // data reference index + w.putZeros(8) // reserved + w.putUint16(channelCount) // channel count + w.putUint16(sampleSize) // sample size + w.putZeros(4) // predefined + reserved + w.putUint32(sampleRate) // sample rate (16.16 fixed point) +} |
