-
Notifications
You must be signed in to change notification settings - Fork 5
/
decoder.js
68 lines (57 loc) · 1.54 KB
/
decoder.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
const EventEmitter = require('events').EventEmitter;
const Header = require('./protocols/Header');
const Body = require('./protocols/Body');
module.exports = class FlvDemux extends EventEmitter {
constructor() {
super();
this.state = Header.STATE;
this.buffer = Buffer.alloc(0);
this.header = new Header();
this.body = new Body();
this.header.on('header', this.headerDataHandler.bind(this));
this.body.on('tag', this.tagDataHandler.bind(this));
}
decode(buffer, size = 0) {
this.buffer = Buffer.concat([this.buffer, buffer]);
for (;;) {
switch (this.state) {
case Header.STATE: {
if (this.buffer.length < Header.MIN_LENGTH) {
return;
}
let body = this.header.decode(this.buffer);
if (!body) {
throw new Error('not right spec header');
}
this.buffer = body;
this.state = Body.STATE;
break;
}
case Body.STATE: {
if (this.buffer.length < Body.MIN_LENGTH) {
return;
}
let body = this.body.decode(this.buffer);
this.buffer = body.data;
if (!body.success) {
return;
}
break;
}
}
}
}
destroy() {
this.buffer = null;
this.state = null;
this.header.removeAllListeners();
this.body.removeAllListeners();
this.removeAllListeners();
}
headerDataHandler(header) {
this.emit('header', header);
}
tagDataHandler(tag) {
this.emit('tag', tag);
}
};