@@ -12,21 +12,33 @@ const (
1212 maxBasetime = 1 * time .Second
1313)
1414
15- func findOldestNextSample (tracks []* formatFMP4Track ) (* sample , time.Duration ) {
16- var oldestSample * sample
17- var oldestDTS time.Duration
15+ // start next segment from the oldest next sample, in order to avoid negative basetimes (impossible) in fMP4.
16+ // keep starting position within a certain distance from the newest next sample to avoid big basetimes.
17+ func nextSegmentStartingPos (tracks []* formatFMP4Track ) (time.Time , time.Duration ) {
18+ var maxDTS time.Duration
19+ for _ , track := range tracks {
20+ if track .nextSample != nil {
21+ dts := timestampToDuration (track .nextSample .dts , int (track .initTrack .TimeScale ))
22+ if dts > maxDTS {
23+ maxDTS = dts
24+ }
25+ }
26+ }
27+
28+ var oldestNTP time.Time
29+ oldestDTS := maxDTS
1830
1931 for _ , track := range tracks {
2032 if track .nextSample != nil {
21- normalizedDTS := timestampToDuration (track .nextSample .dts , int (track .initTrack .TimeScale ))
22- if oldestSample == nil || normalizedDTS < oldestDTS {
23- oldestSample = track .nextSample
24- oldestDTS = normalizedDTS
33+ dts := timestampToDuration (track .nextSample .dts , int (track .initTrack .TimeScale ))
34+ if ( maxDTS - dts ) <= maxBasetime && ( dts <= oldestDTS ) {
35+ oldestNTP = track .nextSample . ntp
36+ oldestDTS = dts
2537 }
2638 }
2739 }
2840
29- return oldestSample , oldestDTS
41+ return oldestNTP , oldestDTS
3042}
3143
3244type formatFMP4Track struct {
@@ -77,19 +89,12 @@ func (t *formatFMP4Track) write(sample *sample) error {
7789 return err
7890 }
7991
80- // start next segment from the oldest next sample, in order to avoid the "negative basetime" issue
81- oldestSample , oldestDTS := findOldestNextSample (t .f .tracks )
82-
83- // prevent going too back in time
84- if (nextDTS - oldestDTS ) > maxBasetime {
85- oldestSample = t .nextSample
86- oldestDTS = nextDTS
87- }
92+ oldestNTP , oldestDTS := nextSegmentStartingPos (t .f .tracks )
8893
8994 t .f .currentSegment = & formatFMP4Segment {
9095 f : t .f ,
9196 startDTS : oldestDTS ,
92- startNTP : oldestSample . ntp ,
97+ startNTP : oldestNTP ,
9398 }
9499 t .f .currentSegment .initialize ()
95100 }
0 commit comments