Skip to content

Commit

Permalink
Fix race condition of _startTime
Browse files Browse the repository at this point in the history
  • Loading branch information
longnguyen2004 committed Jan 24, 2025
1 parent fe966f8 commit 1e005b5
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/media/BaseMediaStream.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Log } from "debug-level";
import { setImmediate } from "node:timers";
import { setTimeout } from "node:timers/promises";
import { Writable } from "node:stream";
import { combineLoHi } from "./utils.js";
Expand Down Expand Up @@ -32,8 +33,19 @@ export class BaseMediaStream extends Writable {
if (val)
{
// Reset timestamp stats when enabling sync
this._startPts = this._startTime = undefined;
this._loggerSync.debug("Sync enabled");
/**
* Since _waitForOtherStream() is an async function, it can only
* return at the end of the event loop, while Node.js is processing
* the microtask queue. If this is run synchronously, it can set
* _startTime to undefined before _waitForOtherStream() returns,
* which will cause the timeout calculation below to return NaN.
* Use setImmediate to put this on the macrotask queue, which is
* processed after the microtask queue.
*/
setImmediate(() => {
this._startPts = this._startTime = undefined;
this._loggerSync.debug("Sync enabled");
});
}
else
{
Expand Down

0 comments on commit 1e005b5

Please sign in to comment.