-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPGMLoaderBase.js
233 lines (155 loc) · 4.8 KB
/
PGMLoaderBase.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
// spec:
// http://netpbm.sourceforge.net/doc/pgm.html
// example images:
// https://people.sc.fsu.edu/~jburkardt/data/pgmb/pgmb.html
// Issues
// - ASCII PGM files are not supported
/**
* @typedef {Object} PGMResult
*
* @param {Uint16Array|Uint8Array} data
* The PGM laid out in an array in row major order where each row has a stride of `width`.
*
* @param {Number} width
* The width of the pgm file in pixels.
*
* @param {Number} height
* The height of the pgm file in pixels.
*
* @param {Number} maxValue
* The maximum gray value in the file.
*/
function swapByteOrder( buffer ) {
const byteBuffer = new Uint8Array( buffer );
for ( let i = 0; i < byteBuffer.byteLength; i += 2 ) {
const temp = byteBuffer[ i ];
byteBuffer[ i ] = byteBuffer[ i + 1 ];
byteBuffer[ i + 1 ] = temp;
}
}
/** Class for loading and parsing PGM image files */
export class PGMLoaderBase {
constructor() {
/**
* @member {Object}
* @description Fetch options for loading the file.
* @default { credentials: 'same-origin' }
*/
this.fetchOptions = { credentials: 'same-origin' };
}
/**
* Loads and parses the PGM file. The promise resolves with the returned
* data from the {@link #PGMLoader#parse parse} function.
* @param {String} url
* @returns {Promise<PGMResult>}
*/
load( url ) {
return fetch( url, this.fetchOptions )
.then( res => {
if ( ! res.ok ) {
throw new Error( `PGMLoader: Failed to load file "${url}" with status ${res.status} : ${res.statusText}` );
}
return res.arrayBuffer();
} )
.then( buffer => this.parse( buffer ) );
}
/**
* Parses the contents of the given PGM and returns an object describing
* the telemetry.
* @param {ArrayBuffer} buffer
* @returns {PGMResult}
*/
parse( buffer ) {
const dataView = new DataView( buffer );
let currIndex = 0;
// read the given number of bytes as a string
function readString( len ) {
const end = currIndex + len;
let s = '';
for ( ; currIndex < end; currIndex ++ ) {
s += String.fromCharCode( dataView.getUint8( currIndex, true ) );
}
return s;
}
// read bytes as a string until the provided function returns true
function readStringUntil( func ) {
let str = '';
while ( true ) {
const c = String.fromCharCode( dataView.getUint8( currIndex, true ) );
if ( func( c ) ) break;
str += c;
currIndex ++;
}
return str;
}
// check file identifier
const identifier = readString( 2 );
if ( identifier !== 'P5' && identifier !== 'P2' ) {
throw new Error( 'PGMLoader: Invalid file identifier' );
}
// Consume header tokens until we have found three.
// Continue for a fixed number of iterations so we
// don't iterate unnecessarily long if there's a problem
const MAX_ITERATIONS = 100;
let header = '';
let headerTokens = null;
for ( let i = 0; i < MAX_ITERATIONS; i ++ ) {
const readContent = readStringUntil( c => /[\s\n\r#]/g.test( c ) );
header += readContent;
const delineator = readString( 1 );
if ( delineator === '#' ) {
// comment
readStringUntil( c => /[\n\r]/g.test( c ) );
} else {
header += delineator;
}
headerTokens = header
// tokenize
.split( /\s+/g )
// remove empty tokens
.filter( t => !! t );
if ( headerTokens.length === 3 ) {
break;
}
}
if ( headerTokens.length !== 3 ) {
throw new Error( 'PGMLoader: Could not parse header -- invalid number of header tokens' );
}
const width = parseInt( headerTokens[ 0 ] );
const height = parseInt( headerTokens[ 1 ] );
const maxValue = parseInt( headerTokens[ 2 ] );
const byteLen = maxValue < 256 ? 1 : 2;
let data;
if ( identifier === 'P5' ) {
if ( width * height * byteLen !== buffer.byteLength - currIndex ) {
throw new Error( 'PGMLoader: Invalid data length' );
}
if ( byteLen === 1 ) {
data = new Uint8Array( buffer, currIndex, width * height );
} else {
// Uint16Array cannot have an offset index that is not a
// multiple of 2 so copy the data buffer here to its own
// separate buffer
const dataBuffer = buffer.slice( currIndex, currIndex + width * height * 2 );
// TODO: Handle endianness properly. We can't guarantee what the byte order of the file is
// or what the byte order of the javascript platform is.
// The expected endianness is flipped
swapByteOrder( dataBuffer );
data = new Uint16Array( dataBuffer );
}
} else {
data = byteLen === 1 ? new Uint8Array( width * height ) : Uint16Array( width * height );
const remainingContent = readString( buffer.byteLength - currIndex );
const parsed = remainingContent.split( /[\s\n\r]+/g );
for ( let i = 0, l = width * height; i < l; i ++ ) {
data[ i ] = parseFloat( parsed[ i ] );
}
}
return {
data,
width,
height,
maxValue,
};
}
}