Skip to content

Commit

Permalink
Fix frame timecode overflow (#5)
Browse files Browse the repository at this point in the history
* Add "target" to gitignore.

* fix: Fix case where frames might be added out of order

For example, if an entire track is added starting at timecode 0,
and then another track is added starting against at timecode 0.
  • Loading branch information
bgrozev authored Dec 18, 2024
1 parent 09e9281 commit 5cec011
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ build/
.classpath
.settings/
.project
target
14 changes: 10 additions & 4 deletions src/main/java/org/ebml/matroska/MatroskaCluster.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class MatroskaCluster
private final List<Long> sliencedTracks = new ArrayList<>();

private long clusterTimecode = Long.MAX_VALUE;
private long lastTimecode = 0;
private long maxFrameTimecode = 0;
private long durationLimit = 500;

public MatroskaCluster()
Expand All @@ -69,14 +69,19 @@ public void addFrame(final MatroskaFileFrame frame)
{
clusterTimecode = frame.getTimecode();
}
lastTimecode = frame.getTimecode();
maxFrameTimecode = Math.max(maxFrameTimecode, frame.getTimecode());
frames.add(frame);
tracks.add(frame.getTrackNo());
}

public boolean isFlushNeeded()
public boolean isFlushNeeded(long nextFrameTimecode)
{
return (lastTimecode - clusterTimecode) > durationLimit;
return
// The next frame will exceed the duration limit
(nextFrameTimecode - clusterTimecode) > durationLimit ||
// The next frame is older, and would lower the cluster timecode enough to overflow the frame timecode
// for one of the existing frames.
maxFrameTimecode - nextFrameTimecode > Short.MAX_VALUE;
}

public long flush(final DataWriter ioDW)
Expand Down Expand Up @@ -136,6 +141,7 @@ public long flush(final DataWriter ioDW)
frames.clear();
tracks.clear();
clusterTimecode = Long.MAX_VALUE;
maxFrameTimecode = Long.MIN_VALUE;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/ebml/matroska/MatroskaFileWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public void unsilenceTrack(final long trackNumber)
public void addFrame(final MatroskaFileFrame frame)
{
initialize();
if ((onlyAudioTracks && cluster.isFlushNeeded())
if ((onlyAudioTracks && cluster.isFlushNeeded(frame.getTimecode()))
|| (frame.isKeyFrame() && videoTrackNumbers.contains(frame.getTrackNo())))
{
flush();
Expand Down

0 comments on commit 5cec011

Please sign in to comment.