From 0c0ccdb16b8767d54f060a9b16e73f48f3bd48bb Mon Sep 17 00:00:00 2001 From: Frank Zalkow Date: Wed, 4 Nov 2026 17:34:48 +0100 Subject: [PATCH 01/45] Fix CCR template defects Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25a0ca09-56e2-41d3-9692-fe2b939d8071 --- src/P808Template/CCR_template.html | 10 +++++----- tests/test_master_script.py | 32 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/P808Template/CCR_template.html b/src/P808Template/CCR_template.html index 9ce1b3c..73353a1 100644 --- a/src/P808Template/CCR_template.html +++ b/src/P808Template/CCR_template.html @@ -195,9 +195,9 @@ howManyHITsAnswered =0; if (hit_num != null ){ howManyHITsAnswered= Number(hit_num); - if (howManyHITsAnswered >= config['allowedMaxHITsInProject']){ - disableTheHIT(Hide_HIT_REASON.MAX_ACHIVED); - } + } + if (howManyHITsAnswered >= config['allowedMaxHITsInProject']){ + disableTheHIT(Hide_HIT_REASON.MAX_ACHIVED); } if ((qual_passed!==null) && (qual_passed=="false")){ disableTheHIT(Hide_HIT_REASON.QUALIFICATON); @@ -1958,7 +1958,7 @@ $('#trainingTabs').append(ccr_nav_tab.f(i+1,'','')); $('#nav-tabContent').append(ccr_tab.f(i+1, urlA, urlB,'', signA, signB)); } - $('#av-tabContent').append(input_template.f(i+1, urls[i].processed, order)); + $('#nav-tabContent').append(input_template.f(i+1, urls[i].processed, order)); } trainingStimulusPlayed = new Array(urls.length).fill(0); @@ -2127,7 +2127,7 @@

in-ear headphones Over-the-ear headphones - loudspeaker + loudspeaker built-in speakers diff --git a/tests/test_master_script.py b/tests/test_master_script.py index 5516d7b..b09a599 100644 --- a/tests/test_master_script.py +++ b/tests/test_master_script.py @@ -1,6 +1,9 @@ import asyncio import configparser import importlib +import json +import shutil +import subprocess from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, Mock @@ -10,6 +13,35 @@ from jinja2 import Template +@pytest.mark.parametrize(("counter", "limit", "blocked"), [ + (None, 0, True), (None, 20, False), ("19", 20, False), ("20", 20, True), +]) +def test_ccr_zero_limit_blocks_fresh_browsers(counter, limit, blocked): + """ + Apply the native participation limit even before a counter has been stored. + + :param counter: Stored completion count, or no prior browser record. + :param limit: Configured maximum number of tasks. + :param blocked: Whether the native task must be disabled. + :return: None. + """ + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is required to execute template JavaScript.") + path = Path(__file__).resolve().parents[1] / "src" / "P808Template" / "CCR_template.html" + html = path.read_text(encoding="utf-8") + body = html.split("\t\thit_num = readCookie(", 1)[1].split("\t\tif ((qual_passed", 1)[0] + script = ( + f"const config={{cookieName:'fixture',allowedMaxHITsInProject:{limit}}};" + f"const readCookie=()=>{json.dumps(counter)};" + "const Hide_HIT_REASON={MAX_ACHIVED:'maximum'};let disabled=false;" + "const disableTheHIT=()=>{disabled=true;};" + "hit_num = readCookie(" + body + "\nconsole.log(JSON.stringify(disabled));" + ) + result = subprocess.run([node, "-e", script], capture_output=True, text=True, check=True, timeout=10) + assert json.loads(result.stdout) is blocked + + class _FakeAzureClipStorage: def __init__(self, config, alg): """ From caf553ef31f38e1514ac8c57a5e4580fca007caf Mon Sep 17 00:00:00 2001 From: Frank Zalkow Date: Wed, 4 Nov 2026 17:34:49 +0100 Subject: [PATCH 02/45] Sync CCR clip highlight with playback Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25a0ca09-56e2-41d3-9692-fe2b939d8071 --- src/P808Template/CCR_template.html | 109 ++++++++++++++++++++++++++--- tests/test_master_script.py | 57 +++++++++++++++ 2 files changed, 156 insertions(+), 10 deletions(-) diff --git a/src/P808Template/CCR_template.html b/src/P808Template/CCR_template.html index 73353a1..d4afe5a 100644 --- a/src/P808Template/CCR_template.html +++ b/src/P808Template/CCR_template.html @@ -1032,6 +1032,103 @@ $("#baudio_l_c_"+id).text(ct.toString().toMMSS()); } +/** + * Keep the current clip highlight and elapsed-time display synchronized with actual playback. + * + * @param {DoubleClip} clip - The pair of audio elements being played. + */ +function configureDoubleClipPlaybackUiForClip(clip){ + var counter = document.getElementById("baudio_l_c_" + clip.id); + var title = document.getElementById("title_" + clip.id); + var gapStartedAt = null; + var gapCompleted = false; + var secondClipStarted = false; + var animationFrame = null; + + function clearHighlight(){ + title.classList.remove("play_clip1", "play_clip2"); + } + + function updateCounter(){ + var currentTime = clip.ae1.currentTime; + if (secondClipStarted){ + currentTime = clip.ae1.duration + clip.pause_time_sec + clip.ae2.currentTime; + }else if (gapStartedAt !== null){ + var gapElapsed = Math.min((performance.now() - gapStartedAt) / 1000, clip.pause_time_sec); + currentTime = clip.ae1.duration + gapElapsed; + if (gapElapsed >= clip.pause_time_sec){ + gapStartedAt = null; + gapCompleted = true; + } + }else if (gapCompleted){ + currentTime = clip.ae1.duration + clip.pause_time_sec; + } + if (Number.isFinite(currentTime)) counter.textContent = currentTime.toString().toMMSS(); + } + + function stopAnimation(){ + if (animationFrame !== null){ + cancelAnimationFrame(animationFrame); + animationFrame = null; + } + } + + function updateWhilePlaying(){ + animationFrame = null; + if (!clip.in_between && clip.ae1.paused && clip.ae2.paused && gapStartedAt !== null){ + var gapElapsed = (performance.now() - gapStartedAt) / 1000; + gapCompleted = gapElapsed >= clip.pause_time_sec; + gapStartedAt = null; + } + updateCounter(); + if (!clip.paused || clip.in_between || gapStartedAt !== null){ + animationFrame = requestAnimationFrame(updateWhilePlaying); + }else{ + clearHighlight(); + } + } + + function scheduleUpdate(){ + if (animationFrame === null) animationFrame = requestAnimationFrame(updateWhilePlaying); + } + + clip.ae1.addEventListener("playing", function(){ + gapStartedAt = null; + gapCompleted = false; + secondClipStarted = false; + clearHighlight(); + title.classList.add("play_clip1"); + scheduleUpdate(); + }); + clip.ae2.addEventListener("playing", function(){ + gapStartedAt = null; + gapCompleted = true; + secondClipStarted = true; + clearHighlight(); + title.classList.add("play_clip2"); + scheduleUpdate(); + }); + clip.ae1.addEventListener("ended", function(){ + gapStartedAt = performance.now(); + gapCompleted = false; + clearHighlight(); + updateCounter(); + scheduleUpdate(); + }); + clip.ae2.addEventListener("ended", function(){ + secondClipStarted = true; + gapStartedAt = null; + gapCompleted = true; + clearHighlight(); + updateCounter(); + stopAnimation(); + }); + [clip.ae1, clip.ae2].forEach(function(media){ + media.addEventListener("pause", scheduleUpdate); + media.addEventListener("waiting", clearHighlight); + }); +} + /* callback function, double clips. it schedule playing the second clip after 1 sec. when the first clup ends. */ @@ -1060,11 +1157,8 @@ this.ae2.play(); this.in_between = false; this.time_out_id = null; - $("#title_"+this.id).removeClass("play_clip1"); - $("#title_"+this.id).addClass("play_clip2"); - - } + /* DoubleClip component, including two audio elements */ @@ -1132,21 +1226,15 @@ let ae2_ct = this.ae2.currentTime; if (ae1_ct < this.ae1.duration){ this.ae1.play(); - $("#title_"+this.id).removeClass("play_clip2"); - $("#title_"+this.id).addClass("play_clip1"); return; } if (ae1_ct == this.ae1.duration && ae2_ct < this.ae2.duration){ this.ae2.play(); - $("#title_"+this.id).removeClass("play_clip1"); - $("#title_"+this.id).addClass("play_clip2"); return; } //so start again this.ae1.play(); this.ae2.currentTime= 0; - $("#title_"+this.id).removeClass("play_clip2"); - $("#title_"+this.id).addClass("play_clip1"); } } @@ -1237,6 +1325,7 @@ audioElement1.addEventListener("ended",doubleClipIsended.bind(double_clip),false); audioElement2.addEventListener("ended",doubleClipIsended.bind(double_clip),false); + configureDoubleClipPlaybackUiForClip(double_clip); }); diff --git a/tests/test_master_script.py b/tests/test_master_script.py index b09a599..feda310 100644 --- a/tests/test_master_script.py +++ b/tests/test_master_script.py @@ -13,6 +13,63 @@ from jinja2 import Template +def test_ccr_clip_highlights_follow_media_playback_events(): + """ + Verify clip highlighting changes on actual playback events and clears at completion. + + :return: None. + """ + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is required to execute template JavaScript.") + path = Path(__file__).resolve().parents[1] / "src" / "P808Template" / "CCR_template.html" + html = path.read_text(encoding="utf-8") + start = html.index("function configureDoubleClipPlaybackUiForClip(clip){") + end = html.index("function doubleClipIsended()", start) + function = html[start:end].rstrip() + script = function + """ +String.prototype.toMMSS = function () { return this.toString(); }; +let nextFrame = 0; +const media = () => ({ + paused: true, currentTime: 0, duration: 3, listeners: {}, + addEventListener(name, callback) { this.listeners[name] = callback; }, + trigger(name) { + this.paused = name !== "playing"; + this.listeners[name](); + } +}); +const first = media(); +const second = media(); +const classes = new Set(); +const clip = { + id: "q_1", ae1: first, ae2: second, pause_time_sec: 1, in_between: false, + get paused() { return first.paused && second.paused && !this.in_between; } +}; +const title = {classList: { + add(name) { classes.add(name); }, + remove(...names) { names.forEach(name => classes.delete(name)); } +}}; +const counter = {textContent: ""}; +global.document = {getElementById(id) { return id.startsWith("title_") ? title : counter; }}; +global.performance = {now: () => 1000}; +global.requestAnimationFrame = () => ++nextFrame; +global.cancelAnimationFrame = () => {}; +""" + function + """ +configureDoubleClipPlaybackUiForClip(clip); +first.trigger("playing"); +if (!classes.has("play_clip1")) throw new Error("first clip highlight missing"); +first.trigger("ended"); +if (classes.size) throw new Error("highlight remained during the gap"); +second.currentTime = second.duration; +second.trigger("playing"); +if (!classes.has("play_clip2")) throw new Error("second clip highlight missing"); +second.trigger("ended"); +if (classes.size) throw new Error("highlight remained after playback"); +if (counter.textContent !== "7") throw new Error("final counter is " + counter.textContent); +""" + subprocess.run([node, "-e", script], capture_output=True, text=True, check=True, timeout=10) + + @pytest.mark.parametrize(("counter", "limit", "blocked"), [ (None, 0, True), (None, 20, False), ("19", 20, False), ("20", 20, True), ]) From ab98eb4d810eafa5fd75d9af6174b110528339e8 Mon Sep 17 00:00:00 2001 From: Frank Zalkow Date: Wed, 4 Nov 2026 17:34:49 +0100 Subject: [PATCH 03/45] Scroll CCR navigation to section starts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25a0ca09-56e2-41d3-9692-fe2b939d8071 --- src/P808Template/CCR_template.html | 32 +++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/P808Template/CCR_template.html b/src/P808Template/CCR_template.html index d4afe5a..ab1f145 100644 --- a/src/P808Template/CCR_template.html +++ b/src/P808Template/CCR_template.html @@ -651,7 +651,7 @@ createCookie(config['cookieName']+"_setup","un_important",config['showSetupEveryMinutes']); unlockAfterSetup(); alert("Your setup looks good. You can continue with the task."); - var setupNext = document.getElementById("training"); + var setupNext = document.getElementById("details_instruction") || document.getElementById("training"); if (setupNext) setupNext.scrollIntoView({ behavior: "smooth", block: "start" }); return; } @@ -843,10 +843,8 @@ id=id+2; $('#trainingTabs li:nth-child('+id+') a').tab('show'); }else{ - // last next is called - setTimeout(function (){ - window.location.hash="navNextPre"; - }, 50); + var ratingSection = document.getElementById("rating_section"); + if (ratingSection) ratingSection.scrollIntoView({ behavior: "smooth", block: "start" }); } } @@ -1443,10 +1441,26 @@ // device check runs an objective acoustic echo test (see startDeviceCheck) document.getElementById("start_headset_check").onclick = function() { startDeviceCheck(); }; wireDeviceCheckOptions(); - $('#prev-training').on('click', function(){ showPreviousQuestionInTrainingSection(); }); - $('#next-training').on('click', function(){ showNextQuestionInTrainingSection(); }); - $('#prev-rating').on('click', function(){ showPreviousQuestionInRatingSection(); }); - $('#next-rating').on('click', function(){ showNextQuestionInRatingSection(); }); + $('#prev-training').on('click', function(event){ event.preventDefault(); showPreviousQuestionInTrainingSection(); }); + $('#next-training').on('click', function(event){ event.preventDefault(); showNextQuestionInTrainingSection(); }); + $('#prev-rating').on('click', function(event){ event.preventDefault(); showPreviousQuestionInRatingSection(); }); + $('#next-rating').on('click', function(event){ event.preventDefault(); showNextQuestionInRatingSection(); }); + $("#trainingTabs, #nav-tab-ul").on("shown.bs.tab", "a", function(){ + var sectionId = this.closest("#trainingTabs") ? "training" : "rating_section"; + scrollToActiveQuestion(sectionId); + }); +} + +/** + * Keep the selected item visible without relying on the navigation link's hash target. + * + * @param {string} sectionId - The practice or rating section containing the selected item. + */ +function scrollToActiveQuestion(sectionId){ + var prefix = sectionId == "training" ? "t" : "q"; + var target = document.getElementById(prefix+"-progress-label"); + if (!target) target = document.querySelector("#"+sectionId+" .tab-pane.active .baudio_table"); + if (target) target.scrollIntoView({ behavior: "smooth", block: "start" }); } From 84ccc8ea1cf00843f26927c464b8e5e25496c8a7 Mon Sep 17 00:00:00 2001 From: Frank Zalkow Date: Wed, 4 Nov 2026 17:34:50 +0100 Subject: [PATCH 04/45] Accept any eligible listening device Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25a0ca09-56e2-41d3-9692-fe2b939d8071 --- docs/prep_dcr_ccr.md | 7 ++- src/P808Template/ACR_template.html | 33 ++++++------- src/P808Template/CCR_template.html | 37 ++++++-------- src/P808Template/DCR_template.html | 33 ++++++------- src/P808Template/P808_multi.html | 33 ++++++------- .../P835_personalized_template3.html | 33 ++++++------- src/P808Template/P835_template.html | 33 ++++++------- tests/test_master_script.py | 49 +++++++++++++++++++ 8 files changed, 145 insertions(+), 113 deletions(-) diff --git a/docs/prep_dcr_ccr.md b/docs/prep_dcr_ccr.md index 8974d31..b25334c 100644 --- a/docs/prep_dcr_ccr.md +++ b/docs/prep_dcr_ccr.md @@ -57,4 +57,9 @@ column named `training_clips` and URLs to corresponding reference clips in colum * `YOUR_PROJECT_NAME_publish_batch.csv`: List of dynamic content to be used during publishing batch in AMT. * `YOUR_PROJECT_NAME_ccr_result_parser.cfg`: Customized configuration file to be used by `result_parser.py` script -Now, you are ready for running the test on [Prolific](running_test_prolific.md) or [Amazon Mechanical Turk](running_test_mturk.md). \ No newline at end of file +Now, you are ready for running the test on [Prolific](running_test_prolific.md) or [Amazon Mechanical Turk](running_test_mturk.md). + +## CCR listening-device availability + +Eligibility passes when any selected device meets `required_playback_device` (`headset`, +`loudspeaker` or `any`). Acoustic checks verify the active device and audibility. diff --git a/src/P808Template/ACR_template.html b/src/P808Template/ACR_template.html index b8287d6..30e36ba 100644 --- a/src/P808Template/ACR_template.html +++ b/src/P808Template/ACR_template.html @@ -416,9 +416,7 @@ // (headset -> in-ear/over-ear, loudspeaker -> ex-ls/ib-ls). When the study accepts // "any" device, any single valid selection is fine. The objective device check // later verifies the actual active device. - device_check = (config.requiredPlaybackDevice === "any") - ? (selfReportedDeviceClass() !== null) - : (selfReportedDeviceClass() === config.requiredPlaybackDevice); + device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice); hearing_self_report_check=$("input[name='8_hearing']:checked").val() == "normal" count_correct_ht=0; if (checkQualNumCorrect($("input[name='num1']").val().trim(),config.qualification.num1)) @@ -1180,22 +1178,21 @@ dB) and the inferred device are stored in the hidden fields for offline checking. */ - /* - Return the self-reported device class from the 4_ld checkboxes: - "headset", "loudspeaker", or null when it is ambiguous/not answered. - */ - function selfReportedDeviceClass() { - var headsetVals = ["in-ear", "over-ear"]; - var speakerVals = ["ex-ls", "ib-ls"]; - var isHeadset = false, isSpeaker = false; - $("input[name='4_ld']:checked").each(function () { - var v = $(this).val(); - if (headsetVals.indexOf(v) >= 0) isHeadset = true; - if (speakerVals.indexOf(v) >= 0) isSpeaker = true; + /** + * Check whether any reported device is eligible, without rejecting mixed device ownership. + * + * @param {string} requiredDevice Required class: "headset", "loudspeaker", or "any". + * @returns {boolean} Whether at least one reported device meets the requirement. + */ + function selfReportedDeviceAvailable(requiredDevice) { + var deviceValues = { + headset: ["in-ear", "over-ear"], + loudspeaker: ["ex-ls", "ib-ls"], + any: ["in-ear", "over-ear", "ex-ls", "ib-ls"] + }[requiredDevice] || []; + return $("input[name='4_ld']:checked").toArray().some(function (input) { + return deviceValues.includes(input.value); }); - if (isHeadset && !isSpeaker) return "headset"; - if (isSpeaker && !isHeadset) return "loudspeaker"; - return null; } function sleepMs(ms) { diff --git a/src/P808Template/CCR_template.html b/src/P808Template/CCR_template.html index ab1f145..31ce2d4 100644 --- a/src/P808Template/CCR_template.html +++ b/src/P808Template/CCR_template.html @@ -361,13 +361,7 @@ }).get(); m_tongue_check = mother_tongues.some(function (v) { return config.qualification.mother_tongue.includes(v); }); - // check listening-device self-report against the required playback device - // (headset -> in-ear/over-ear, loudspeaker -> ex-ls/ib-ls). When the study accepts - // "any" device, any single valid selection is fine. The objective device check - // later verifies the actual active device. - device_check = (config.requiredPlaybackDevice === "any") - ? (selfReportedDeviceClass() !== null) - : (selfReportedDeviceClass() === config.requiredPlaybackDevice); + device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice); hearing_self_report_check=$("input[name='8_hearing']:checked").val() == "normal" count_correct_ht=0; if (checkQualNumCorrect($("input[name='num1']").val().trim(),config.qualification.num1)) @@ -1478,22 +1472,21 @@ dB) and the inferred device are stored in the hidden fields for offline checking. */ - /* - Return the self-reported device class from the 4_ld checkboxes: - "headset", "loudspeaker", or null when it is ambiguous/not answered. - */ - function selfReportedDeviceClass() { - var headsetVals = ["in-ear", "over-ear"]; - var speakerVals = ["ex-ls", "ib-ls"]; - var isHeadset = false, isSpeaker = false; - $("input[name='4_ld']:checked").each(function () { - var v = $(this).val(); - if (headsetVals.indexOf(v) >= 0) isHeadset = true; - if (speakerVals.indexOf(v) >= 0) isSpeaker = true; + /** + * Check whether any reported device is eligible, without rejecting mixed device ownership. + * + * @param {string} requiredDevice Required class: "headset", "loudspeaker", or "any". + * @returns {boolean} Whether at least one reported device meets the requirement. + */ + function selfReportedDeviceAvailable(requiredDevice) { + var deviceValues = { + headset: ["in-ear", "over-ear"], + loudspeaker: ["ex-ls", "ib-ls"], + any: ["in-ear", "over-ear", "ex-ls", "ib-ls"] + }[requiredDevice] || []; + return $("input[name='4_ld']:checked").toArray().some(function (input) { + return deviceValues.includes(input.value); }); - if (isHeadset && !isSpeaker) return "headset"; - if (isSpeaker && !isHeadset) return "loudspeaker"; - return null; } function sleepMs(ms) { diff --git a/src/P808Template/DCR_template.html b/src/P808Template/DCR_template.html index 9f9d257..4ba2278 100644 --- a/src/P808Template/DCR_template.html +++ b/src/P808Template/DCR_template.html @@ -357,9 +357,7 @@ // (headset -> in-ear/over-ear, loudspeaker -> ex-ls/ib-ls). When the study accepts // "any" device, any single valid selection is fine. The objective device check // later verifies the actual active device. - device_check = (config.requiredPlaybackDevice === "any") - ? (selfReportedDeviceClass() !== null) - : (selfReportedDeviceClass() === config.requiredPlaybackDevice); + device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice); hearing_self_report_check=$("input[name='8_hearing']:checked").val() == "normal" count_correct_ht=0; if (checkQualNumCorrect($("input[name='num1']").val().trim(),config.qualification.num1)) @@ -1114,22 +1112,21 @@ dB) and the inferred device are stored in the hidden fields for offline checking. */ - /* - Return the self-reported device class from the 4_ld checkboxes: - "headset", "loudspeaker", or null when it is ambiguous/not answered. - */ - function selfReportedDeviceClass() { - var headsetVals = ["in-ear", "over-ear"]; - var speakerVals = ["ex-ls", "ib-ls"]; - var isHeadset = false, isSpeaker = false; - $("input[name='4_ld']:checked").each(function () { - var v = $(this).val(); - if (headsetVals.indexOf(v) >= 0) isHeadset = true; - if (speakerVals.indexOf(v) >= 0) isSpeaker = true; + /** + * Check whether any reported device is eligible, without rejecting mixed device ownership. + * + * @param {string} requiredDevice Required class: "headset", "loudspeaker", or "any". + * @returns {boolean} Whether at least one reported device meets the requirement. + */ + function selfReportedDeviceAvailable(requiredDevice) { + var deviceValues = { + headset: ["in-ear", "over-ear"], + loudspeaker: ["ex-ls", "ib-ls"], + any: ["in-ear", "over-ear", "ex-ls", "ib-ls"] + }[requiredDevice] || []; + return $("input[name='4_ld']:checked").toArray().some(function (input) { + return deviceValues.includes(input.value); }); - if (isHeadset && !isSpeaker) return "headset"; - if (isSpeaker && !isHeadset) return "loudspeaker"; - return null; } function sleepMs(ms) { diff --git a/src/P808Template/P808_multi.html b/src/P808Template/P808_multi.html index 3f49455..c12b04c 100644 --- a/src/P808Template/P808_multi.html +++ b/src/P808Template/P808_multi.html @@ -703,9 +703,7 @@ // (headset -> in-ear/over-ear, loudspeaker -> ex-ls/ib-ls). When the study accepts // "any" device, any single valid selection is fine. The objective device check // later verifies the actual active device. - device_check = (config.requiredPlaybackDevice === "any") - ? (selfReportedDeviceClass() !== null) - : (selfReportedDeviceClass() === config.requiredPlaybackDevice); + device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice); hearing_self_report_check = $("input[name='8_hearing']:checked").val() == "normal" count_correct_ht = 0; @@ -1831,22 +1829,21 @@ dB) and the inferred device are stored in the hidden fields for offline checking. */ - /* - Return the self-reported device class from the 4_ld checkboxes: - "headset", "loudspeaker", or null when it is ambiguous/not answered. - */ - function selfReportedDeviceClass() { - var headsetVals = ["in-ear", "over-ear"]; - var speakerVals = ["ex-ls", "ib-ls"]; - var isHeadset = false, isSpeaker = false; - $("input[name='4_ld']:checked").each(function () { - var v = $(this).val(); - if (headsetVals.indexOf(v) >= 0) isHeadset = true; - if (speakerVals.indexOf(v) >= 0) isSpeaker = true; + /** + * Check whether any reported device is eligible, without rejecting mixed device ownership. + * + * @param {string} requiredDevice Required class: "headset", "loudspeaker", or "any". + * @returns {boolean} Whether at least one reported device meets the requirement. + */ + function selfReportedDeviceAvailable(requiredDevice) { + var deviceValues = { + headset: ["in-ear", "over-ear"], + loudspeaker: ["ex-ls", "ib-ls"], + any: ["in-ear", "over-ear", "ex-ls", "ib-ls"] + }[requiredDevice] || []; + return $("input[name='4_ld']:checked").toArray().some(function (input) { + return deviceValues.includes(input.value); }); - if (isHeadset && !isSpeaker) return "headset"; - if (isSpeaker && !isHeadset) return "loudspeaker"; - return null; } function sleepMs(ms) { diff --git a/src/P808Template/P835_personalized_template3.html b/src/P808Template/P835_personalized_template3.html index c3d79eb..fa7898c 100644 --- a/src/P808Template/P835_personalized_template3.html +++ b/src/P808Template/P835_personalized_template3.html @@ -537,9 +537,7 @@ // (headset -> in-ear/over-ear, loudspeaker -> ex-ls/ib-ls). When the study accepts // "any" device, any single valid selection is fine. The objective device check // later verifies the actual active device. - device_check = (config.requiredPlaybackDevice === "any") - ? (selfReportedDeviceClass() !== null) - : (selfReportedDeviceClass() === config.requiredPlaybackDevice); + device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice); hearing_self_report_check = $("input[name='8_hearing']:checked").val() == "normal" count_correct_ht = 0; if (checkQualNumCorrect($("input[name='num1']").val().trim(), config.qualification.num1)) @@ -1464,22 +1462,21 @@ dB) and the inferred device are stored in the hidden fields for offline checking. */ - /* - Return the self-reported device class from the 4_ld checkboxes: - "headset", "loudspeaker", or null when it is ambiguous/not answered. - */ - function selfReportedDeviceClass() { - var headsetVals = ["in-ear", "over-ear"]; - var speakerVals = ["ex-ls", "ib-ls"]; - var isHeadset = false, isSpeaker = false; - $("input[name='4_ld']:checked").each(function () { - var v = $(this).val(); - if (headsetVals.indexOf(v) >= 0) isHeadset = true; - if (speakerVals.indexOf(v) >= 0) isSpeaker = true; + /** + * Check whether any reported device is eligible, without rejecting mixed device ownership. + * + * @param {string} requiredDevice Required class: "headset", "loudspeaker", or "any". + * @returns {boolean} Whether at least one reported device meets the requirement. + */ + function selfReportedDeviceAvailable(requiredDevice) { + var deviceValues = { + headset: ["in-ear", "over-ear"], + loudspeaker: ["ex-ls", "ib-ls"], + any: ["in-ear", "over-ear", "ex-ls", "ib-ls"] + }[requiredDevice] || []; + return $("input[name='4_ld']:checked").toArray().some(function (input) { + return deviceValues.includes(input.value); }); - if (isHeadset && !isSpeaker) return "headset"; - if (isSpeaker && !isHeadset) return "loudspeaker"; - return null; } function sleepMs(ms) { diff --git a/src/P808Template/P835_template.html b/src/P808Template/P835_template.html index 8c38d68..2cd78e6 100644 --- a/src/P808Template/P835_template.html +++ b/src/P808Template/P835_template.html @@ -428,9 +428,7 @@ // (headset -> in-ear/over-ear, loudspeaker -> ex-ls/ib-ls). When the study accepts // "any" device, any single valid selection is fine. The objective device check // later verifies the actual active device. - device_check = (config.requiredPlaybackDevice === "any") - ? (selfReportedDeviceClass() !== null) - : (selfReportedDeviceClass() === config.requiredPlaybackDevice); + device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice); hearing_self_report_check=$("input[name='8_hearing']:checked").val() == "normal" count_correct_ht=0; if (checkQualNumCorrect($("input[name='num1']").val().trim(),config.qualification.num1)) @@ -1175,22 +1173,21 @@ dB) and the inferred device are stored in the hidden fields for offline checking. */ - /* - Return the self-reported device class from the 4_ld checkboxes: - "headset", "loudspeaker", or null when it is ambiguous/not answered. - */ - function selfReportedDeviceClass() { - var headsetVals = ["in-ear", "over-ear"]; - var speakerVals = ["ex-ls", "ib-ls"]; - var isHeadset = false, isSpeaker = false; - $("input[name='4_ld']:checked").each(function () { - var v = $(this).val(); - if (headsetVals.indexOf(v) >= 0) isHeadset = true; - if (speakerVals.indexOf(v) >= 0) isSpeaker = true; + /** + * Check whether any reported device is eligible, without rejecting mixed device ownership. + * + * @param {string} requiredDevice Required class: "headset", "loudspeaker", or "any". + * @returns {boolean} Whether at least one reported device meets the requirement. + */ + function selfReportedDeviceAvailable(requiredDevice) { + var deviceValues = { + headset: ["in-ear", "over-ear"], + loudspeaker: ["ex-ls", "ib-ls"], + any: ["in-ear", "over-ear", "ex-ls", "ib-ls"] + }[requiredDevice] || []; + return $("input[name='4_ld']:checked").toArray().some(function (input) { + return deviceValues.includes(input.value); }); - if (isHeadset && !isSpeaker) return "headset"; - if (isSpeaker && !isHeadset) return "loudspeaker"; - return null; } function sleepMs(ms) { diff --git a/tests/test_master_script.py b/tests/test_master_script.py index feda310..0fc0f08 100644 --- a/tests/test_master_script.py +++ b/tests/test_master_script.py @@ -2,6 +2,7 @@ import configparser import importlib import json +import re import shutil import subprocess from pathlib import Path @@ -13,6 +14,54 @@ from jinja2 import Template +@pytest.mark.parametrize( + ("template", "required_device", "selected_devices", "expected"), + [ + (template, "headset", ["in-ear", "ib-ls"], True) + for template in [ + "ACR_template.html", "CCR_template.html", "DCR_template.html", "P808_multi.html", + "P835_template.html", "P835_personalized_template3.html", + ] + ] + [ + ("CCR_template.html", "headset", ["over-ear", "ex-ls"], True), + ("CCR_template.html", "headset", ["in-ear", "over-ear"], True), + ("CCR_template.html", "headset", ["ib-ls", "ex-ls"], False), + ("CCR_template.html", "headset", [], False), + ("CCR_template.html", "loudspeaker", ["in-ear", "ex-ls"], True), + ("CCR_template.html", "loudspeaker", ["over-ear"], False), + ("CCR_template.html", "any", ["in-ear", "ex-ls"], True), + ("CCR_template.html", "any", [], False), + ], +) +def test_templates_accept_any_eligible_reported_device(template, required_device, selected_devices, expected): + """ + Execute the listening-device availability check without confusing ownership with active playback. + + :param template: Template file containing the availability check. + :param required_device: Configured playback-device class. + :param selected_devices: Device types reported as available by the participant. + :param expected: Whether the available devices meet the configured requirement. + :return: None. + """ + node = shutil.which("node") + if node is None: + pytest.skip("Node.js is required to execute template JavaScript.") + path = Path(__file__).resolve().parents[1] / "src" / "P808Template" / template + html = path.read_text(encoding="utf-8") + function = re.search( + r"function selfReportedDeviceAvailable\(requiredDevice\) \{.*?\n\s*\}(?=\n)", html, re.DOTALL, + ).group(0) + script = ( + "const selected = " + json.dumps(selected_devices) + ";" + "const $ = selector => ({toArray: () => selected.map(value => ({value}))});" + + function + + "\nconsole.log(JSON.stringify(selfReportedDeviceAvailable(" + json.dumps(required_device) + ")));" + ) + result = subprocess.run([node, "-e", script], capture_output=True, text=True, check=True, timeout=10) + assert json.loads(result.stdout) is expected + assert "device_check = selfReportedDeviceAvailable(config.requiredPlaybackDevice);" in html + + def test_ccr_clip_highlights_follow_media_playback_events(): """ Verify clip highlighting changes on actual playback events and clears at completion. From 8f0b68f58e2f68ec62a1b20f4e0217e0730cde28 Mon Sep 17 00:00:00 2001 From: Frank Zalkow Date: Wed, 4 Nov 2026 17:34:51 +0100 Subject: [PATCH 05/45] Clarify device-check retry instructions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 25a0ca09-56e2-41d3-9692-fe2b939d8071 --- src/P808Template/ACR_template.html | 4 ++-- src/P808Template/CCR_template.html | 4 ++-- src/P808Template/DCR_template.html | 4 ++-- src/P808Template/P808_multi.html | 4 ++-- src/P808Template/P835_personalized_template3.html | 4 ++-- src/P808Template/P835_template.html | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/P808Template/ACR_template.html b/src/P808Template/ACR_template.html index 30e36ba..04d6b67 100644 --- a/src/P808Template/ACR_template.html +++ b/src/P808Template/ACR_template.html @@ -2165,8 +2165,8 @@