/
session-recorder.js
246 lines (218 loc) · 6.66 KB
/
session-recorder.js
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
var watch = require('mutant/watch')
var computed = require('mutant/computed')
var Struct = require('mutant/struct')
var Value = require('mutant/value')
var resolve = require('mutant/resolve')
var join = require('path').join
var strftime = require('strftime')
var recordToDisk = require('lib/record-to-disk')
var mkdirp = require('mkdirp')
var each = require('async-each')
var getBaseName = require('path').basename
var getDirName = require('path').dirname
var getExt = require('path').extname
module.exports = SessionRecorder
function SessionRecorder (context, active) {
var obs = Struct({
recording: Value(false)
})
obs.recordPosition = Value(null)
obs.input = context.audio.createGain() // context.audio.createMediaStreamDestination()
obs.recordingPath = Value(null)
// constant signal to ensure file has no gaps
Silence(context.audio).connect(obs.input)
var recordingsPath = join(resolve(context.cwd), '~recordings')
mkdirp(recordingsPath, { fs: context.fs })
var isRecording = computed([obs.recording, active], (a, b) => a || b)
var storing = computed(obs.recording, a => a)
var currentRecordingPath = null
var clips = []
var releases = []
watch(isRecording, refreshRecording)
watch(storing, function (value) {
if (currentRecordingPath) {
obs.recordingPath.set(null)
moveClipsToTimeline(currentRecordingPath)
currentRecordingPath = null
}
if (value) {
currentRecordingPath = join(recordingsPath, strftime('%F %H%M%S'))
mkdirp(currentRecordingPath, { fs: context.fs }, function () {
context.project.recordingEntries.refresh()
obs.recordingPath.set(currentRecordingPath)
})
}
})
obs.cleanUpOldClips = function (maxTime, cb) {
context.fs.readdir(recordingsPath, function (err, fileNames) {
if (err) return cb && cb(err)
var paths = fileNames.filter(x => getExt(x) === '.json').map(name => join(recordingsPath, name))
each(paths, function (path, next) {
context.fs.readFile(path, 'utf8', function (err, result) {
if (err) return next(err)
result = JSON.parse(result)
result.path = path
next(null, result)
})
}, function (err, files) {
if (err) return cb && cb(err)
var toDelete = []
var collectedDuation = 0
files.sort((a, b) => b.recordedAt - a.recordedAt)
for (var i = 0; i < files.length; i++) {
if (collectedDuation > maxTime || files[i].duration < 5) {
toDelete.push(files[i])
}
collectedDuation += files[i].duration
}
each(toDelete, function (file, next) {
console.log('removing old preroll', file.path)
var base = getDirName(file.path)
context.fs.unlink(file.path + '.time')
context.fs.unlink(file.path, function (err) {
if (err) next(err)
each(file.segments, function (segment, next) {
context.fs.unlink(join(base, segment.src), next)
}, next)
})
}, cb)
})
})
}
obs.stop = function (cb) {
if (isRecording()) {
if (storing()) {
moveClipsToTimeline(currentRecordingPath, cb)
} else {
stopRecording(cb)
}
} else {
setImmediate(cb)
}
}
obs.context = context
return obs
function moveClipsToTimeline (path, cb) {
moveClips(path, function (err, fileNames) {
if (err) throw err
var data = {
node: 'recording',
timeline: {
node: 'timeline',
primary: getClips(fileNames)
}
}
context.fs.writeFile(join(path, 'index.json'), JSON.stringify(data), cb)
})
}
function refreshRecording () {
stopRecording()
if (isRecording()) {
var path = join(recordingsPath, strftime('%F %H%M%S') + '.json')
clips.push(path)
obs.recordPosition.set(0)
releases.push(
recordToDisk(path, obs.input, onTick),
writeTimeCodeToDisk(context, path + '.time')
)
}
}
function onTick (pos) {
obs.recordPosition.set(pos)
}
function moveClips (basePath, cb) {
stopRecording(function () {
var lists = clips.slice()
clips.length = 0
each(lists, function (path, next) {
var fileName = getBaseName(path)
var newPath = join(basePath, fileName)
moveList(context.fs, path, basePath, function (err) {
if (err) return cb(err)
context.fs.rename(path + '.time', newPath + '.time', function (discardError) {
next(null, fileName)
})
})
}, cb)
// restart recording process
refreshRecording()
})
}
function stopRecording (cb) {
each(releases.slice(), (fn, next) => fn(next), cb)
obs.recordPosition.set(null)
releases.length = 0
}
}
function getClips (fileNames) {
var last = fileNames[fileNames.length - 1]
return fileNames.map(function (fileName) {
if (fileName === last) {
return {
node: 'timeline/clip',
src: './' + fileName
}
} else {
return {
flags: ['preroll'],
node: 'timeline/clip',
src: './' + fileName
}
}
})
}
function Silence (audioContext) {
var buffer = audioContext.createBuffer(2, 2, audioContext.sampleRate)
var player = audioContext.createBufferSource()
player.buffer = buffer
player.loop = true
player.start()
return player
}
function writeTimeCodeToDisk (context, filePath) {
// time stamps
var output = context.fs.createWriteStream(filePath)
var startAt = context.audio.currentTime
var timeOffset = -0.012
var releaseSchedule = context.scheduler.onSchedule(function (data) {
var from = Math.floor(data.from * 2) / 2
var to = Math.floor(data.to * 2) / 2
var hasCue = to - from
if (hasCue) {
var time = context.scheduler.getTimeAt(to) - startAt
output.write(floatBuffer(time + timeOffset))
}
})
return function (cb) {
releaseSchedule()
if (cb) {
output.on('finish', cb)
}
output.end()
}
}
function floatBuffer (value) {
var buffer = new Buffer(4)
buffer.writeFloatLE(value, 0)
return buffer
}
function moveList (fs, path, to, cb) {
var basePath = getDirName(path)
var file = getBaseName(path)
var newPath = join(to, file)
fs.readFile(path, 'utf8', function (err, result) {
if (err) return cb(err)
var data = JSON.parse(result)
var files = data.segments.map(function (segment) {
return segment.src
})
fs.rename(path, newPath, function (err) {
if (err) return cb(err)
each(files, function (file, next) {
var oldPath = join(basePath, file)
var newPath = join(to, file)
fs.rename(oldPath, newPath, next)
}, cb)
})
})
}