From c2f5593be00a224ea60beba6ba29fb82242979ff Mon Sep 17 00:00:00 2001 From: ThibG Date: Fri, 10 Jul 2020 13:57:05 +0200 Subject: [PATCH] Audio player visualization improvements (#14281) * Fix audio player ticks position * Split visualizer code into own file to comply with license * Change top-left corner of visualizer always showing peaks, clean up code --- .../mastodon/features/audio/index.js | 161 ++---------------- .../mastodon/features/audio/visualizer.js | 136 +++++++++++++++ 2 files changed, 148 insertions(+), 149 deletions(-) create mode 100644 app/javascript/mastodon/features/audio/visualizer.js diff --git a/app/javascript/mastodon/features/audio/index.js b/app/javascript/mastodon/features/audio/index.js index 6ab835bd6e..a494892576 100644 --- a/app/javascript/mastodon/features/audio/index.js +++ b/app/javascript/mastodon/features/audio/index.js @@ -7,11 +7,7 @@ import classNames from 'classnames'; import { throttle } from 'lodash'; import { getPointerPosition, fileNameFromURL } from 'mastodon/features/video'; import { debounce } from 'lodash'; - -const hex2rgba = (hex, alpha = 1) => { - const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16)); - return `rgba(${r}, ${g}, ${b}, ${alpha})`; -}; +import Visualizer from './visualizer'; const messages = defineMessages({ play: { id: 'video.play', defaultMessage: 'Play' }, @@ -21,9 +17,6 @@ const messages = defineMessages({ download: { id: 'video.download', defaultMessage: 'Download file' }, }); -// Some parts of the canvas rendering code in this file have been adopted from -// https://codepen.io/alexdevp/full/RNELPV by Alex Permyakov - const TICK_SIZE = 10; const PADDING = 180; @@ -57,6 +50,11 @@ class Audio extends React.PureComponent { dragging: false, }; + constructor (props) { + super(props); + this.visualizer = new Visualizer(TICK_SIZE); + } + setPlayerRef = c => { this.player = c; @@ -95,9 +93,7 @@ class Audio extends React.PureComponent { setCanvasRef = c => { this.canvas = c; - if (c) { - this.canvasContext = c.getContext('2d'); - } + this.visualizer.setCanvas(c); } componentDidMount () { @@ -265,17 +261,12 @@ class Audio extends React.PureComponent { _initAudioContext () { const context = new AudioContext(); - const analyser = context.createAnalyser(); const source = context.createMediaElementSource(this.audio); - analyser.smoothingTimeConstant = 0.6; - analyser.fftSize = 2048; - - source.connect(analyser); + this.visualizer.setAudioContext(context, source); source.connect(context.destination); this.audioContext = context; - this.analyser = analyser; } handleDownload = () => { @@ -308,20 +299,12 @@ class Audio extends React.PureComponent { }); } - _clear () { - this.canvasContext.clearRect(0, 0, this.state.width, this.state.height); + _clear() { + this.visualizer.clear(this.state.width, this.state.height); } - _draw () { - this.canvasContext.save(); - - const ticks = this._getTicks(360 * this._getScaleCoefficient(), TICK_SIZE); - - ticks.forEach(tick => { - this._drawTick(tick.x1, tick.y1, tick.x2, tick.y2); - }); - - this.canvasContext.restore(); + _draw() { + this.visualizer.draw(this._getCX(), this._getCY(), this._getAccentColor(), this._getRadius(), this._getScaleCoefficient()); } _getRadius () { @@ -332,126 +315,6 @@ class Audio extends React.PureComponent { return (this.state.height || this.props.height) / 982; } - _getTicks (count, size, animationParams = [0, 90]) { - const radius = this._getRadius(); - const ticks = this._getTickPoints(count); - const lesser = 200; - const m = []; - const bufferLength = this.analyser ? this.analyser.frequencyBinCount : 0; - const frequencyData = new Uint8Array(bufferLength); - const allScales = []; - const scaleCoefficient = this._getScaleCoefficient(); - - if (this.analyser) { - this.analyser.getByteFrequencyData(frequencyData); - } - - ticks.forEach((tick, i) => { - const coef = 1 - i / (ticks.length * 2.5); - - let delta = ((frequencyData[i] || 0) - lesser * coef) * scaleCoefficient; - - if (delta < 0) { - delta = 0; - } - - let k; - - if (animationParams[0] <= tick.angle && tick.angle <= animationParams[1]) { - k = radius / (radius - this._getSize(tick.angle, animationParams[0], animationParams[1]) - delta); - } else { - k = radius / (radius - (size + delta)); - } - - const x1 = tick.x * (radius - size); - const y1 = tick.y * (radius - size); - const x2 = x1 * k; - const y2 = y1 * k; - - m.push({ x1, y1, x2, y2 }); - - if (i < 20) { - let scale = delta / (200 * scaleCoefficient); - scale = scale < 1 ? 1 : scale; - allScales.push(scale); - } - }); - - const scale = allScales.reduce((pv, cv) => pv + cv, 0) / allScales.length; - - return m.map(({ x1, y1, x2, y2 }) => ({ - x1: x1, - y1: y1, - x2: x2 * scale, - y2: y2 * scale, - })); - } - - _getSize (angle, l, r) { - const scaleCoefficient = this._getScaleCoefficient(); - const maxTickSize = TICK_SIZE * 9 * scaleCoefficient; - const m = (r - l) / 2; - const x = (angle - l); - - let h; - - if (x === m) { - return maxTickSize; - } - - const d = Math.abs(m - x); - const v = 40 * Math.sqrt(1 / d); - - if (v > maxTickSize) { - h = maxTickSize; - } else { - h = Math.max(TICK_SIZE, v); - } - - return h; - } - - _getTickPoints (count) { - const PI = 360; - const coords = []; - const step = PI / count; - - let rad; - - for(let deg = 0; deg < PI; deg += step) { - rad = deg * Math.PI / (PI / 2); - coords.push({ x: Math.cos(rad), y: -Math.sin(rad), angle: deg }); - } - - return coords; - } - - _drawTick (x1, y1, x2, y2) { - const cx = this._getCX(); - const cy = this._getCY(); - - const dx1 = Math.ceil(cx + x1); - const dy1 = Math.ceil(cy + y1); - const dx2 = Math.ceil(cx + x2); - const dy2 = Math.ceil(cy + y2); - - const gradient = this.canvasContext.createLinearGradient(dx1, dy1, dx2, dy2); - - const mainColor = this._getAccentColor(); - const lastColor = hex2rgba(mainColor, 0); - - gradient.addColorStop(0, mainColor); - gradient.addColorStop(0.6, mainColor); - gradient.addColorStop(1, lastColor); - - this.canvasContext.beginPath(); - this.canvasContext.strokeStyle = gradient; - this.canvasContext.lineWidth = 2; - this.canvasContext.moveTo(dx1, dy1); - this.canvasContext.lineTo(dx2, dy2); - this.canvasContext.stroke(); - } - _getCX() { return Math.floor(this.state.width / 2); } diff --git a/app/javascript/mastodon/features/audio/visualizer.js b/app/javascript/mastodon/features/audio/visualizer.js new file mode 100644 index 0000000000..77d5b5a65c --- /dev/null +++ b/app/javascript/mastodon/features/audio/visualizer.js @@ -0,0 +1,136 @@ +/* +Copyright (c) 2020 by Alex Permyakov (https://codepen.io/alexdevp/pen/RNELPV) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +const hex2rgba = (hex, alpha = 1) => { + const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16)); + return `rgba(${r}, ${g}, ${b}, ${alpha})`; +}; + +export default class Visualizer { + + constructor (tickSize) { + this.tickSize = tickSize; + } + + setCanvas(canvas) { + this.canvas = canvas; + if (canvas) { + this.context = canvas.getContext('2d'); + } + } + + setAudioContext(context, source) { + const analyser = context.createAnalyser(); + + analyser.smoothingTimeConstant = 0.6; + analyser.fftSize = 2048; + + source.connect(analyser); + + this.analyser = analyser; + } + + getTickPoints (count) { + const coords = []; + + for(let i = 0; i < count; i++) { + const rad = Math.PI * 2 * i / count; + coords.push({ x: Math.cos(rad), y: -Math.sin(rad) }); + } + + return coords; + } + + drawTick (cx, cy, mainColor, x1, y1, x2, y2) { + const dx1 = Math.ceil(cx + x1); + const dy1 = Math.ceil(cy + y1); + const dx2 = Math.ceil(cx + x2); + const dy2 = Math.ceil(cy + y2); + + const gradient = this.context.createLinearGradient(dx1, dy1, dx2, dy2); + + const lastColor = hex2rgba(mainColor, 0); + + gradient.addColorStop(0, mainColor); + gradient.addColorStop(0.6, mainColor); + gradient.addColorStop(1, lastColor); + + this.context.beginPath(); + this.context.strokeStyle = gradient; + this.context.lineWidth = 2; + this.context.moveTo(dx1, dy1); + this.context.lineTo(dx2, dy2); + this.context.stroke(); + } + + getTicks (count, size, radius, scaleCoefficient) { + const ticks = this.getTickPoints(count); + const lesser = 200; + const m = []; + const bufferLength = this.analyser ? this.analyser.frequencyBinCount : 0; + const frequencyData = new Uint8Array(bufferLength); + const allScales = []; + + if (this.analyser) { + this.analyser.getByteFrequencyData(frequencyData); + } + + ticks.forEach((tick, i) => { + const coef = 1 - i / (ticks.length * 2.5); + + let delta = ((frequencyData[i] || 0) - lesser * coef) * scaleCoefficient; + + if (delta < 0) { + delta = 0; + } + + const k = radius / (radius - (size + delta)); + + const x1 = tick.x * (radius - size); + const y1 = tick.y * (radius - size); + const x2 = x1 * k; + const y2 = y1 * k; + + m.push({ x1, y1, x2, y2 }); + + if (i < 20) { + let scale = delta / (200 * scaleCoefficient); + scale = scale < 1 ? 1 : scale; + allScales.push(scale); + } + }); + + const scale = allScales.reduce((pv, cv) => pv + cv, 0) / allScales.length; + + return m.map(({ x1, y1, x2, y2 }) => ({ + x1: x1, + y1: y1, + x2: x2 * scale, + y2: y2 * scale, + })); + } + + clear (width, height) { + this.context.clearRect(0, 0, width, height); + } + + draw (cx, cy, color, radius, coefficient) { + this.context.save(); + + const ticks = this.getTicks(parseInt(360 * coefficient), this.tickSize, radius, coefficient); + + ticks.forEach(tick => { + this.drawTick(cx, cy, color, tick.x1, tick.y1, tick.x2, tick.y2); + }); + + this.context.restore(); + } + +}