-
Notifications
You must be signed in to change notification settings - Fork 0
/
avalanche.ts
387 lines (351 loc) · 9.68 KB
/
avalanche.ts
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
378
379
380
381
382
383
384
385
386
387
/**
* (c) Chad Walker, Chris Kirmse
*/
import sem from 'semaphore-mutex';
import log from './log.js';
import ResourceIo from './resource_io.js';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// tslint:disable:no-var-requires
const avalancheNative = require('./Release/avalanche.node');
const Semaphore = sem.default;
let pendingStr = '';
const defaultLogAvalanche = (level: string, isLibav: boolean, str: string) => {
pendingStr += str;
if (!pendingStr.endsWith('\n')) {
return;
}
// remove newline
pendingStr = pendingStr.slice(0, -1);
if (isLibav) {
log.trace('libav:', pendingStr);
} else {
switch (level) {
case 'info':
log.info('avalanche:', pendingStr);
break;
case 'error':
// video errors can be caused by bad data, which is expected from some users;
// therefore this is a log info
log.info('avalanche:', pendingStr);
break;
default:
log.info('avalanche: unknown level', level, pendingStr);
break;
}
}
pendingStr = '';
};
type LogFn = (level: string, isLibav: boolean, str: string) => void;
const setLogFunc = (logFunc: LogFn) => {
avalancheNative.setLogFunc(logFunc);
};
const setDefaultLogFunc = () => {
setLogFunc(defaultLogAvalanche);
};
setDefaultLogFunc();
const activeVideoReaders = new Set<LockedVideoReader>();
type Token = number;
type Action = {
input: any[] | null;
output: any | null;
};
type Metadata = {
video_encoding_name: string;
audio_encoding_name: string;
container_start_time: number;
container_duration: number;
video_start_time: number;
video_duration: number;
video_width: number;
video_height: number;
frame_rate: number;
};
type ImageData = {
net_image_buffer: Buffer;
timestamp: number;
duration: number;
};
type VideoData = {
video_start_time: number;
video_duration: number;
count_video_packets: number;
count_key_frames: number;
};
type VolumeData = {
mean_volume: number;
max_volume: number;
};
type ProgressFn = (step: number, total: number) => void;
// we wrap the calls into video read here with our own javascript mutex
// which is implemented as a "fair" mutex, meaning all the calls get to the
// native code in the same order as they get here
//
// Important note: the wrapped_video_reader and c++ VideoReader implementetation
// only allow one high-level call at a time; that's why some locking/queuing
// is required.
class LockedVideoReader {
private _videoReader;
private _lock = new Semaphore(1);
private _latestAction: Action = {
input: null,
output: null,
};
constructor() {
this._videoReader = new avalancheNative.VideoReader();
}
async _startAction() {
const token = (await this._lock.acquire()) as Token;
activeVideoReaders.add(this);
return token;
}
_endAction(token: Token) {
activeVideoReaders.delete(this);
this._lock.release(token);
}
async init(input: string | typeof ResourceIo) {
const token = await this._startAction();
this._latestAction = {
input: ['init', input],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.init(input);
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
drain() {
this._videoReader.drain();
}
async destroy() {
const token = await this._startAction();
this._latestAction = {
input: ['destroy'],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.destroy();
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async verifyHasVideoStream() {
const token = await this._startAction();
this._latestAction = {
input: ['init'],
output: '<running>',
};
let retval;
try {
retval = this._videoReader.verifyHasVideoStream();
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async verifyHasAudioStream() {
const token = await this._startAction();
this._latestAction = {
input: ['init'],
output: '<running>',
};
let retval;
try {
retval = this._videoReader.verifyHasAudioStream();
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async getMetadata(): Promise<Metadata> {
const token = await this._startAction();
this._latestAction = {
input: ['get_metadata'],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.getMetadata();
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async getImageAtTimestamp(timestamp: number): Promise<ImageData> {
const token = await this._startAction();
this._latestAction = {
input: ['get_image_at_timestamp', timestamp],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.getImageAtTimestamp(timestamp);
this._latestAction.output = { ...retval };
if (this._latestAction.output.net_image_buffer) {
this._latestAction.output.net_image_buffer = `Buffer length ${this._latestAction.output.net_image_buffer.length}`;
}
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async extractClipReencode(
destUri: string,
startTime: number,
endTime: number,
progress: ProgressFn,
): Promise<VideoData> {
const token = await this._startAction();
this._latestAction = {
input: ['extract_clip_reencode', destUri, startTime, endTime],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.extractClipReencode(destUri, startTime, endTime, progress);
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async extractClipRemux(
destUri: string,
startTime: number,
endTime: number,
progress: ProgressFn,
): Promise<VideoData> {
const token = await this._startAction();
this._latestAction = {
input: ['extract_clip_remux', destUri, startTime, endTime],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.extractClipRemux(destUri, startTime, endTime, progress);
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async remux(destUri: string, progress: ProgressFn): Promise<VideoData> {
const token = await this._startAction();
this._latestAction = {
input: ['remux', destUri],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.remux(destUri, progress);
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async getClipVolumeData(startTime: number, endTime: number, progress: ProgressFn): Promise<VolumeData> {
const token = await this._startAction();
this._latestAction = {
input: ['get_clip_volume_data', startTime, endTime],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.getClipVolumeData(startTime, endTime, progress);
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
async getVolumeData(progress: ProgressFn): Promise<VolumeData> {
const token = await this._startAction();
this._latestAction = {
input: ['get_volume_data'],
output: '<running>',
};
let retval;
try {
retval = await this._videoReader.getVolumeData(progress);
this._latestAction.output = retval;
} catch (err) {
this._latestAction.output = 'exception';
throw err;
} finally {
this._endAction(token);
}
return retval;
}
getLatestAction() {
return this._latestAction;
}
getBlockedCount() {
return this._lock.getBlockedCount();
}
}
const createVideoReader = () => {
return new LockedVideoReader();
};
const drainActiveVideoReaders = () => {
for (const videoReader of activeVideoReaders) {
// log this because it's not very common
// also it is helpful to know in case things go wrong
log.info('draining a video reader');
videoReader.drain();
}
activeVideoReaders.clear();
};
process.on('exit', (code) => {
// other threads can be waiting on a uv_cond that is waiting for javascript to signal them;
// since the process is exiting, no more javascript will be run, so those threads will be stuck
// and the process won't actually exit. Therefore, we tell all running video_readers
// to unstick everything (aka drain) which causes all other threads to finish their operations
drainActiveVideoReaders();
});
export default {
...avalancheNative,
defaultLogAvalanche,
setLogFunc,
createVideoReader,
};