Skip to content

Commit

Permalink
fix: robust stsc allocations by early size consistency check
Browse files Browse the repository at this point in the history
  • Loading branch information
tobbee committed Jan 14, 2025
1 parent e108010 commit 5a3edce
Showing 1 changed file with 11 additions and 15 deletions.
26 changes: 11 additions & 15 deletions mp4/stsc.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ import (
"github.com/Eyevinn/mp4ff/bits"
)

const (
safeAllocationSize = 512
)

// StscBox is Sample To Chunk Box in progressive file.
//
// A chunk contains samples. This table defines to which chunk a sample is associated.
Expand Down Expand Up @@ -53,9 +49,13 @@ func DecodeStscSR(hdr BoxHeader, startPos uint64, sr bits.SliceReader) (Box, err
b := StscBox{
Version: byte(versionAndFlags >> 24),
Flags: versionAndFlags & flagsMask,
Entries: make([]StscEntry, 0, limitedInitialSize(entryCount)),
}
if hdr.Size != b.expectedSize(int(entryCount)) {
return nil, fmt.Errorf("invalid stsc box size")
}

b.Entries = make([]StscEntry, 0, entryCount)

var accSampleNr uint32 = 1

for i := 0; i < int(entryCount); i++ {
Expand All @@ -74,7 +74,7 @@ func DecodeStscSR(hdr BoxHeader, startPos uint64, sr bits.SliceReader) (Box, err
} else {
if sdi != b.singleSampleDescriptionID {
if b.singleSampleDescriptionID != 0 {
b.SampleDescriptionID = make([]uint32, 0, limitedInitialSize(entryCount))
b.SampleDescriptionID = make([]uint32, 0, entryCount)
for j := 0; j < i; j++ {
b.SampleDescriptionID = append(b.SampleDescriptionID, b.singleSampleDescriptionID)
}
Expand All @@ -94,7 +94,11 @@ func (b *StscBox) Type() string {

// Size - box-specific size
func (b *StscBox) Size() uint64 {
return uint64(boxHeaderSize + 8 + len(b.Entries)*12)
return b.expectedSize(len(b.Entries))
}

func (b *StscBox) expectedSize(nrEntries int) uint64 {
return uint64(boxHeaderSize + 8 + nrEntries*12)
}

// Encode - write box to w
Expand Down Expand Up @@ -288,11 +292,3 @@ func (b *StscBox) FindEntryNrForSampleNr(sampleNr, lowEntryIdx uint32) uint32 {
}
return low - 1
}

// limitedInitialSize returns a limited size to prevent from excessive initial allocation.
func limitedInitialSize(a uint32) uint32 {
if a > safeAllocationSize {
return safeAllocationSize
}
return a
}

0 comments on commit 5a3edce

Please sign in to comment.