-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
68 lines (55 loc) · 1.56 KB
/
index.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
var map = require('through2-map')
function glitch(buf, intensity) {
if (typeof intensity !== 'number') {
intensity = 0.1
}
var header_length = 0
var sos_chars_seen = 0
var last_byte
var end = buf.length - 1
for (var i = 0; i < end; i++) {
/**
First, we're looking for the Start Of Scan bytes which are
0xFFDA. The two bytes after this say how long the header stream
is. We'll skip forward that many bytes before we mess with
things so we don't make the jpeg invalid.
*/
if (sos_chars_seen === 0 && buf[i] === 255) {
sos_chars_seen = 1
} else if (sos_chars_seen === 1 && buf[i] === 218) {
sos_chars_seen = 2
header_length = buf[i+1] + buf[i+2]
} else if (header_length-- > 0) {
// skip forward until after we're past header.
continue
}
if (buf[i] === 255 || last_byte === 255) {
// Just skip over things with FF as that's bit of a touchy thing
// when it comes to huffman encoding that I'd prefer to ignore
// for the moment.
continue
}
last_byte = buf[i]
// skip some bytes
if (Math.random() >= intensity) {
continue
}
// only replace 120s
if (buf[i] !== 120) {
continue
}
// over 254 and things do not work.
buf[i] = rng(1, 254)
}
return buf
}
function rng(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
function glitchStream(intensity) {
return map(function(buf){
return glitch(buf, intensity)
})
}
glitch.stream = glitchStream
module.exports = glitch