summaryrefslogtreecommitdiff
path: root/app/client/live/player.js
blob: 3fd33e8b2dbb30693d59570619b29e842dc06508 (plain)
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
import { store } from '../store'
import Whammy from './whammy'
import types from '../types'
import * as pix2wav from '../audio/pix2wav'

let fps = 0, last_frame
let recording = false, saving = false, synthesizing = false
let videoWriter

export function startSynthesizing(){
  synthesizing = true
}
export function stopSynthesizing(){
  synthesizing = false
}

export function startRecording(){
  videoWriter = new Whammy.Video(10)
  recording = true
  store.dispatch({
    type: types.player.start_recording,
  })
}

export function stopRecording(){
  if (!recording) return
  recording = false
  store.dispatch({
    type: types.player.saving_video,
  })
  videoWriter.compile(false, function(blob){
    // console.log(blob)
    store.dispatch({
      type: types.player.save_video,
      blob: blob,
    })
  })
}

export function saveFrame(){
  saving = true
}

export function onFrame (data) {
  const blob = new Blob([data.frame], { type: 'image/jpg' })
  const url = URL.createObjectURL(blob)
  const img = new Image ()
  let canvas = document.querySelector('.player canvas')
  if (! canvas) return console.error('no canvas for frame')
  img.onload = () => {
    img.onload = null
    last_frame = data.meta
    URL.revokeObjectURL(url)
    const ctx = canvas.getContext('2d-lodpi')
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
    if (synthesizing) {
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
      pix2wav.play({ imageData })
    }
    if (recording) {
      console.log('record frame')
      videoWriter.add(canvas)
      store.dispatch({
        type: types.player.add_record_frame,
      })
    }
    if (saving) {
      saving = false
      canvas.toBlob(blob => {
        store.dispatch({
          type: types.player.save_frame,
          blob: blob,
        })
      })
    }
    fps += 1
  }
  img.src = url
}

let previousValue, currentValue
function handleChange() {
  let previousValue = currentValue
  currentValue = store.getState().live.playing

  if (previousValue !== currentValue) {
    if (currentValue) {
      startWatchingFPS()
    } else {
      stopWatchingFPS()
    }
  }
}

let fpsInterval;

function startWatchingFPS(){
  clearInterval(fpsInterval)
  fpsInterval = setInterval(() => {
    store.dispatch({
      type: types.player.set_fps,
      fps: fps,
    })
    store.dispatch({
      type: types.player.current_frame,
      meta: last_frame,
    })
    fps = 0
  }, 1000)
}
function stopWatchingFPS(){
  clearInterval(fpsInterval)
}