Skip to content

Commit

Permalink
refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
vpalmisano committed Oct 14, 2024
1 parent 26f817f commit 8c9e0fe
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 90 deletions.
89 changes: 61 additions & 28 deletions scripts/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,37 +48,45 @@ webrtcperf.safeStringify = obj => {
* log
* @param {...any} args args
*/
function log(...args) {
webrtcperf.log = (...args) => {
console.log.apply(null, [`[webrtcperf-${window.WEBRTC_PERF_INDEX}]`, ...args])
}
const log = webrtcperf.log

/**
* sleep
* @param {number} ms ms
* @return {Promise}
*/
function sleep(ms) {
webrtcperf.sleep = ms => {
return new Promise(resolve => setTimeout(resolve, ms))
}
const sleep = webrtcperf.sleep

/**
* getParticipantName
*/
window.getParticipantName = (index = window.WEBRTC_PERF_INDEX || 0) => {
webrtcperf.getParticipantName = window.getParticipantName = (
index = window.WEBRTC_PERF_INDEX || 0,
) => {
return `Participant-${index.toString().padStart(6, '0')}`
}

window.getParticipantNameForSave = (sendrecv, track) => {
webrtcperf.getParticipantNameForSave = window.getParticipantNameForSave = (
sendrecv,
track,
) => {
return `${window.getParticipantName()}_${sendrecv}_${track.id}`
}

/**
* Returns the name of the sender participant for a given track.
* @param {MediaStreamTrack} track
*/
window.getReceiverParticipantName = track => {
return track.id
}
webrtcperf.getReceiverParticipantName = window.getReceiverParticipantName =
track => {
return track.id
}

/**
* getElement
Expand All @@ -87,12 +95,16 @@ window.getReceiverParticipantName = track => {
* @param {boolean} throwError
* @return {Promise<HTMLElement>}
*/
window.getElement = async (selector, timeout = 60000, throwError = false) => {
webrtcperf.getElement = window.getElement = async (
selector,
timeout = 60000,
throwError = false,
) => {
let element = document.querySelector(selector)
if (timeout) {
const startTime = Date.now()
while (!element && Date.now() - startTime < timeout) {
await sleep(Math.min(timeout / 2, 1000))
await sleep(Math.max(timeout / 2, 200))
element = document.querySelector(selector)
}
}
Expand All @@ -110,7 +122,7 @@ window.getElement = async (selector, timeout = 60000, throwError = false) => {
* @param {string} innerText
* @return {Promise<HTMLElement[]>}
*/
window.getElements = async (
webrtcperf.getElements = window.getElements = async (
selector,
timeout = 60000,
throwError = false,
Expand All @@ -136,10 +148,23 @@ window.getElements = async (
}
}

webrtcperf.simulateMouseClick = element => {
;['mousedown', 'click', 'mouseup'].forEach(event =>
element.dispatchEvent(
new MouseEvent(event, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1,
}),
),
)
}

/**
* overrideLocalStorage
*/
window.overrideLocalStorage = () => {
webrtcperf.overrideLocalStorage = window.overrideLocalStorage = () => {
if (window.LOCAL_STORAGE) {
try {
const values = JSON.parse(window.LOCAL_STORAGE)
Expand All @@ -152,14 +177,18 @@ window.overrideLocalStorage = () => {
}
}

window.injectCss = css => {
webrtcperf.injectCss = window.injectCss = css => {
const style = document.createElement('style')
style.setAttribute('type', 'text/css')
style.innerHTML = css
document.head.appendChild(style)
}

window.watchObjectProperty = (object, name, cb) => {
webrtcperf.watchObjectProperty = window.watchObjectProperty = (
object,
name,
cb,
) => {
let value = object[name]
Object.defineProperty(object, name, {
get: function () {
Expand All @@ -172,7 +201,11 @@ window.watchObjectProperty = (object, name, cb) => {
})
}

window.loadScript = (name, src = '', textContent = '') => {
webrtcperf.loadScript = window.loadScript = (
name,
src = '',
textContent = '',
) => {
return new Promise((resolve, reject) => {
let script = document.getElementById(name)
if (script) {
Expand All @@ -198,7 +231,7 @@ window.loadScript = (name, src = '', textContent = '') => {
})
}

window.harmonicMean = array => {
webrtcperf.harmonicMean = array => {
return array.length
? 1 /
(array.reduce((sum, b) => {
Expand All @@ -209,15 +242,15 @@ window.harmonicMean = array => {
: 0
}

window.unregisterServiceWorkers = () => {
webrtcperf.unregisterServiceWorkers = () => {
navigator.serviceWorker.getRegistrations().then(registrations => {
for (let registration of registrations) {
registration.unregister()
}
})
}

window.MeasuredStats = class {
webrtcperf.MeasuredStats = window.MeasuredStats = class {
constructor(
{ ttl, maxItems, secondsPerSample, storeId } = {
ttl: 0,
Expand Down Expand Up @@ -354,7 +387,11 @@ window.MeasuredStats = class {
}
}

window.enabledForSession = value => {
/**
* Check if the current session is included into the value setting configuration.
* @param {number | string | boolean} value A session ID number, a range of numbers separated by a dash, a comma separated list of numbers or a boolean.
*/
webrtcperf.enabledForSession = value => {
if (value === true || value === 'true') {
return true
} else if (value === false || value === 'false' || value === undefined) {
Expand Down Expand Up @@ -385,10 +422,9 @@ window.enabledForSession = value => {
// Common page actions
let actionsStarted = false

window.webrtcPerfElapsedTime = () =>
Date.now() - window.WEBRTC_PERF_START_TIMESTAMP
webrtcperf.elapsedTime = () => Date.now() - window.WEBRTC_PERF_START_TIMESTAMP

window.setupActions = async () => {
webrtcperf.setupActions = async () => {
if (!window.PARAMS?.actions || actionsStarted) {
return
}
Expand All @@ -407,12 +443,12 @@ window.setupActions = async () => {
}

if (index !== undefined) {
if (!window.enabledForSession(index)) {
if (!webrtcperf.enabledForSession(index)) {
return
}
}

const setupTime = window.webrtcPerfElapsedTime()
const setupTime = webrtcperf.elapsedTime()
let startTime = at > 0 ? at * 1000 - setupTime : 0
if (startTime < 0) {
log(
Expand All @@ -436,7 +472,7 @@ window.setupActions = async () => {
)
let currentIteration = 0
const cb = async () => {
const now = window.webrtcPerfElapsedTime()
const now = webrtcperf.elapsedTime()
const ts = (now / 1000).toFixed(0)
log(
`run action [${ts}s] ${name}(${params || ''})${
Expand All @@ -453,10 +489,7 @@ window.setupActions = async () => {
} else {
await fn()
}
const elapsed = (
(window.webrtcPerfElapsedTime() - now) /
1000
).toFixed(3)
const elapsed = ((webrtcperf.elapsedTime() - now) / 1000).toFixed(3)
log(
`run action [${ts}s] [${window.WEBRTC_PERF_INDEX}] ${name} done (${elapsed}s elapsed)`,
)
Expand Down
4 changes: 2 additions & 2 deletions scripts/e2e-audio-stats.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global log, enabledForSession, ggwave_factory, MeasuredStats */
/* global webrtcperf, log, ggwave_factory, MeasuredStats */

/**
* Audio end-to-end delay stats.
Expand All @@ -18,7 +18,7 @@ function convertTypedArray(src, type) {

let ggwave = null

if (enabledForSession(window.PARAMS?.timestampWatermarkAudio)) {
if (webrtcperf.enabledForSession(window.PARAMS?.timestampWatermarkAudio)) {
document.addEventListener('DOMContentLoaded', async () => {
try {
ggwave = await ggwave_factory()
Expand Down
30 changes: 15 additions & 15 deletions scripts/e2e-video-stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ const applyVideoTimestampWatermarkFn = () => {
ctx.font = `${fontSize}px Noto Mono`
ctx.textAlign = 'center'
const textHeight = Math.round(fontSize * 1.2)
const participantNameIndex = parseInt(participantName.split('-')[1]) || 0

const transformer = new TransformStream({
async transform(videoFrame, controller) {
const text = String(Date.now())
const text = `${participantNameIndex}-${Date.now()}`
const timestamp = videoFrame.timestamp

const bitmap = await createImageBitmap(videoFrame)
Expand All @@ -42,14 +43,13 @@ const applyVideoTimestampWatermarkFn = () => {

ctx.fillStyle = 'black'
ctx.fillRect(0, 0, width, textHeight)
ctx.fillRect(0, height - textHeight, width, height)

ctx.beginPath()
for (let d = 0; d < 20; d += 4) {
ctx.moveTo(0, textHeight + d)
ctx.lineTo(width, textHeight + d)
ctx.moveTo(0, height - textHeight - d)
ctx.lineTo(width, height - textHeight - d)
for (let d = 0; d < 50; d += 10) {
//ctx.moveTo(0, textHeight * 2 + d)
//ctx.lineTo(width, textHeight * 2 + d)
//ctx.moveTo(0, height - d)
//ctx.lineTo(width, height - d)
ctx.moveTo(d, 0)
ctx.lineTo(d, height)
ctx.moveTo(width - d, 0)
Expand All @@ -60,7 +60,6 @@ const applyVideoTimestampWatermarkFn = () => {

ctx.fillStyle = 'white'
ctx.fillText(text, width / 2, fontSize)
ctx.fillText(participantName, width / 2, height - 6)

const newBitmap = await createImageBitmap(canvas)
const newFrame = new VideoFrame(newBitmap, { timestamp })
Expand Down Expand Up @@ -183,7 +182,7 @@ async function loadTesseract() {
)
await worker.setParameters({
tessedit_pageseg_mode: Tesseract.PSM.SINGLE_LINE,
tessedit_char_whitelist: '0123456789',
tessedit_char_whitelist: '0123456789-',
})
scheduler.addWorker(worker)
log('Creating Tesseract worker done')
Expand Down Expand Up @@ -229,25 +228,26 @@ window.recognizeVideoTimestampWatermark = async (
) {
lastTimestamp = timestamp
const now = Date.now()
const fontHeight = Math.ceil(codedHeight / 18) + 6
const fontSize = Math.round(codedHeight / 18)
const textHeight = Math.round(fontSize * 1.2)
canvas.width = codedWidth
canvas.height = fontHeight
canvas.height = textHeight
const bitmap = await createImageBitmap(
videoFrame,
0,
0,
codedWidth,
fontHeight,
textHeight,
)
ctx.drawImage(bitmap, 0, 0, codedWidth, fontHeight)
ctx.drawImage(bitmap, 0, 0, codedWidth, textHeight)
bitmap.close()

scheduler
.addJob('recognize', canvas)
.then(({ data }) => {
const cleanText = data.text.trim()
if (cleanText && data.confidence > 70) {
const recognizedTimestamp = parseInt(cleanText)
if (cleanText && data.confidence > 50) {
const recognizedTimestamp = parseInt(cleanText.split('-')[1])
const delay = now - recognizedTimestamp
if (isFinite(delay) && delay > 0 && delay < 30000) {
log(
Expand Down
6 changes: 3 additions & 3 deletions scripts/get-user-media.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* global webrtcperf, log, sleep, applyAudioTimestampWatermark, applyVideoTimestampWatermark, enabledForSession */
/* global webrtcperf, log, sleep, applyAudioTimestampWatermark, applyVideoTimestampWatermark */

const applyOverride = (constraints, override) => {
if (override) {
Expand Down Expand Up @@ -170,11 +170,11 @@ if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
log(`collectMediaTracks error:`, err)
}

if (enabledForSession(window.PARAMS?.timestampWatermarkAudio)) {
if (webrtcperf.enabledForSession(window.PARAMS?.timestampWatermarkAudio)) {
mediaStream = applyAudioTimestampWatermark(mediaStream)
}

if (enabledForSession(window.PARAMS?.timestampWatermarkVideo)) {
if (webrtcperf.enabledForSession(window.PARAMS?.timestampWatermarkVideo)) {
mediaStream = applyVideoTimestampWatermark(mediaStream)
}

Expand Down
4 changes: 2 additions & 2 deletions scripts/page-stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ window.collectHttpResourcesStats = () => {
if (typeof window.PerformanceObserver === 'function') {
// Stop ServiceWorkers.
/* navigator.serviceWorker.addEventListener('controllerchange', () => {
unregisterServiceWorkers()
webrtcperf.unregisterServiceWorkers()
})
unregisterServiceWorkers() */
webrtcperf.unregisterServiceWorkers() */

// https://nicj.net/resourcetiming-in-practice/
const processEntries = entries => {
Expand Down
Loading

0 comments on commit 8c9e0fe

Please sign in to comment.