Skip to content
Open
Show file tree
Hide file tree
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
142 changes: 135 additions & 7 deletions src-tauri/resources/media-audio.test.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Run with: node --test src-tauri/resources/media-audio.test.mjs
// media.js sections 5 and 6 (Linux): one sound stream. A small fake DOM; the
// media.js sections 5 and 6 (Linux): one sound stream. Section 7: alert sounds
// play from throwaway iframes (issue #120). A small fake DOM; the
// engine behaviour (streams per paused <audio> and per AudioContext) was
// measured in a real WebKitGTK 2.54 window.
import assert from 'node:assert/strict';
Expand All @@ -9,12 +10,15 @@ import { test } from 'node:test';

const source = readFileSync(new URL('./media.js', import.meta.url), 'utf8');

function harness() {
function harness({ top = false, copyPlay = 'resolve' } = {}) {
const logs = [];
const timers = [];
class Event { constructor(type) { this.type = type; this.stopped = false; } stopImmediatePropagation() { this.stopped = true; } }
class Element {
constructor(tag) { this.tagName = String(tag).toUpperCase(); this.attrs = {}; this.listeners = []; this.style = {}; }
constructor(tag) { this.tagName = String(tag).toUpperCase(); this.attrs = {}; this.listeners = []; this.style = {}; this.children = []; this.parentNode = null; }
appendChild(c) { this.children.push(c); c.parentNode = this; return c; }
removeChild(c) { this.children = this.children.filter(x => x !== c); c.parentNode = null; return c; }
getAttribute(n) { return n in this.attrs ? this.attrs[n] : null; }
setAttribute(n, v) { this.attrs[n] = String(v); if (n === 'src') this._src = String(v); }
removeAttribute(n) { delete this.attrs[n]; if (n === 'src') this._src = ''; }
addEventListener(type, fn, capture) { this.listeners.push({ type, fn, capture: !!capture }); }
Expand All @@ -38,7 +42,24 @@ function harness() {
pause() { this._paused = true; }
load() { engine.loads.push(this._src); if (!this._src) { engine.streams.delete(this); this.dispatchEvent(new Event('emptied')); } }
}
class HTMLAudioElement extends HTMLMediaElement { constructor() { super('audio'); } }
class HTMLAudioElement extends HTMLMediaElement { constructor() { super('audio'); this.loop = false; this.volume = 1; this.muted = false; } }
// `new Audio(url)`: like the engine's, it takes the URL without the src setter.
function Audio(url) { const a = new HTMLAudioElement(); if (url !== undefined) a._src = String(url); return a; }
Audio.prototype = HTMLAudioElement.prototype;
// An <audio> made by a hidden iframe's window: the copy section 7 plays.
// `end()` stands in for the sound finishing; `copyPlay: 'reject'` refuses it.
const copies = [];
class FrameAudio {
constructor(url) { this.url = url; this.listeners = {}; this.paused = true; copies.push(this); }
addEventListener(type, fn) { (this.listeners[type] ||= []).push(fn); }
play() {
if (copyPlay === 'reject') return Promise.reject(Object.assign(new Error('refused'), { name: 'NotAllowedError' }));
this.paused = false; return Promise.resolve();
}
pause() { this.paused = true; }
end(type = 'ended') { this.paused = true; (this.listeners[type] || []).forEach(fn => fn()); }
}
class HTMLIFrameElement extends Element { constructor() { super('iframe'); this.contentWindow = { Audio: FrameAudio }; } }
class HTMLVideoElement extends HTMLMediaElement {}
class HTMLImageElement extends Element { constructor() { super('img'); this._src = ''; } get src() { return this._src; } set src(v) { this._src = v; } }
let n = 0;
Expand All @@ -56,14 +77,17 @@ function harness() {
createGain() { return new GainNode(this); }
}
class GainNode { constructor(ctx) { if (!(ctx instanceof AudioContext) || contexts.indexOf(ctx) < 0) throw new TypeError('not an engine context'); this.context = ctx; } }
const window = { location: { origin: 'https://web.whatsapp.com' }, AudioContext, GainNode,
const window = { location: { origin: 'https://web.whatsapp.com' }, AudioContext, GainNode, Audio,
__TAURI__: { core: { invoke: (c, a) => { logs.push(a.msg); return Promise.resolve(); } } } };
runInNewContext(source, { window, document: { body: new Element('body'), createElement: () => new HTMLAudioElement() }, URL, Event, Element,
window.top = top ? window : {};
const body = new Element('body');
const document = { body, createElement: tag => (tag === 'iframe' ? new HTMLIFrameElement() : new HTMLAudioElement()) };
runInNewContext(source, { window, document, URL, Event, Element,
HTMLMediaElement, HTMLAudioElement, HTMLVideoElement, HTMLImageElement, MutationObserver: class { observe() {} disconnect() {} },
WeakSet, WeakMap, Map, Set, Object, String, Number, Array, Date, Promise, Proxy, Reflect, Error, TypeError, DOMException,
isFinite, setTimeout: fn => { timers.push(fn); return timers.length; }, clearTimeout: id => { timers[id - 1] = null; } });
const flush = () => { const t = timers.splice(0); t.forEach(f => f && f()); };
return { window, URL, logs, flush, engine, contexts, live, HTMLAudioElement };
return { window, URL, logs, flush, engine, contexts, live, HTMLAudioElement, body, copies };
}

test('a paused alert sound gives its stream back and replays from the page position', async () => {
Expand Down Expand Up @@ -162,3 +186,107 @@ test('every AudioContext without its own sample rate shares one engine context',
assert.equal(contexts.length, 3, 'a new one after that');
assert.ok(logs.includes('media: shared audio context installed'));
});

// --- 7. alert sounds play from throwaway iframes (issue #120) ---------------
const NOTIFICATION = 'https://static.whatsapp.net/rsrc.php/yW/r/BS_BUUXbKq5.mp3';
const frames = body => body.children.filter(c => c.getAttribute('data-whatrust') === 'alert-sound');
const watch = (el, types) => { const seen = []; types.forEach(t => el.addEventListener(t, () => seen.push(t))); return seen; };

test('the page\'s own alert element never gives its URL to the engine', () => {
const { window, engine, HTMLAudioElement } = harness({ top: true });
const viaConstructor = new window.Audio(NOTIFICATION); // how WhatsApp makes its alert sounds
const viaSetter = new HTMLAudioElement(); viaSetter.src = NOTIFICATION;
const viaAttribute = new HTMLAudioElement(); viaAttribute.setAttribute('src', 'data:audio/mpeg;base64,AAAA');
for (const el of [viaConstructor, viaSetter, viaAttribute]) {
assert.equal(el._src, '', 'the engine has nothing to load');
assert.equal(el.currentSrc, el.src, 'the page reads back its own URL');
}
assert.equal(viaConstructor.src, NOTIFICATION);
assert.ok(viaConstructor instanceof HTMLAudioElement);
assert.deepEqual(engine.loads, []);
});

test('an alert plays from a copy in a hidden iframe that is removed when it ends', async () => {
const { window, engine, body, copies } = harness({ top: true });
const a = new window.Audio(NOTIFICATION);
a.volume = 0.4;
const seen = watch(a, ['play', 'playing', 'ended']);
await a.play();
assert.equal(engine.streams.size, 0, 'the page element itself never plays');
assert.equal(copies.length, 1);
assert.equal(copies[0].url, NOTIFICATION);
assert.equal(copies[0].volume, 0.4, 'volume is carried over');
assert.equal(a.paused, false, 'the page sees its sound playing');
const [frame] = frames(body);
assert.ok(frame, 'the copy lives in an iframe');
assert.equal(frame.style.cssText, 'display:none');
assert.deepEqual(seen, ['play', 'playing']);
copies[0].end();
assert.equal(frames(body).length, 0, 'the iframe, and with it the media player, is gone');
assert.equal(a.paused, true);
assert.deepEqual(seen, ['play', 'playing', 'ended']);
});

test('a new alert restarts the sound and never leaves an iframe behind', async () => {
const { window, body, copies } = harness({ top: true });
const a = new window.Audio(NOTIFICATION);
await a.play();
await a.play(); // a second message before the first sound ended
assert.equal(frames(body).length, 1, 'only the newest copy remains');
assert.equal(copies[0].paused, true, 'the first copy was stopped');
const seen = watch(a, ['ended']);
copies[0].end(); // a late event from the stopped copy is ignored
assert.deepEqual(seen, []);
copies[1].end();
assert.equal(frames(body).length, 0);
assert.deepEqual(seen, ['ended']);
});

test('pause(), a load error and a new src remove the iframe too', async () => {
const { window, body, copies } = harness({ top: true });
const a = new window.Audio(NOTIFICATION);
a.loop = true; // a ringtone loops until WhatsApp pauses it
const seen = watch(a, ['pause', 'error']);
await a.play();
assert.equal(copies[0].loop, true);
a.pause();
assert.equal(frames(body).length, 0);
assert.equal(copies[0].paused, true);
await a.play();
copies[1].end('error');
assert.equal(frames(body).length, 0);
await a.play();
a.src = NOTIFICATION; // replacing the source stops what was sounding
assert.equal(frames(body).length, 0);
assert.deepEqual(seen, ['pause', 'error']);
});

test('voice messages (blob:) keep the engine playback', async () => {
const { URL, engine, body, copies, HTMLAudioElement } = harness({ top: true });
const voice = new HTMLAudioElement();
voice.src = URL.createObjectURL({ type: 'audio/ogg' });
assert.equal(voice._src, voice.src, 'the engine gets a blob URL');
await voice.play();
assert.equal(engine.streams.size, 1);
assert.equal(copies.length, 0);
assert.equal(frames(body).length, 0);
});

test('a refused copy falls back to the engine, so the sound is never lost', async () => {
const { window, engine, body, logs } = harness({ top: true, copyPlay: 'reject' });
const a = new window.Audio(NOTIFICATION);
await a.play();
assert.equal(a._src, NOTIFICATION, 'the engine now has the URL');
assert.equal(engine.streams.size, 1, 'and plays it');
assert.equal(frames(body).length, 0, 'the unused iframe is removed');
assert.ok(logs.some(m => /alert sound copy refused \(NotAllowedError\)/.test(m)));
});

test('inside an iframe nothing is held or copied', async () => {
const { window, engine, logs } = harness({ top: false });
const a = new window.Audio(NOTIFICATION);
assert.equal(a._src, NOTIFICATION);
await a.play();
assert.equal(engine.streams.size, 1);
assert.ok(logs.includes('media: alert sounds: not installed here'));
});
144 changes: 142 additions & 2 deletions src-tauri/resources/media.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Linux only (WebKitGTK): make attaching a video work, and keep WhatsApp's
// sounds to one audio stream (sections 5 and 6).
// Linux only (WebKitGTK): make attaching a video work, keep WhatsApp's sounds
// to one audio stream (sections 5 and 6), and keep its alert sounds from
// leaving a media player in the desktop's media controls (section 7).
//
// whatRust presents itself to WhatsApp Web as Chrome on Linux, so WhatsApp runs
// its Chromium code paths on WebKitGTK, where three engine behaviours differ.
Expand Down Expand Up @@ -485,4 +486,143 @@
} catch (e) {
note("shared audio context not installed: " + e);
}

// -- 7. alert sounds leave no media player behind (#120) -------------------
// WebKitGTK registers a page's audio as an MPRIS media player (GNOME's media
// controls) and removes it only when the element's document goes away. Worse,
// once anything has played, an <audio> that merely LOADS registers a player
// too, and every player then reports "Playing" for good. WhatsApp makes its
// alert sounds at startup (`new Audio(url)`: the new-message .mp3, the 40 ms
// send_message .m4a) and keeps them, so a stuck "Playing" entry appeared even
// when nothing sounded. Reproduced on the real web.whatsapp.com in a bare
// WebKitGTK 2.52 view; pausing, muting, clearing `src`, or turning off the
// MediaSession feature does not remove the player.
// So the page's own alert elements never load: they keep their URL, the engine
// never gets it. Each play() sounds from a copy in a hidden iframe that is
// removed when the copy ends, errors or is paused, which destroys its player.
// The page's element gets play, playing, ended, pause and error as before.
// Alerts are https:/data: <audio> in the top page; voice messages (blob:) and
// calls (srcObject) keep the engine's own playback. Runs after section 5, so
// its idle release never sees an alert element with media.
try {
var AP7 = HTMLMediaElement.prototype;
var src7 = Object.getOwnPropertyDescriptor(AP7, "src");
var currentSrc7 = Object.getOwnPropertyDescriptor(AP7, "currentSrc");
var paused7 = Object.getOwnPropertyDescriptor(AP7, "paused");
var NativeAudio = window.Audio;
if (window.top !== window || typeof NativeAudio !== "function" || !src7 || !src7.set || !paused7 || !paused7.get) {
note("alert sounds: not installed here");
} else {
var isAlertUrl = function (u) { return /^(https?|data):/i.test(String(u)); };
var held = new WeakMap(); // page alert element -> the URL the engine never got
var copies = new WeakMap(); // page alert element -> { frame, audio } now sounding
var play7 = AP7.play, pause7 = AP7.pause, setAttr7 = Element.prototype.setAttribute;
var hold = function (el, url) {
if (el instanceof HTMLAudioElement && isAlertUrl(url)) { held.set(el, String(url)); return true; }
held.delete(el);
return false;
};
var stopCopy = function (el) {
var c = copies.get(el);
if (!c) return;
copies.delete(el);
try { c.audio.pause(); } catch (e) {}
if (c.frame.parentNode) c.frame.parentNode.removeChild(c.frame);
};
// `new Audio(url)` hands the URL to the engine without our setter: take it.
var Audio7 = function Audio(url) {
if (!new.target) throw new TypeError("Constructor Audio requires 'new'");
var el = new NativeAudio();
if (url !== undefined) el.src = url;
return el;
};
Audio7.prototype = NativeAudio.prototype;
window.Audio = Audio7;
Object.defineProperty(AP7, "src", {
configurable: true, enumerable: src7.enumerable,
get: function () { return held.has(this) ? held.get(this) : src7.get.call(this); },
set: function (v) {
stopCopy(this);
if (hold(this, v)) return;
return src7.set.call(this, v);
},
});
if (currentSrc7 && currentSrc7.get) {
Object.defineProperty(AP7, "currentSrc", {
configurable: true, enumerable: currentSrc7.enumerable,
get: function () { return held.has(this) ? held.get(this) : currentSrc7.get.call(this); },
});
}
Object.defineProperty(AP7, "paused", {
configurable: true, enumerable: paused7.enumerable,
get: function () { var c = copies.get(this); return c ? c.audio.paused : paused7.get.call(this); },
});
Element.prototype.setAttribute = function (name, value) {
if (this instanceof HTMLMediaElement && String(name).toLowerCase() === "src") {
stopCopy(this);
if (hold(this, value)) return;
}
return setAttr7.call(this, name, value);
};
AP7.play = function () {
var el = this, url = held.get(el);
if (url === undefined) return play7.apply(this, arguments);
var frame = null, copy;
try {
frame = document.createElement("iframe");
setAttr7.call(frame, "data-whatrust", "alert-sound");
setAttr7.call(frame, "aria-hidden", "true");
frame.style.cssText = "display:none";
(document.body || document.documentElement).appendChild(frame);
copy = new frame.contentWindow.Audio(url);
} catch (e) {
if (frame && frame.parentNode) frame.parentNode.removeChild(frame);
return fallback(el, e);
}
stopCopy(el); // a new alert restarts the sound, like replaying one element
copies.set(el, { frame: frame, audio: copy });
copy.loop = el.loop;
copy.volume = el.volume;
copy.muted = el.muted;
var finish = function (type) {
return function () {
var c = copies.get(el);
if (!c || c.audio !== copy) return; // superseded by a newer play()
stopCopy(el);
el.dispatchEvent(new Event(type));
};
};
copy.addEventListener("ended", finish("ended"));
copy.addEventListener("error", finish("error"));
return copy.play().then(function () {
el.dispatchEvent(new Event("play"));
el.dispatchEvent(new Event("playing"));
}, function (err) {
stopCopy(el);
return fallback(el, err);
});
};
// The copy was refused (autoplay rules, say): give the element its URL and
// play it natively. The leftover player comes back for it, but the sound
// is never lost.
var fallback = function (el, err) {
var url = held.get(el);
held.delete(el);
note("alert sound copy refused (" + (err && err.name) + "), playing natively");
if (url !== undefined) src7.set.call(el, url);
return play7.call(el);
};
AP7.pause = function () {
if (copies.has(this)) {
stopCopy(this);
this.dispatchEvent(new Event("pause"));
return;
}
return pause7.apply(this, arguments);
};
note("alert sounds play from throwaway frames");
}
} catch (e) {
note("alert sounds not installed: " + e);
}
})();
Loading