diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-02-13 08:07:38 +0100 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-02-13 08:07:38 +0100 |
| commit | 8502816a943bb33705a7775838c760ed72046ae8 (patch) | |
| tree | 0239df7a4df76414e59956bd679b32eb40054a6c | |
| parent | 34bb3e8c7e644ad8fb3d8546f68595d76b85cd00 (diff) | |
| download | mp4-8502816a943bb33705a7775838c760ed72046ae8.tar.gz mp4-8502816a943bb33705a7775838c760ed72046ae8.zip | |
Remove remuxer
| -rw-r--r-- | cmd/mp4probe/main.go | 121 | ||||
| -rw-r--r-- | remux/direct.go | 110 | ||||
| -rw-r--r-- | remux/remuxer.go | 693 | ||||
| -rw-r--r-- | remux/writer.go | 193 |
4 files changed, 0 insertions, 1117 deletions
diff --git a/cmd/mp4probe/main.go b/cmd/mp4probe/main.go deleted file mode 100644 index eb163bb..0000000 --- a/cmd/mp4probe/main.go +++ /dev/null @@ -1,121 +0,0 @@ -// Command mp4probe gathers information about tracks and keyframe distribution from an MP4 file. -package main - -import ( - "fmt" - "os" - - "github.com/tetsuo/mp4/remux" -) - -func main() { - if len(os.Args) < 2 { - fmt.Fprintf(os.Stderr, "usage: %s <file.mp4>\n", os.Args[0]) - os.Exit(1) - } - - f, err := os.Open(os.Args[1]) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - defer f.Close() - - remuxer, err := remux.NewRemuxer(f) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - - for i, track := range remuxer.Tracks { - fmt.Printf("Track %d: %s\n", i, track.Codec) - fmt.Printf(" Total samples: %d\n", len(track.Samples)) - fmt.Printf(" Duration: %.2fs\n", track.Duration()) - fmt.Printf(" TimeScale: %d\n\n", track.TimeScale) - - // Count keyframes - keyframes := 0 - var prevKfTime float64 - var intervals []float64 - - fmt.Println(" Keyframes:") - for j, s := range track.Samples { - if s.Sync { - pts := float64(s.DTS+int64(s.PresentationOffset)) / float64(track.TimeScale) - fmt.Printf(" [%5d] %.3fs", j, pts) - - if keyframes > 0 { - interval := pts - prevKfTime - intervals = append(intervals, interval) - fmt.Printf(" (%.3fs since last)", interval) - } - fmt.Println() - - prevKfTime = pts - keyframes++ - - if keyframes >= 20 { - fmt.Printf(" ... (%d more keyframes)\n", countRemainingKeyframes(track.Samples[j+1:])) - break - } - } - } - - fmt.Printf("\n Total keyframes: %d\n", countTotalKeyframes(track.Samples)) - if len(intervals) > 0 { - avg := average(intervals) - min := minimum(intervals) - max := maximum(intervals) - fmt.Printf(" Keyframe interval: avg=%.3fs min=%.3fs max=%.3fs\n", avg, min, max) - } - fmt.Println() - } -} - -func countRemainingKeyframes(samples []remux.Sample) int { - count := 0 - for _, s := range samples { - if s.Sync { - count++ - } - } - return count -} - -func countTotalKeyframes(samples []remux.Sample) int { - count := 0 - for _, s := range samples { - if s.Sync { - count++ - } - } - return count -} - -func average(vals []float64) float64 { - sum := 0.0 - for _, v := range vals { - sum += v - } - return sum / float64(len(vals)) -} - -func minimum(vals []float64) float64 { - min := vals[0] - for _, v := range vals { - if v < min { - min = v - } - } - return min -} - -func maximum(vals []float64) float64 { - max := vals[0] - for _, v := range vals { - if v > max { - max = v - } - } - return max -} diff --git a/remux/direct.go b/remux/direct.go deleted file mode 100644 index 58eb6f9..0000000 --- a/remux/direct.go +++ /dev/null @@ -1,110 +0,0 @@ -package remux - -import ( - "encoding/binary" - "io" - - "github.com/tetsuo/mp4" -) - -// writeMoof writes a complete moof box directly as binary to w. -func writeMoof(w io.Writer, seqNum uint32, trackID uint32, baseMediaDecodeTime uint32, entries []mp4.TrunEntry, trunVersion uint8, buf []byte) ([]byte, error) { - be := binary.BigEndian - - // Fixed sizes (no version-1 tfdt for now, baseMediaDecodeTime is uint32) - // moof header: 8 - // mfhd: 16 (8 hdr + 4 ver/flags + 4 seqnum) - // traf header: 8 - // tfhd: 16 (8 hdr + 4 ver/flags + 4 trackid) - // tfdt: 16 (8 hdr + 4 ver/flags + 4 base_decode_time) - // trun header: 20 (8 hdr + 4 ver/flags + 4 sample_count + 4 data_offset) - // trun entries: 16 * len(entries) - n := len(entries) - trunSize := 20 + n*16 - trafSize := 8 + 16 + 16 + trunSize - moofSize := 8 + 16 + trafSize - dataOffset := moofSize + 8 // +8 for mdat header - - // Grow buffer when needed - if cap(buf) < moofSize { - buf = make([]byte, moofSize) - } else { - buf = buf[:moofSize] - } - - p := 0 - - // moof box header - be.PutUint32(buf[p:], uint32(moofSize)) - copy(buf[p+4:], "moof") - p += 8 - - // mfhd (full box: version=0, flags=0) - be.PutUint32(buf[p:], 16) - copy(buf[p+4:], "mfhd") - buf[p+8] = 0 - buf[p+9] = 0 - buf[p+10] = 0 - buf[p+11] = 0 - be.PutUint32(buf[p+12:], seqNum) - p += 16 - - // traf box header - be.PutUint32(buf[p:], uint32(trafSize)) - copy(buf[p+4:], "traf") - p += 8 - - // tfhd (full box: version=0, flags=0x020000 = default-base-is-moof) - be.PutUint32(buf[p:], 16) - copy(buf[p+4:], "tfhd") - buf[p+8] = 0 - buf[p+9] = 0x02 - buf[p+10] = 0 - buf[p+11] = 0 - be.PutUint32(buf[p+12:], trackID) - p += 16 - - // tfdt (full box: version=0, flags=0) - be.PutUint32(buf[p:], 16) - copy(buf[p+4:], "tfdt") - buf[p+8] = 0 - buf[p+9] = 0 - buf[p+10] = 0 - buf[p+11] = 0 - be.PutUint32(buf[p+12:], baseMediaDecodeTime) - p += 16 - - // trun (full box: version=trunVersion, flags=0x000f01) - // flags: 0x001 = data-offset-present - // 0x100 = sample-duration-present - // 0x200 = sample-size-present - // 0x400 = sample-flags-present - // 0x800 = sample-composition-time-offset-present - be.PutUint32(buf[p:], uint32(trunSize)) - copy(buf[p+4:], "trun") - buf[p+8] = trunVersion - buf[p+9] = 0x00 - buf[p+10] = 0x0f - buf[p+11] = 0x01 - be.PutUint32(buf[p+12:], uint32(n)) - be.PutUint32(buf[p+16:], uint32(dataOffset)) - p += 20 - - // trun entries: duration(4) + size(4) + flags(4) + compositionTimeOffset(4) - for i := range n { - e := &entries[i] - be.PutUint32(buf[p:], e.SampleDuration) - be.PutUint32(buf[p+4:], e.SampleSize) - be.PutUint32(buf[p+8:], e.SampleFlags) - if trunVersion == 1 { - // signed composition offset - be.PutUint32(buf[p+12:], uint32(e.SampleCompositionTimeOffset)) - } else { - be.PutUint32(buf[p+12:], uint32(e.SampleCompositionTimeOffset)) - } - p += 16 - } - - _, err := w.Write(buf[:moofSize]) - return buf, err -} diff --git a/remux/remuxer.go b/remux/remuxer.go deleted file mode 100644 index 6cf786b..0000000 --- a/remux/remuxer.go +++ /dev/null @@ -1,693 +0,0 @@ -package remux - -import ( - "encoding/binary" - "fmt" - "io" - "sort" - - "github.com/tetsuo/mp4" -) - -var be = binary.BigEndian - -// Sample represents a single decoded sample (frame) with all metadata needed for remuxing. -type Sample struct { - Offset int64 - Size uint32 - Duration uint32 - DTS int64 - PresentationOffset int32 - Sync bool -} - -// Track holds the parsed metadata for one track (audio or video). -type Track struct { - TrackID uint32 - TimeScale uint32 - Codec string - Mime string - - Samples []Sample - - // initBuf is the pre-encoded ftyp+moov for this track's init segment. - initBuf []byte - // defaultSampleDescriptionIndex from the last stsc entry. - defaultSampleDescriptionIndex uint32 -} - -// Remuxer holds parsed MP4 metadata and writes fragmented MP4 streams. -type Remuxer struct { - Tracks []*Track -} - -// minFragmentDuration is the minimum fragment duration in seconds. -const minFragmentDuration = 1 - -// NewRemuxer parses the moov box from an MP4 source and prepares track metadata. -func NewRemuxer(rs io.ReadSeeker) (*Remuxer, error) { - moov, err := findAndParseMoov(rs) - if err != nil { - return nil, err - } - return newRemuxer(moov) -} - -// NewRemuxerFromBytes parses the moov box from an in-memory MP4 file. -func NewRemuxerFromBytes(data []byte) (*Remuxer, error) { - moov, err := findAndParseMoovBytes(data) - if err != nil { - return nil, err - } - return newRemuxer(moov) -} - -// findAndParseMoov locates the moov box by scanning top-level boxes. -func findAndParseMoov(rs io.ReadSeeker) (*mp4.Box, error) { - var hdr [8]byte - var offset int64 - - for { - if _, err := io.ReadFull(rs, hdr[:]); err != nil { - if err == io.EOF || err == io.ErrUnexpectedEOF { - return nil, fmt.Errorf("moov box not found") - } - return nil, err - } - - size := int64(binary.BigEndian.Uint32(hdr[:4])) - boxType := string(hdr[4:8]) - - if size == 1 { - // 64-bit extended size - var ext [8]byte - if _, err := io.ReadFull(rs, ext[:]); err != nil { - return nil, err - } - size = int64(binary.BigEndian.Uint64(ext[:])) - } - - if boxType == "moov" { - contentSize := size - 8 - buf := make([]byte, size) - copy(buf[:8], hdr[:]) - if _, err := io.ReadFull(rs, buf[8:]); err != nil { - return nil, fmt.Errorf("reading moov: %w", err) - } - box, err := mp4.Decode(buf, 0, int(size)) - if err != nil { - return nil, fmt.Errorf("decoding moov: %w", err) - } - _ = contentSize - return box, nil - } - - // Skip this box - skip := size - 8 - if skip > 0 { - if _, err := rs.Seek(skip, io.SeekCurrent); err != nil { - return nil, err - } - } - offset += size - } -} - -func findAndParseMoovBytes(data []byte) (*mp4.Box, error) { - ptr := 0 - for ptr+8 <= len(data) { - size := int(binary.BigEndian.Uint32(data[ptr:])) - if size < 8 { - return nil, fmt.Errorf("invalid box size %d at offset %d", size, ptr) - } - boxType := string(data[ptr+4 : ptr+8]) - if size == 1 && ptr+16 <= len(data) { - size = int(binary.BigEndian.Uint64(data[ptr+8:])) - } - if boxType == "moov" { - return mp4.Decode(data, ptr, ptr+size) - } - ptr += size - } - return nil, fmt.Errorf("moov box not found") -} - -func newRemuxer(moov *mp4.Box) (*Remuxer, error) { - mvhd := moov.Child(mp4.TypeMvhd) - if mvhd == nil || mvhd.Mvhd == nil { - return nil, fmt.Errorf("missing mvhd") - } - - traks := moov.ChildList(mp4.TypeTrak) - if len(traks) == 0 { - return nil, fmt.Errorf("no tracks found") - } - - r := &Remuxer{} - hasVideo := false - hasAudio := false - - for _, trak := range traks { - tkhdBox := trak.Child(mp4.TypeTkhd) - if tkhdBox == nil || tkhdBox.Tkhd == nil { - continue - } - mdiaBox := trak.Child(mp4.TypeMdia) - if mdiaBox == nil { - continue - } - hdlrBox := mdiaBox.Child(mp4.TypeHdlr) - if hdlrBox == nil || hdlrBox.Hdlr == nil { - continue - } - minfBox := mdiaBox.Child(mp4.TypeMinf) - if minfBox == nil { - continue - } - stblBox := minfBox.Child(mp4.TypeStbl) - if stblBox == nil { - continue - } - mdhdBox := mdiaBox.Child(mp4.TypeMdhd) - if mdhdBox == nil || mdhdBox.Mdhd == nil { - continue - } - - handlerType := string(hdlrBox.Hdlr.HandlerType[:]) - - stsdBox := stblBox.Child(mp4.TypeStsd) - if stsdBox == nil || stsdBox.Stsd == nil || len(stsdBox.Stsd.Entries) == 0 { - continue - } - stsdEntry := stsdBox.Stsd.Entries[0] - - var codec, mime string - - if handlerType == "vide" && stsdEntry.Type == mp4.TypeAvc1 { - if hasVideo { - continue - } - hasVideo = true - codec = "avc1" - if stsdEntry.Visual != nil { - for _, child := range stsdEntry.Visual.Children { - if child.Type == mp4.TypeAvcC && child.AvcC != nil { - codec += "." + child.AvcC.MimeCodec - break - } - } - } - mime = fmt.Sprintf(`video/mp4; codecs="%s"`, codec) - } else if handlerType == "soun" && stsdEntry.Type == mp4.TypeMp4a { - if hasAudio { - continue - } - hasAudio = true - codec = "mp4a" - if stsdEntry.Audio != nil { - for _, child := range stsdEntry.Audio.Children { - if child.Type == mp4.TypeEsds && child.Esds != nil && child.Esds.MimeCodec != "" { - codec += "." + child.Esds.MimeCodec - break - } - } - } - mime = fmt.Sprintf(`audio/mp4; codecs="%s"`, codec) - } else { - continue - } - - samples, defaultSdi, err := buildSampleTable(stblBox) - if err != nil { - return nil, fmt.Errorf("track %d: %w", tkhdBox.Tkhd.TrackId, err) - } - - track := &Track{ - TrackID: tkhdBox.Tkhd.TrackId, - TimeScale: mdhdBox.Mdhd.TimeScale, - Codec: codec, - Mime: mime, - Samples: samples, - defaultSampleDescriptionIndex: defaultSdi, - } - - // Build init segment - initBuf, err := buildInitSegment(mvhd, trak, track) - if err != nil { - return nil, fmt.Errorf("track %d init: %w", track.TrackID, err) - } - track.initBuf = initBuf - - r.Tracks = append(r.Tracks, track) - } - - if len(r.Tracks) == 0 { - return nil, fmt.Errorf("no playable tracks") - } - - return r, nil -} - -func buildSampleTable(stbl *mp4.Box) ([]Sample, uint32, error) { - stszBox := stbl.Child(mp4.TypeStsz) - if stszBox == nil || stszBox.Stsz == nil { - return nil, 0, fmt.Errorf("missing stsz") - } - sttsBox := stbl.Child(mp4.TypeStts) - if sttsBox == nil || sttsBox.Stts == nil { - return nil, 0, fmt.Errorf("missing stts") - } - stscBox := stbl.Child(mp4.TypeStsc) - if stscBox == nil || stscBox.Stsc == nil { - return nil, 0, fmt.Errorf("missing stsc") - } - - // Chunk offset table (stco or co64) - var chunkOffsets []int64 - if co64Box := stbl.Child(mp4.TypeCo64); co64Box != nil && co64Box.Co64 != nil { - chunkOffsets = make([]int64, len(co64Box.Co64.Entries)) - for i, v := range co64Box.Co64.Entries { - chunkOffsets[i] = int64(v) - } - } else if stcoBox := stbl.Child(mp4.TypeStco); stcoBox != nil && stcoBox.Stco != nil { - chunkOffsets = make([]int64, len(stcoBox.Stco.Entries)) - for i, v := range stcoBox.Stco.Entries { - chunkOffsets[i] = int64(v) - } - } else { - return nil, 0, fmt.Errorf("missing stco/co64") - } - - numSamples := len(stszBox.Stsz.Entries) - samples := make([]Sample, numSamples) - - // Chunk/position iterators - sampleInChunk := 0 - chunk := 0 - var offsetInChunk int64 - sampleToChunkIndex := 0 - stscEntries := stscBox.Stsc.Entries - - // Time iterators - var dts int64 - sttsEntries := sttsBox.Stts.Entries - decodingIdx := 0 - decodingOff := 0 - - // Composition offsets (optional) - var cttsEntries []mp4.CTTSEntry - cttsIdx := 0 - cttsOff := 0 - if cttsBox := stbl.Child(mp4.TypeCtts); cttsBox != nil && cttsBox.Ctts != nil { - cttsEntries = cttsBox.Ctts.Entries - } - - // Sync sample table (optional) - var syncEntries []uint32 - syncIdx := 0 - if stssBox := stbl.Child(mp4.TypeStss); stssBox != nil && stssBox.Stco != nil { - syncEntries = stssBox.Stco.Entries - } - - var defaultSdi uint32 - - for i := range numSamples { - currChunkEntry := stscEntries[sampleToChunkIndex] - defaultSdi = currChunkEntry.SampleDescriptionId - - size := stszBox.Stsz.Entries[i] - duration := sttsEntries[decodingIdx].Duration - - var presentationOffset int32 - if cttsEntries != nil && cttsIdx < len(cttsEntries) { - presentationOffset = cttsEntries[cttsIdx].CompositionOffset - } - - sync := true - if syncEntries != nil { - sync = syncIdx < len(syncEntries) && syncEntries[syncIdx] == uint32(i+1) - } - - samples[i] = Sample{ - Offset: offsetInChunk + chunkOffsets[chunk], - Size: size, - Duration: duration, - DTS: dts, - PresentationOffset: presentationOffset, - Sync: sync, - } - - // Advance to next sample - if i+1 >= numSamples { - break - } - - // Advance chunk position - sampleInChunk++ - offsetInChunk += int64(size) - if sampleInChunk >= int(currChunkEntry.SamplesPerChunk) { - sampleInChunk = 0 - offsetInChunk = 0 - chunk++ - if sampleToChunkIndex+1 < len(stscEntries) { - nextEntry := stscEntries[sampleToChunkIndex+1] - if uint32(chunk+1) >= nextEntry.FirstChunk { - sampleToChunkIndex++ - } - } - } - - // Advance time - dts += int64(duration) - decodingOff++ - if decodingOff >= int(sttsEntries[decodingIdx].Count) { - decodingIdx++ - decodingOff = 0 - } - - // Advance composition offset - if cttsEntries != nil { - cttsOff++ - if cttsIdx < len(cttsEntries) && cttsOff >= int(cttsEntries[cttsIdx].Count) { - cttsIdx++ - cttsOff = 0 - } - } - - // Advance sync index - if sync { - syncIdx++ - } - } - - return samples, defaultSdi, nil -} - -func buildInitSegment(mvhd *mp4.Box, trak *mp4.Box, track *Track) ([]byte, error) { - tkhdBox := trak.Child(mp4.TypeTkhd) - mdiaBox := trak.Child(mp4.TypeMdia) - mdhdBox := mdiaBox.Child(mp4.TypeMdhd) - hdlrBox := mdiaBox.Child(mp4.TypeHdlr) - minfBox := mdiaBox.Child(mp4.TypeMinf) - stblBox := minfBox.Child(mp4.TypeStbl) - stsdBox := stblBox.Child(mp4.TypeStsd) - - // Clone tkhd with duration=0 - tkhdClone := *tkhdBox.Tkhd - be.PutUint32(tkhdClone.CTime[:], be.Uint32(tkhdBox.Tkhd.CTime[:])) - // zero out duration - tkhdClone.Duration = 0 - - // Clone mdhd with duration=0 - mdhdClone := *mdhdBox.Mdhd - mdhdClone.Duration = 0 - - emptyBox := func(t mp4.BoxType) *mp4.Box { - return &mp4.Box{ - Type: t, - Version: 0, - Flags: 0, - } - } - - emptyEntryBox := func(t mp4.BoxType) *mp4.Box { - b := emptyBox(t) - switch t { - case mp4.TypeStts: - b.Stts = &mp4.Stts{} - case mp4.TypeCtts: - b.Ctts = &mp4.Ctts{} - case mp4.TypeStsc: - b.Stsc = &mp4.Stsc{} - case mp4.TypeStsz: - b.Stsz = &mp4.Stsz{} - case mp4.TypeStco: - b.Stco = &mp4.Stco{} - case mp4.TypeStss: - b.Stco = &mp4.Stco{} // stss uses same codec as stco - } - return b - } - - // Build minf children - minfChildren := make(map[mp4.BoxType][]*mp4.Box) - // Copy vmhd or smhd - if vmhd := minfBox.Child(mp4.TypeVmhd); vmhd != nil { - minfChildren[mp4.TypeVmhd] = []*mp4.Box{vmhd} - } - if smhd := minfBox.Child(mp4.TypeSmhd); smhd != nil { - minfChildren[mp4.TypeSmhd] = []*mp4.Box{smhd} - } - if dinf := minfBox.Child(mp4.TypeDinf); dinf != nil { - minfChildren[mp4.TypeDinf] = []*mp4.Box{dinf} - } - - stblNew := &mp4.Box{ - Type: mp4.TypeStbl, - Children: map[mp4.BoxType][]*mp4.Box{ - mp4.TypeStsd: {stsdBox}, - mp4.TypeStts: {emptyEntryBox(mp4.TypeStts)}, - mp4.TypeCtts: {emptyEntryBox(mp4.TypeCtts)}, - mp4.TypeStsc: {emptyEntryBox(mp4.TypeStsc)}, - mp4.TypeStsz: {emptyEntryBox(mp4.TypeStsz)}, - mp4.TypeStco: {emptyEntryBox(mp4.TypeStco)}, - mp4.TypeStss: {emptyEntryBox(mp4.TypeStss)}, - }, - } - minfChildren[mp4.TypeStbl] = []*mp4.Box{stblNew} - - // Clone mvhd with duration=0 - mvhdClone := *mvhd.Mvhd - mvhdClone.Duration = 0 - mvhdBox := &mp4.Box{Type: mp4.TypeMvhd, Version: mvhd.Version, Flags: mvhd.Flags, Mvhd: &mvhdClone} - - moov := &mp4.Box{ - Type: mp4.TypeMoov, - Children: map[mp4.BoxType][]*mp4.Box{ - mp4.TypeMvhd: {mvhdBox}, - mp4.TypeTrak: {{ - Type: mp4.TypeTrak, - Children: map[mp4.BoxType][]*mp4.Box{ - mp4.TypeTkhd: {{Type: mp4.TypeTkhd, Version: tkhdBox.Version, Flags: tkhdBox.Flags, Tkhd: &tkhdClone}}, - mp4.TypeMdia: {{ - Type: mp4.TypeMdia, - Children: map[mp4.BoxType][]*mp4.Box{ - mp4.TypeMdhd: {{Type: mp4.TypeMdhd, Version: mdhdBox.Version, Flags: mdhdBox.Flags, Mdhd: &mdhdClone}}, - mp4.TypeHdlr: {hdlrBox}, - mp4.TypeMinf: {{ - Type: mp4.TypeMinf, - Children: minfChildren, - }}, - }, - }}, - }, - }}, - mp4.TypeMvex: {{ - Type: mp4.TypeMvex, - Children: map[mp4.BoxType][]*mp4.Box{ - mp4.TypeMehd: {{Type: mp4.TypeMehd, Mehd: &mp4.Mehd{FragmentDuration: mvhd.Mvhd.Duration}}}, - mp4.TypeTrex: {{Type: mp4.TypeTrex, Trex: &mp4.Trex{ - TrackId: track.TrackID, - DefaultSampleDescriptionIndex: track.defaultSampleDescriptionIndex, - }}}, - }, - }}, - }, - } - - ftyp := &mp4.Box{ - Type: mp4.TypeFtyp, - Ftyp: &mp4.Ftyp{ - Brand: [4]byte{'i', 's', 'o', '5'}, - BrandVersion: 0, - CompatibleBrands: [][4]byte{{'i', 's', 'o', '5'}}, - }, - } - - ftypBuf, err := mp4.EncodeToBytes(ftyp) - if err != nil { - return nil, err - } - moovBuf, err := mp4.EncodeToBytes(moov) - if err != nil { - return nil, err - } - - out := make([]byte, len(ftypBuf)+len(moovBuf)) - copy(out, ftypBuf) - copy(out[len(ftypBuf):], moovBuf) - return out, nil -} - -// InitSegment returns the pre-built init segment (ftyp+moov) for the given track. -func (t *Track) InitSegment() []byte { - return t.initBuf -} - -// Duration returns the total duration of the track in seconds. -func (t *Track) Duration() float64 { - if len(t.Samples) == 0 || t.TimeScale == 0 { - return 0 - } - last := t.Samples[len(t.Samples)-1] - return float64(last.DTS+int64(last.Duration)) / float64(t.TimeScale) -} - -// Fragment represents a moof+mdat fragment to be written. -type Fragment struct { - trackID uint32 - timeScale uint32 - firstSample int - lastSample int // exclusive - samples []Sample - sequenceNumber uint32 - version uint8 -} - -// FindSampleBefore finds the sync sample at or before the given time (in seconds). -// Useful for seeking backward to a safe playback position. -func (t *Track) FindSampleBefore(timeSeconds float64) int { - scaledTime := int64(timeSeconds * float64(t.TimeScale)) - - // Binary search: find last sample with pts <= scaledTime - idx := max(sort.Search(len(t.Samples), func(i int) bool { - pts := t.Samples[i].DTS + int64(t.Samples[i].PresentationOffset) - return pts > scaledTime - })-1, 0) - - // Walk backward to find the preceding sync sample - for idx > 0 && !t.Samples[idx].Sync { - idx-- - } - - return idx -} - -// FindSampleAfter finds the first sync sample at or after the given time (in seconds). -// Useful for finding a clean start point for time-based extraction. -func (t *Track) FindSampleAfter(timeSeconds float64) int { - scaledTime := int64(timeSeconds * float64(t.TimeScale)) - - // Binary search: find first sample with pts >= scaledTime - idx := sort.Search(len(t.Samples), func(i int) bool { - pts := t.Samples[i].DTS + int64(t.Samples[i].PresentationOffset) - return pts >= scaledTime - }) - - if idx >= len(t.Samples) { - return len(t.Samples) - 1 - } - - // Walk forward to find the next sync sample - for idx < len(t.Samples) && !t.Samples[idx].Sync { - idx++ - } - - // If went past the end, return the last sample - if idx >= len(t.Samples) { - return len(t.Samples) - 1 - } - - return idx -} - -// byteRange represents a contiguous range of bytes in the source file. -type byteRange struct { - Start int64 - End int64 // exclusive -} - -// generateFragment builds fragment metadata for samples starting at firstSample. -// trunEntries and ranges are caller-provided slices that will be reused (resliced). -// Returns the populated slices, total mdat payload size, next sample index, and trun version. -func generateFragment(track *Track, firstSample int, endTimeScaled int64, trunEntries []mp4.TrunEntry, ranges []byteRange) ([]mp4.TrunEntry, []byteRange, int64, int, uint8) { - samples := track.Samples - if firstSample >= len(samples) { - return trunEntries[:0], ranges[:0], 0, firstSample, 0 - } - - startDts := samples[firstSample].DTS - threshold := int64(track.TimeScale) * minFragmentDuration - - // Find the end of this fragment - lastSample := firstSample - - for lastSample < len(samples) { - s := samples[lastSample] - pts := s.DTS + int64(s.PresentationOffset) - - // Hard stop: don't include any sample at or past end time - if endTimeScaled > 0 && pts >= endTimeScaled { - break - } - - // Fragment boundary: when no end time, break at sync samples - // after minimum duration - if endTimeScaled == 0 && lastSample > firstSample && s.Sync { - elapsed := s.DTS - startDts - if elapsed >= threshold { - break - } - } - - lastSample++ - } - - n := lastSample - firstSample - if n == 0 { - return trunEntries[:0], ranges[:0], 0, lastSample, 0 - } - - // Grow trunEntries when needed - if cap(trunEntries) < n { - trunEntries = make([]mp4.TrunEntry, n) - } else { - trunEntries = trunEntries[:n] - } - - var totalLen int64 - var trunVersion uint8 - - for i := range n { - s := samples[firstSample+i] - if s.PresentationOffset < 0 { - trunVersion = 1 - } - flags := uint32(0x2000000) // sync - if !s.Sync { - flags = 0x1010000 // non-sync - } - trunEntries[i] = mp4.TrunEntry{ - SampleDuration: s.Duration, - SampleSize: s.Size, - SampleFlags: flags, - SampleCompositionTimeOffset: s.PresentationOffset, - } - totalLen += int64(s.Size) - } - - // Build contiguous byte ranges, reuse slice - ranges = ranges[:0] - for i := range n { - s := samples[firstSample+i] - sStart := s.Offset - sEnd := s.Offset + int64(s.Size) - if len(ranges) > 0 && ranges[len(ranges)-1].End == sStart { - ranges[len(ranges)-1].End = sEnd - } else { - ranges = append(ranges, byteRange{Start: sStart, End: sEnd}) - } - } - - return trunEntries, ranges, totalLen, lastSample, trunVersion -} - -// WriteTo writes a complete fragmented MP4 stream for a single track, -// starting from the given time (seconds), to w. -// If endTime > 0, stops writing fragments at or before the given end time. -// -// Each call creates a new [Writer]. For repeated calls, create a [Writer] -// once and call its [Writer.WriteTo] method instead of this helper. -func WriteTo(w io.Writer, rs io.ReadSeeker, track *Track, startTime float64, endTime float64) error { - return NewWriter().WriteTo(w, rs, track, startTime, endTime) -} diff --git a/remux/writer.go b/remux/writer.go deleted file mode 100644 index 89c06ba..0000000 --- a/remux/writer.go +++ /dev/null @@ -1,193 +0,0 @@ -package remux - -import ( - "encoding/binary" - "io" - - "github.com/tetsuo/mp4" -) - -// Writer holds reusable buffers for writing fragmented MP4 streams. -// -// A Writer is NOT safe for concurrent use. Use one Writer per goroutine, -// or protect with a mutex. -type Writer struct { - trunEntries []mp4.TrunEntry - ranges []byteRange - copyBuf []byte - moofBuf []byte - mdatHdr [8]byte -} - -// NewWriter creates a Writer with pre-allocated buffers. -func NewWriter() *Writer { - return &Writer{ - trunEntries: make([]mp4.TrunEntry, 0, 512), - ranges: make([]byteRange, 0, 64), - copyBuf: make([]byte, 32768), - moofBuf: make([]byte, 0, 8192), - } -} - -// WriteTo writes a complete fragmented MP4 stream for a single track to w. -// rs must support Seek+Read (e.g. *[os.File]). -// For concurrent use with a shared file, use [Writer.WriteToFrom] with [io.ReaderAt] instead. -func (wr *Writer) WriteTo(w io.Writer, rs io.ReadSeeker, track *Track, startTime float64, endTime float64) error { - firstSample, dtsOffset, endTimeScaled := wr.resolveRange(track, startTime, endTime) - - if _, err := w.Write(track.InitSegment()); err != nil { - return err - } - - var seqNum uint32 = 1 - sample := firstSample - - for sample < len(track.Samples) { - if endTimeScaled > 0 { - pts := track.Samples[sample].DTS + int64(track.Samples[sample].PresentationOffset) - if pts >= endTimeScaled { - break - } - } - - var mdatSize int64 - var nextSample int - var trunVersion uint8 - wr.trunEntries, wr.ranges, mdatSize, nextSample, trunVersion = generateFragment(track, sample, endTimeScaled, wr.trunEntries, wr.ranges) - if len(wr.trunEntries) == 0 { - break - } - - baseMediaDecodeTime := uint32(track.Samples[sample].DTS - dtsOffset) - var err error - wr.moofBuf, err = writeMoof(w, seqNum, track.TrackID, baseMediaDecodeTime, wr.trunEntries, trunVersion, wr.moofBuf) - if err != nil { - return err - } - - binary.BigEndian.PutUint32(wr.mdatHdr[:4], uint32(8+mdatSize)) - copy(wr.mdatHdr[4:8], "mdat") - if _, err := w.Write(wr.mdatHdr[:]); err != nil { - return err - } - - for _, r := range wr.ranges { - if _, err := rs.Seek(r.Start, io.SeekStart); err != nil { - return err - } - remaining := r.End - r.Start - for remaining > 0 { - n := min(int64(len(wr.copyBuf)), remaining) - nr, err := rs.Read(wr.copyBuf[:n]) - if nr > 0 { - if _, werr := w.Write(wr.copyBuf[:nr]); werr != nil { - return werr - } - remaining -= int64(nr) - } - if err != nil { - if err == io.EOF && remaining == 0 { - break - } - return err - } - } - } - - seqNum++ - sample = nextSample - } - - return nil -} - -// WriteToFrom writes a complete fragmented MP4 stream using an [io.ReaderAt]. -// Unlike [Writer.WriteTo], this is safe to use with a single shared *[os.File] from multiple -// goroutines (each with their own Writer), because [io.ReaderAt.ReadAt] does not mutate file position. -func (wr *Writer) WriteToFrom(w io.Writer, ra io.ReaderAt, track *Track, startTime float64, endTime float64) error { - firstSample, dtsOffset, endTimeScaled := wr.resolveRange(track, startTime, endTime) - - if _, err := w.Write(track.InitSegment()); err != nil { - return err - } - - var seqNum uint32 = 1 - sample := firstSample - - for sample < len(track.Samples) { - if endTimeScaled > 0 { - pts := track.Samples[sample].DTS + int64(track.Samples[sample].PresentationOffset) - if pts >= endTimeScaled { - break - } - } - - var mdatSize int64 - var nextSample int - var trunVersion uint8 - wr.trunEntries, wr.ranges, mdatSize, nextSample, trunVersion = generateFragment(track, sample, endTimeScaled, wr.trunEntries, wr.ranges) - if len(wr.trunEntries) == 0 { - break - } - - baseMediaDecodeTime := uint32(track.Samples[sample].DTS - dtsOffset) - var err error - wr.moofBuf, err = writeMoof(w, seqNum, track.TrackID, baseMediaDecodeTime, wr.trunEntries, trunVersion, wr.moofBuf) - if err != nil { - return err - } - - binary.BigEndian.PutUint32(wr.mdatHdr[:4], uint32(8+mdatSize)) - copy(wr.mdatHdr[4:8], "mdat") - if _, err := w.Write(wr.mdatHdr[:]); err != nil { - return err - } - - for _, r := range wr.ranges { - off := r.Start - remaining := r.End - r.Start - for remaining > 0 { - n := min(int64(len(wr.copyBuf)), remaining) - nr, err := ra.ReadAt(wr.copyBuf[:n], off) - if nr > 0 { - if _, werr := w.Write(wr.copyBuf[:nr]); werr != nil { - return werr - } - off += int64(nr) - remaining -= int64(nr) - } - if err != nil { - if err == io.EOF && remaining == 0 { - break - } - return err - } - } - } - - seqNum++ - sample = nextSample - } - - return nil -} - -func (wr *Writer) resolveRange(track *Track, startTime float64, endTime float64) (firstSample int, dtsOffset int64, endTimeScaled int64) { - firstSample = track.FindSampleAfter(startTime) - - if endTime > 0 && firstSample < len(track.Samples) { - pts := track.Samples[firstSample].DTS + int64(track.Samples[firstSample].PresentationOffset) - endScaled := int64(endTime * float64(track.TimeScale)) - if pts >= endScaled { - firstSample = track.FindSampleBefore(startTime) - } - } - - dtsOffset = track.Samples[firstSample].DTS - - if endTime > 0 { - endTimeScaled = int64(endTime * float64(track.TimeScale)) - } - - return -} |
