Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Account for overlapping sidx subsegment durations by parsing earlierstPresentationTime #6192

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 28 additions & 9 deletions src/utils/mp4-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@
return val < 0 ? 4294967296 + val : val;
}

export function readUint64(buffer: Uint8Array, offset: number) {
let result = readUint32(buffer, offset);
result *= Math.pow(2, 32);
result += readUint32(buffer, offset + 4);
return result;
}

export function readSint32(buffer: Uint8Array, offset: number): number {
return (
(buffer[offset] << 24) |
Expand Down Expand Up @@ -125,15 +132,15 @@
const timescale = readUint32(sidx, index);
index += 4;

// TODO: parse earliestPresentationTime and firstOffset
// usually zero in our case
const earliestPresentationTime = 0;
const firstOffset = 0;
let earliestPresentationTime = 0;
let firstOffset = 0;

if (version === 0) {
index += 8;
earliestPresentationTime = readUint32(sidx, (index += 4));
firstOffset = readUint32(sidx, (index += 4));
} else {
index += 16;
earliestPresentationTime = readUint64(sidx, (index += 8));
firstOffset = readUint64(sidx, (index += 8));
}

// skip reserved
Expand Down Expand Up @@ -469,7 +476,7 @@

function skipBERInteger(bytes: Uint8Array, i: number): number {
const limit = i + 5;
while (bytes[i++] & 0x80 && i < limit) {}

Check warning on line 479 in src/utils/mp4-tools.ts

View workflow job for this annotation

GitHub Actions / build

Empty block statement
return i;
}

Expand Down Expand Up @@ -677,19 +684,31 @@
}
if (videoDuration === 0 && audioDuration === 0) {
// If duration samples are not available in the traf use sidx subsegment_duration
let sidxMinStart = Infinity;
let sidxMaxEnd = 0;
let sidxDuration = 0;
const sidxs = findBox(data, ['sidx']);
for (let i = 0; i < sidxs.length; i++) {
const sidx = parseSegmentIndex(sidxs[i]);
if (sidx?.references) {
sidxDuration += sidx.references.reduce(
sidxMinStart = Math.min(
sidxMinStart,
sidx.earliestPresentationTime / sidx.timescale,
);
const subSegmentDuration = sidx.references.reduce(
(dur, ref) => dur + ref.info.duration || 0,
0,
);
sidxMaxEnd = Math.max(
sidxMaxEnd,
subSegmentDuration + sidx.earliestPresentationTime / sidx.timescale,
);
sidxDuration = sidxMaxEnd - sidxMinStart;
}
}

return sidxDuration;
if (sidxDuration && Number.isFinite(sidxDuration)) {
return sidxDuration;
}
}
if (videoDuration) {
return videoDuration;
Expand Down
Loading