All files / src/core renderer.ts

90.91% Statements 130/143
83.93% Branches 47/56
87.5% Functions 28/32
92.65% Lines 126/136

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 3783x   3x     3x   3x 3x   29x     29x     29x 29x 29x 29x 29x       17x 17x     29x 4x     29x 1x 1x       17x       17x 17x   17x 17x 17x                     8x 2x     6x             5x 36x     5x       5x                           5x 5x 5x   5x 56x   56x 56x     56x     5x 3x     2x                                             3x 3x 35x                         5x 5x 5x   5x   5x 56x     56x   56x 56x       56x 1x     56x                                 5x   5x           5x   5x                     5x 5x             5x                       61x 61x       61x 61x 41x 41x   41x                   41x 40x   40x                       41x 41x   41x     41x                             64x 1x   63x 63x 63x 63x       81x 81x 81x   63x 44x   19x 19x       81x 3x   78x       18x 17x 15x         17x                 17x 17x   17x 17x 17x 17x           1x             3x 3x 1x   3x       20x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x       18x 18x 18x          
import * as WaveSurfer from "wavesurfer.js"
import CanvasEntry from "wavesurfer.js/src/drawer.canvasentry.js"
import MultiCanvas from "wavesurfer.js/src/drawer.multicanvas.js"
 
import { Channel, PlayerParams } from "../types"
import { waveStyles } from "./styles"
 
const util: WaveSurfer.WaveSurferUtil = (WaveSurfer as any).default.util
export class Drawer extends MultiCanvas {
  container: HTMLElement
  channels: Channel[] = []
  params: Required<PlayerParams>
  cursorCanvas?: HTMLCanvasElement
  currentPosition = 0
 
  constructor(container: HTMLElement, params: WaveSurfer.WaveSurferParams) {
    super(container, params)
    this.container = container
    this.params = params as Required<PlayerParams>
    window.addEventListener("resize", this.handleWindowResize)
    this.hasProgressCanvas = true
  }
 
  public init() {
    super.createWrapper()
    this.createElements()
  }
 
  private handleWindowResize = () => {
    this.fireEvent("redraw")
  }
 
  public destroy = () => {
    window.removeEventListener("resize", this.handleWindowResize)
    this.destroyCursor()
  }
 
  public createElements() {
    this.progressWave = this.wrapper.appendChild(
      this.style(document.createElement("wave"), waveStyles)
    ) as HTMLDivElement
 
    this.addCanvas()
    this.createCursor()
 
    this.wrapper.style.backgroundColor = this.params.backgroundColor
    this.container.style.position = "relative"
    this.container.style.backgroundColor = "transparent"
  }
 
  public drawBars(
    peaks: number[][],
    channelIndex: number,
    start?: number,
    end?: number
  ) {
    // if drawBars was called within ws.empty we don't pass a start and
    // don't want anything to happen
    if (start === undefined || end === undefined) {
      return
    }
 
    return util.frame(this.prepareForDraw.bind(this))(peaks, start, end)
  }
 
  private preparePeaks(peaks: ReadonlyArray<ReadonlyArray<number>>) {
    // In case the peaks are generated by Wavesurfer, every second entry is a negative number,
    // because it is intended to describe a wave going up and down.
    // We just filter out the negative numbers in that case.
    const hasMinVals = peaks.some((channelPeaks: readonly number[]) =>
      channelPeaks.some(val => val < 0)
    )
 
    Iif (hasMinVals) {
      return peaks.map(peaks => (peaks as number[]).filter((_, i) => !(i % 2)))
    }
 
    return peaks
  }
 
  private prepareBars({
    start,
    end,
    step,
    peaks,
  }: {
    start: number
    end: number
    step: number
    peaks: ReadonlyArray<ReadonlyArray<number>>
  }) {
    const scale = peaks[0].length / this.width
    const bars: number[][] = [...new Array(peaks.length)].map(() => [])
    let i = start
 
    for (i; i < end; i += step) {
      const peakIndex = Math.floor(i * scale)
 
      const heights = peaks.map(p =>
        this.getPeakAverageValue(p, peakIndex, step)
      )
 
      heights.forEach((h, i) => bars[i].push(h))
    }
 
    if (this.params.normalize) {
      return this.normalizeBars(bars)
    }
 
    return bars
  }
 
  private prepareProgressBars({
    start,
    end,
    step,
  }: {
    start: number
    end: number
    step: number
  }) {
    let i = start
    const heights = []
 
    for (i; i < end; i += step) {
      heights.push(0.5)
    }
    return [heights]
  }
 
  private normalizeBars(bars: ReadonlyArray<ReadonlyArray<number>>) {
    // We normalize each channel on its own
    return bars.map(barsForChannel => {
      const max = util.max(barsForChannel)
      return barsForChannel.map(val => (this.params.barHeight * val) / max)
    })
  }
 
  private renderBars({
    bars,
    start,
    step,
  }: {
    bars: number[][]
    start: number
    step: number
  }) {
    const height = this.params.height * this.params.pixelRatio
    const halfH = height / 2
    const barWidth = Math.floor(this.params.barWidth * this.params.pixelRatio)
 
    let channels = Array.from(bars.keys())
 
    bars[0].forEach((_, index) => {
      const i = start + index * step
      // If we have multiple channels, we have to make sure we draw the heighest bar first,
      // so that it does not cover the smaller ones
      channels = channels.sort((a, b) => bars[b][index] - bars[a][index])
 
      channels.forEach(channelIndex => {
        let h = Math.round(bars[channelIndex][index] * halfH)
 
        // in case of silences, allow the user to specify that we
        // always draw *something* (normally a 1px high bar)
        if (h === 0 && this.params.barMinHeight) {
          h = this.params.barMinHeight
        }
 
        this.fillRect(
          channelIndex,
          i + this.halfPixel,
          this.height - h * 2,
          barWidth + this.halfPixel,
          h * 2,
          0
        )
      })
    })
  }
 
  public prepareForDraw(
    peaks: ReadonlyArray<ReadonlyArray<number>>,
    start: number,
    end: number
  ): void {
    const bar = this.params.barWidth * this.params.pixelRatio
    const gap =
      this.params.barGap === null || this.params.barGap === undefined
        ? Math.max(this.params.pixelRatio, Math.floor(bar / 2))
        : Math.max(
            this.params.pixelRatio,
            this.params.barGap * this.params.pixelRatio
          )
    const step = Math.floor(bar + gap)
 
    Iif (!peaks || !peaks.length) {
      // Peaks are not available and Wavesurfer is currently generating them.
      // We display bars going half way.
      const bars = this.prepareProgressBars({
        start,
        end,
        step,
      })
 
      this.renderBars({ bars, start, step })
    } else {
      const processedPeaks = this.preparePeaks(peaks)
      const bars = this.prepareBars({
        start,
        end,
        step,
        peaks: processedPeaks,
      })
 
      this.renderBars({ bars, start, step })
    }
  }
 
  public fillRect(
    channelIndex: number,
    x: number,
    y: number,
    width: number,
    height: number,
    radius?: number
  ) {
    const startCanvas = Math.floor(x / this.maxCanvasWidth)
    const endCanvas = Math.min(
      Math.ceil((x + width) / this.maxCanvasWidth) + 1,
      this.canvases.length
    )
    let i = startCanvas
    for (i; i < endCanvas; i++) {
      const entry = this.canvases[i]
      const leftOffset = i * this.maxCanvasWidth
 
      const intersection = {
        x1: Math.max(x, i * this.maxCanvasWidth),
        y1: y,
        x2: Math.min(
          x + width,
          i * this.maxCanvasWidth + entry.wave!.width // eslint-disable-line @typescript-eslint/no-non-null-assertion
        ),
        y2: y + height,
      }
 
      if (intersection.x1 < intersection.x2) {
        this.setFillStyles(entry, channelIndex)
 
        entry.fillRects(
          intersection.x1 - leftOffset,
          intersection.y1,
          intersection.x2 - intersection.x1,
          intersection.y2 - intersection.y1,
          radius
        )
      }
    }
  }
 
  public setFillStyles(entry: CanvasEntry, channelIndex: number) {
    const channel = this.channels[channelIndex]
    const color = (channel && channel.color) || this.params.waveColor
    const progressColor =
      (channel && channel.progressColor) ||
      (channel && channel.color) ||
      this.params.progressColor
    entry.setFillStyles(color, progressColor)
  }
 
  /**
   * Get weighted arithmetic mean of peak values in radius surrounding the value at index
   * @param {array} peaks Source peak array
   * @param {number} index Index of the middle value
   * @param {number} radius Radius from the index
   * @returns {number} Arithemtic mean of values
   */
  public getPeakAverageValue(
    peaks: readonly number[],
    index: number,
    radius: number
  ) {
    if (index < 0) {
      return 0
    }
    let sum = 0
    let weightSum = 0
    for (
      let i = Math.max(0, index - radius);
      i <= Math.min(peaks.length - 1, index + radius);
      i++
    ) {
      const w = this.weightDistributionFunction(i - index, radius / 2)
      sum += w * peaks[i]
      weightSum += w
    }
    if (weightSum === 0) {
      return 0
    }
    const average = sum / weightSum
    return average
  }
 
  private weightDistributionFunction(x: number, deviation: number) {
    if (!deviation) {
      return 1
    }
    return Math.exp(-1 * Math.pow(x / deviation, 2))
  }
 
  public createCursor() {
    if (this.progressWave) {
      if (this.params.progressBackgroundColor) {
        this.style(this.progressWave, {
          backgroundColor: this.params.progressBackgroundColor,
        })
      }
 
      this.cursorCanvas = this.style(document.createElement("canvas"), {
        position: "absolute",
        top: "0",
        left: "0",
        height: "100%",
        width: "100%",
        zIndex: "5",
        pointerEvents: "none",
      }) as HTMLCanvasElement
      this.cursorCanvas.classList.add("twilio-player-cursor")
      this.container.appendChild(this.cursorCanvas)
 
      const ctx = this.cursorCanvas.getContext("2d")
      Eif (ctx) {
        ctx.imageSmoothingEnabled = false
        this.drawCursor(0)
      }
    }
  }
 
  public destroyCursor() {
    Iif (this.cursorCanvas) {
      this.cursorCanvas.parentNode?.removeChild(this.cursorCanvas)
      this.cursorCanvas = undefined
    }
  }
 
  public updateProgress(position: number) {
    position = Math.floor(position)
    if (this.progressWave) {
      this.style(this.progressWave, { width: position + "px" })
    }
    this.drawCursor(position)
  }
 
  public drawCursor(position: number) {
    if (this.cursorCanvas) {
      const ctx = this.cursorCanvas.getContext("2d")
      Eif (ctx && this.cursorCanvas) {
        ctx.imageSmoothingEnabled = false
        this.cursorCanvas.width = this.container.clientWidth
        this.cursorCanvas.height = this.container.clientHeight
        ctx.clearRect(0, 0, this.cursorCanvas.width, this.cursorCanvas.height)
        ctx.fillStyle = this.params.cursorColor
        ctx.beginPath()
        ctx.moveTo(position - 3 * this.params.cursorWidth + 0.5, -0.5)
        ctx.lineTo(position + 0.5, 8.5)
        ctx.lineTo(position + 0.5, this.cursorCanvas.height + 0.5)
        ctx.lineTo(
          position + this.params.cursorWidth + 0.5,
          this.cursorCanvas.height + 0.5
        )
        ctx.lineTo(position + this.params.cursorWidth + 0.5, 8.5)
        ctx.lineTo(position + 4 * this.params.cursorWidth + 0.5, -0.5)
        ctx.fill()
      }
    }
  }
}