The "setPlaybackQuality" API call is a no-op. It was removed in October 2019.
Hence the whole optimizeAmbient function is pointless. The ambient video can be muted in the "onReady" callback once.
The requestAnimationFrame function is also a no-op since it gets started before both objects are ready, then it throws an error and never executes again. Even if you fix that, ambient video stutters like crazy and never really plays, since it's overwhelmed with 60-240 seek calls per second. I've tried using regular "setInterval" at 1000ms and then only updating if both positions are too far apart, and it regularly makes the ambient video stutter. The best solution was not to do it at all.
function onYouTubeIframeAPIReady () {
const el = document.getElementById ( 'video' );
const videoId = el.dataset.ytId;
const ambilight = new YT.Player ( 'ambilight', {
videoId,
events: {
onReady: event => { event.target.mute (); }
}
});
const video = new YT.Player ( 'video', {
videoId,
events: {
onStateChange: event => {
if ( event.data == YT.PlayerState.PLAYING ) {
ambilight.seekTo ( event.target.getCurrentTime () );
ambilight.playVideo ();
} else if ( event.data == YT.PlayerState.PAUSED ) {
ambilight.pauseVideo ();
ambilight.seekTo ( event.target.getCurrentTime () );
}
}
}
});
}
It takes the videoId from the dataset of the "video" element.
e.g. <div id="video" data-yt-id="ASzOzrB-a9E"></div>