forked from driusan/brainviewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MincLoader.js
2470 lines (2304 loc) · 75.3 KB
/
MincLoader.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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as pako from 'pako';
/*
* BrainBrowser: Web-based Neurological Visualization Tools
* (https://brainbrowser.cbrain.mcgill.ca)
*
* Copyright (C) 2016
* The Royal Institution for the Advancement of Learning
* McGill University
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Author: Robert D. Vincent ([email protected])
*
* Interprets a subset of the HDF5 format for the volume viewer. This
* is sufficient to parse most MINC 2.0 files, but may not handle HDF5
* from other sources!!
*
* Relies on pako (https://github.com/nodeca/pako) to inflate
* compressed data chunks.
*
* For details on the HDF5 format, see:
* https://www.hdfgroup.org/HDF5/doc/H5.format.html
*/
'use strict';
/* Internal type codes. These have nothing to do with HDF5. */
var type_enum = {
INT8: 1,
UINT8: 2,
INT16: 3,
UINT16: 4,
INT32: 5,
UINT32: 6,
FLT: 7,
DBL: 8,
STR: 9
};
function defined(x) {
return typeof x !== 'undefined';
}
function typeName(x) {
if (!defined(x)) {
return "undefined";
}
return x.constructor.name;
}
var type_sizes = [0, 1, 1, 2, 2, 4, 4, 4, 8, 0];
function typeSize(typ) {
if (typ >= type_enum.INT8 && typ < type_sizes.length) {
return type_sizes[typ];
}
throw new Error('Unknown type ' + typ);
}
function typeIsFloat(typ) {
return (typ >= type_enum.FLT && typ <= type_enum.DBL);
}
/**
* @doc function
* @name hdf5Reader
* @param {object} abuf The ArrayBuffer containing the data to be
* parsed.
* @param {boolean} debug True if we should print debugging information
* to the console.
* @returns A 'link' object that corresponds to the root group of the HDF5
* file structure.
* @description Attempts to interpret an ArrayBuffer as an HDF5 file.
*/
function hdf5Reader(abuf, debug) {
/* 'global' variables. */
var dv_offset = 0;
var align = 8;
var little_endian = true;
var continuation_queue = [];
console.log(typeof(abuf));
var dv = new DataView(abuf);
var superblk = {};
var start_offset = 0;
debug = debug || false;
/**
* @doc object
* @name hdf5.link
* @property {string} name The name associated with this object.
* @property {object} attributes Hash of all of the attributes
* associated with this object.
* @property {array} children Indexed list of child nodes.
* @property {object} array The typed array that contains the actual
* data associated with the link.
* @property {number} type The type of the data associated with this
* node, one of the type_enum values.
* @property {boolean} inflate True if the data needs to be decompressed
* during loading.
* @property {array} dims The lengths of each dimension in the image.
* @description This object is used to represent HDF5 objects such as
* groups and datasets, or NetCDF variables.
*/
/**
* @doc function
* @name hdf5Reader.createLink
* @returns {object} One of our internal 'link' objects.
* @description
* Function to create and initialize one of our internal
* 'link' objects, which represent either an HDF5 group
* or dataset here.
*/
function createLink() {
var r = {};
// internal/private
r.hdr_offset = 0; // offset to object header.
r.data_offset = 0; // offset to actual data.
r.data_length = 0; // length of data.
r.n_filled = 0; // counts elements written to array
r.chunk_size = 0; // number of bytes per chunk.
r.chunk_dims = []; // dimensions of chunks.
r.sym_btree = 0; // offset of symbol table btree
r.sym_lheap = 0; // offset of symbol table local heap
// permanent/global
r.name = ""; // name of this group or dataset.
r.attributes = {}; // indexed by attribute name.
r.children = []; // not associative for now.
r.array = undefined; // actual data, if dataset.
r.type = -1; // type of data.
r.inflate = false; // true if need to inflate (gzip).
r.dims = []; // dimension sizes.
return r;
}
/* Turns out that alignment of the messages in at least the
* version 1 object header is actually relative to the start
* of the header. So we update the start position of the
* header here, so we can refer to it when calculating the
* alignment in checkAlignment().
*/
function startAlignment() {
start_offset = dv_offset;
}
function checkAlignment() {
var tmp = dv_offset - start_offset;
if ((tmp % align) !== 0) {
var n = align - (tmp % align);
dv_offset += n;
if (debug) {
console.log('skipping ' + n + ' bytes at ' + tmp + ' for alignmnent');
}
}
}
/* helper functions to manipulate the current DataView offset.
*/
function skip(n_bytes) {
dv_offset += n_bytes;
}
function seek(new_offset) {
dv_offset = new_offset;
}
function tell() {
return dv_offset;
}
/* helper functions for access to our DataView. */
function getU8() {
var v = dv.getUint8(dv_offset);
dv_offset += 1;
return v;
}
function getU16() {
var v = dv.getUint16(dv_offset, little_endian);
dv_offset += 2;
return v;
}
function getU32() {
var v = dv.getUint32(dv_offset, little_endian);
dv_offset += 4;
return v;
}
function getU64() {
var v = dv.getUint64(dv_offset, little_endian);
dv_offset += 8;
return v;
}
function getF32() {
var v = dv.getFloat32(dv_offset, little_endian);
dv_offset += 4;
return v;
}
function getF64() {
var v = dv.getFloat64(dv_offset, little_endian);
dv_offset += 8;
return v;
}
function getOffset(offsz) {
var v = 0;
offsz = offsz || superblk.offsz;
if (offsz === 4) {
v = dv.getUint32(dv_offset, little_endian);
} else if (offsz === 8) {
v = dv.getUint64(dv_offset, little_endian);
} else {
throw new Error('Unsupported value for offset size ' + offsz);
}
dv_offset += offsz;
return v;
}
function getLength() {
var v = dv.getUint64(dv_offset, little_endian);
dv_offset += superblk.lensz;
return v;
}
function getString(length) {
var r = "";
var i;
var c;
for (i = 0; i < length; i += 1) {
c = getU8();
if (c === 0) {
dv_offset += (length - i - 1);
break;
}
r += String.fromCharCode(c);
}
return r;
}
function getArray(typ, n_bytes, new_off) {
var value;
var n_values;
var new_abuf;
var i;
var spp = dv_offset;
if (new_off) {
dv_offset = new_off;
}
switch (typ) {
case type_enum.INT8:
value = new Int8Array(abuf, dv_offset, n_bytes);
break;
case type_enum.UINT8:
value = new Uint8Array(abuf, dv_offset, n_bytes);
break;
case type_enum.INT16:
if ((dv_offset % 2) !== 0) {
new_abuf = new ArrayBuffer(n_bytes);
n_values = n_bytes / 2;
value = new Int16Array(new_abuf);
for (i = 0; i < n_values; i += 1) {
value[i] = getU16();
}
} else {
value = new Int16Array(abuf, dv_offset, n_bytes / 2);
dv_offset += n_bytes;
}
break;
case type_enum.UINT16:
if ((dv_offset % 2) !== 0) {
new_abuf = new ArrayBuffer(n_bytes);
n_values = n_bytes / 2;
value = new Uint16Array(new_abuf);
for (i = 0; i < n_values; i += 1) {
value[i] = getU16();
}
} else {
value = new Uint16Array(abuf, dv_offset, n_bytes / 2);
dv_offset += n_bytes;
}
break;
case type_enum.INT32:
if ((dv_offset % 4) !== 0) {
new_abuf = new ArrayBuffer(n_bytes);
n_values = n_bytes / 4;
value = new Int32Array(new_abuf);
for (i = 0; i < n_values; i += 1) {
value[i] = getU32();
}
} else {
value = new Int32Array(abuf, dv_offset, n_bytes / 4);
dv_offset += n_bytes;
}
break;
case type_enum.UINT32:
if ((dv_offset % 4) !== 0) {
new_abuf = new ArrayBuffer(n_bytes);
n_values = n_bytes / 4;
value = new Uint32Array(new_abuf);
for (i = 0; i < n_values; i += 1) {
value[i] = getU32();
}
} else {
value = new Uint32Array(abuf, dv_offset, n_bytes / 4);
dv_offset += n_bytes;
}
break;
case type_enum.FLT:
if ((dv_offset % 4) !== 0) {
new_abuf = new ArrayBuffer(n_bytes);
n_values = n_bytes / 4;
value = new Float32Array(new_abuf);
for (i = 0; i < n_values; i += 1) {
value[i] = getF32();
}
} else {
value = new Float32Array(abuf, dv_offset, n_bytes / 4);
dv_offset += n_bytes;
}
break;
case type_enum.DBL:
if ((dv_offset % 8) !== 0) {
new_abuf = new ArrayBuffer(n_bytes);
n_values = n_bytes / 8;
value = new Float64Array(new_abuf);
for (i = 0; i < n_values; i += 1) {
value[i] = getF64();
}
} else {
value = new Float64Array(abuf, dv_offset, n_bytes / 8);
dv_offset += n_bytes;
}
break;
default:
throw new Error('Bad type in getArray ' + typ);
}
if (new_off) {
dv_offset = spp;
}
return value;
}
/* Get a variably-sized integer from the DataView. */
function getUXX(n) {
var v;
var i;
switch (n) {
case 1:
v = dv.getUint8(dv_offset);
break;
case 2:
v = dv.getUint16(dv_offset, little_endian);
break;
case 4:
v = dv.getUint32(dv_offset, little_endian);
break;
case 8:
v = dv.getUint64(dv_offset, little_endian);
break;
default:
/* Certain hdf5 types can have odd numbers of bytes. We try
* to deal with that special case here.
*/
v = 0;
if (!little_endian) {
for (i = 0; i < n; i++) {
v = (v << 8) + dv.getUint8(dv_offset + i);
}
}
else {
for (i = n - 1; i >= 0; i--) {
v = (v << 8) + dv.getUint8(dv_offset + i);
}
}
}
dv_offset += n;
return v;
}
/* Patch in the missing function to get 64-bit integers.
* Note: this won't really quite work b/c Javascript doesn't
* have support for 64-bit integers.
*/
dv.getUint64 = function (off, little_endian) {
var l4 = dv.getUint32(off + 0, little_endian);
var u4 = dv.getUint32(off + 4, little_endian);
if (little_endian) {
return (u4 << 32) + l4;
} else {
return (l4 << 32) + u4;
}
};
/* Verify that the expected signature is found at this offset.
*/
function checkSignature(str) {
var i;
for (i = 0; i < str.length; i += 1) {
if (dv.getUint8(dv_offset + i) !== str.charCodeAt(i)) {
return false;
}
}
skip(str.length);
return true;
}
function hdf5Superblock() {
var sb = {};
if (!checkSignature("\u0089HDF\r\n\u001A\n")) {
throw new Error('Bad magic string in HDF5');
}
sb.sbver = getU8();
if (sb.sbver > 2) {
throw new Error('Unsupported HDF5 superblock version ' + sb.sbver);
}
if (sb.sbver <= 1) {
sb.fsver = getU8();
sb.rgver = getU8();
skip(1); // reserved
sb.shver = getU8();
sb.offsz = getU8();
sb.lensz = getU8();
skip(1); // reserved
sb.gln_k = getU16();
sb.gin_k = getU16();
sb.cflags = getU32();
if (sb.sbver === 1) {
sb.isin_k = getU16();
skip(2); // reserved
}
sb.base_addr = getOffset(sb.offsz);
sb.gfsi_addr = getOffset(sb.offsz);
sb.eof_addr = getOffset(sb.offsz);
sb.dib_addr = getOffset(sb.offsz);
sb.root_ln_offs = getOffset(sb.offsz);
sb.root_addr = getOffset(sb.offsz);
sb.root_cache_type = getU32();
skip(4);
skip(16);
} else {
sb.offsz = getU8();
sb.lensz = getU8();
sb.cflags = getU8();
sb.base_addr = getOffset(sb.offsz);
sb.ext_addr = getOffset(sb.offsz);
sb.eof_addr = getOffset(sb.offsz);
sb.root_addr = getOffset(sb.offsz);
sb.checksum = getU32();
}
if (debug) {
console.log("HDF5 SB " + sb.sbver + " " + sb.offsz + " " + sb.lensz + " " + sb.cflags);
}
return sb;
}
/* read the v2 fractal heap header */
function hdf5FractalHeapHeader() {
var fh = {};
if (!checkSignature("FRHP")) {
throw new Error('Bad or missing FRHP signature');
}
fh.ver = getU8(); // Version
fh.idlen = getU16(); // Heap ID length
fh.iof_el = getU16(); // I/O filter's encoded length
fh.flags = getU8(); // Flags
fh.objmax = getU32(); // Maximum size of managed objects.
fh.objnid = getLength(); // Next huge object ID
fh.objbta = getOffset(); // v2 B-tree address of huge objects
fh.nf_blk = getLength(); // Amount of free space in managed blocks
fh.af_blk = getOffset(); // Address of managed block free space manager
fh.heap_total = getLength(); // Amount of managed space in heap
fh.heap_alloc = getLength(); // Amount of allocated managed space in heap
fh.bai_offset = getLength(); // Offset of direct block allocation iterator
fh.heap_nobj = getLength(); // Number of managed objects in heap
fh.heap_chuge = getLength(); // Size of huge objects in heap
fh.heap_nhuge = getLength(); // Number of huge objects in heap
fh.heap_ctiny = getLength(); // Size of tiny objects in heap
fh.heap_ntiny = getLength(); // Number of tiny objects in heap
fh.table_width = getU16(); // Table width
fh.start_blksz = getLength(); // Starting block size
fh.max_blksz = getLength(); // Maximum direct block size
fh.max_heapsz = getU16(); // Maximum heap size
fh.rib_srows = getU16(); // Starting # of rows in root indirect block
fh.root_addr = getOffset(); // Address of root block
fh.rib_crows = getU16(); // Current # of rows in root indirect block
var max_dblock_rows = Math.log2(fh.max_blksz) - Math.log2(fh.start_blksz) + 2;
fh.K = Math.min(fh.rib_crows, max_dblock_rows) * fh.table_width;
fh.N = (fh.rib_crows < max_dblock_rows) ? 0 : fh.K - (max_dblock_rows * fh.table_width);
if (debug) {
console.log("FRHP V" + fh.ver + " F" + fh.flags + " " + fh.objbta + " Total:" + fh.heap_total + " Alloc:" + fh.heap_alloc + " #obj:" + fh.heap_nobj + " width:" + fh.table_width + " start_blksz:" + fh.start_blksz + " max_blksz:" + fh.max_blksz + " " + fh.max_heapsz + " srows:" + fh.rib_srows + " crows:" + fh.rib_crows + " " + fh.heap_nhuge);
console.log(" K: " + fh.K + " N: " + fh.N);
}
if (fh.iof_el > 0) {
throw new Error("Filters present in fractal heap.");
}
return fh;
}
/* read the v2 btree header */
function hdf5V2BtreeHeader() {
var bh = {};
if (!checkSignature("BTHD")) {
throw new Error('Bad or missing BTHD signature');
}
bh.ver = getU8();
bh.type = getU8();
bh.nodesz = getU32();
bh.recsz = getU16();
bh.depth = getU16();
bh.splitp = getU8();
bh.mergep = getU8();
bh.root_addr = getOffset();
bh.root_nrec = getU16();
bh.total_nrec = getLength();
bh.checksum = getU32();
if (debug) {
console.log("BTHD V" + bh.ver + " T" + bh.type + " " + bh.nodesz + " " + bh.recsz + " " + bh.depth + " " + bh.root_addr + " " + bh.root_nrec + " " + bh.total_nrec);
}
return bh;
}
var huge_id;
/*
* Enumerates btree records in a block. Records are found both in direct
* and indirect v2 btree blocks.
*/
function hdf5V2BtreeRecords(fh, bt_type, nrec, link) {
var i;
var spp; // saved position pointer
var offset;
var length;
if (bt_type === 1) {
for (i = 0; i < nrec; i++) {
offset = getOffset();
length = getLength();
var id = getLength();
if (debug) {
console.log(" -> " + offset + " " + length + " " + id + " " + huge_id);
}
spp = tell();
if (id === huge_id) {
seek(offset);
hdf5MsgAttribute(length, link);
}
seek(spp);
}
}
else if (bt_type === 8) {
var cb_offs;
var cb_leng;
/* maximum heap size is stored in bits! */
cb_offs = fh.max_heapsz / 8;
var tmp = Math.min(fh.objmax, fh.max_blksz);
if (tmp <= 256) {
cb_leng = 1;
}
else if (tmp <= 65536) {
cb_leng = 2;
}
else {
cb_leng = 4;
}
for (i = 0; i < nrec; i++) {
/* Read managed fractal heap ID.
*/
var vt = getU8();
if ((vt & 0xc0) !== 0) {
throw new Error('Bad Fractal Heap ID version ' + vt);
}
var id_type = (vt & 0x30);
var flags;
if (id_type === 0x10) { // huge!
huge_id = getUXX(7);
}
else if (id_type === 0x00) { // managed.
offset = getUXX(cb_offs);
length = getUXX(cb_leng);
}
else {
throw new Error("Can't handle this Heap ID: " + vt);
}
flags = getU8();
/* Read the rest of the record.
*/
getU32(); // creation order (IGNORE)
getU32(); // hash (IGNORE)
if (debug) {
console.log(" -> " + vt + " " + offset + " " + length + " " + flags);
}
spp = tell();
if (id_type === 0x10) {
/* A "huge" object is found by indexing through the btree
* present in the header
*/
seek(fh.objbta);
var bh = hdf5V2BtreeHeader();
if (bh.type === 1) {
seek(bh.root_addr);
hdf5V2BtreeLeafNode(fh, bh.root_nrec, link);
}
else {
throw new Error("Can only handle type-1 btrees");
}
}
else {
/*
* A managed object implies that the attribute message is
* found in the associated fractal heap at the specified
* offset in the heap. We get the actual address
* corresponding to the offset here.
*/
var location = hdf5FractalHeapOffset(fh, offset);
if (location >= 0) {
seek(location);
hdf5MsgAttribute(length, link);
}
}
seek(spp);
}
}
else {
throw new Error("Unhandled V2 btree type.");
}
}
/* read a v2 btree leaf node */
function hdf5V2BtreeLeafNode(fh, nrec, link) {
if (!checkSignature("BTLF")) {
throw new Error('Bad or missing BTLF signature');
}
var ver = getU8();
var typ = getU8();
if (debug) {
console.log("BTLF V" + ver + " T" + typ + " " + tell());
}
hdf5V2BtreeRecords(fh, typ, nrec, link);
}
/* read the hdf5 v2 btree internal node */
function hdf5V2BtreeInternalNode(fh, nrec, depth, link) {
if (!checkSignature("BTIN")) {
throw new Error('Bad or missing BTIN signature');
}
var ver = getU8();
var type = getU8();
var i;
if (debug) {
console.log("BTIN V" + ver + " T" + type);
}
hdf5V2BtreeRecords(fh, type, nrec, link);
for (i = 0; i <= nrec; i++) {
var child_offset = getOffset();
var child_nrec = getUXX(1); // TODO: calculate real size!!
var child_total;
/* TODO: unfortunately, this field is optional and
* variably-sized. Calculating the size is non-trivial, as it
* depends on the total depth and size of the tree. For now
* we will just assume it is its minimum size, as I've never
* encountered a file with depth > 1 anyway.
*/
if (depth > 1) {
child_total = getUXX(1);
}
if (debug) {
console.log(" child->" + child_offset + " " + child_nrec + " " + child_total);
}
}
}
/* Names of the various HDF5 messages.
* Note that MESSAGE23 appears to be illegal. All the rest are defined,
* although I've never encountered a BOGUS message!
*/
var msg_names = [
"NIL", "Dataspace", "LinkInfo", "Datatype", "FillValue 1", "FillValue 2",
"Link", "ExternalFiles", "Layout", "BOGUS", "GroupInfo", "FilterPipeline",
"Attribute", "ObjectComment", "ObjectModTime 1", "SharedMsgTable",
"ObjHdrContinue", "SymbolTable", "ObjectModTime 2", "BtreeKValue",
"DriverInfo", "AttrInfo", "ObjectRefCnt", "MESSAGE23",
"FileSpaceInfo"
];
function hdf5GetMsgName(n) {
if (n < msg_names.length) {
return msg_names[n];
}
throw new Error('Unknown message type ' + n + " " + tell());
}
// Compute the expected uncompressed size of a chunk. We have to
// do some additional calculation because it is possible to have a
// "padded" chunk when the chunk dimension is not an even multiple
// of the total dataset dimension.
//
function calcChunkSize(dims, chunk_dims, chunk_offsets) {
var j;
var result = 1;
for (j = 0; j < dims.length; j++) {
// compute the number of remaining points in this chunk.
var diff = dims[j] - chunk_offsets[j];
if ( chunk_dims[j] > diff ) {
result *= diff;
}
else {
result *= chunk_dims[j];
}
}
return result;
}
function hdf5V1BtreeNode(link) {
var i;
var bt = {};
if (!checkSignature("TREE")) {
throw new Error('Bad TREE signature at ' + tell());
}
bt.keys = [];
bt.node_type = getU8();
bt.node_level = getU8();
bt.entries_used = getU16();
bt.left_sibling = getOffset();
bt.right_sibling = getOffset();
if (debug) {
console.log("BTREE type " + bt.node_type + " lvl " +
bt.node_level + " n_used " + bt.entries_used + " " +
bt.left_sibling + " " + bt.right_sibling);
}
if (!link) {
/* If this BTREE is associated with a group (not a dataset),
* then its keys are single "length" value.
*/
for (i = 0; i < bt.entries_used; i += 1) {
bt.keys[i] = {};
bt.keys[i].key_value = getLength();
bt.keys[i].child_address = getOffset();
if (debug) {
console.log(" BTREE " + i + " key " +
bt.keys[i].key_value + " adr " +
bt.keys[i].child_address);
}
}
} else {
var j;
/* If this BTREE is a "chunked raw data node" associated
* with a dataset, then its keys are complex, consisting
* of the chunk size in bytes, a filter mask, and a set of
* offsets matching the dimensionality of the chunk layout.
* The chunk size stores the actual stored length of the
* data, so it may not equal the uncompressed chunk size.
*/
var chunks = [];
for (i = 0; i < bt.entries_used; i += 1) {
bt.keys[i] = {};
chunks[i] = {};
chunks[i].chunk_size = getU32();
chunks[i].filter_mask = getU32();
chunks[i].chunk_offsets = [];
for (j = 0; j < link.dims.length + 1; j += 1) {
chunks[i].chunk_offsets.push(getU64());
}
bt.keys[i].child_address = getOffset();
if (i < bt.entries_used) {
if (debug) {
console.log(" BTREE " + i +
" chunk_size " + chunks[i].chunk_size +
" filter_mask " + chunks[i].filter_mask +
" addr " + bt.keys[i].child_address);
}
}
}
chunks[i] = {};
chunks[i].chunk_size = getU32();
chunks[i].filter_mask = getU32();
chunks[i].chunk_offsets = [];
for (j = 0; j < link.dims.length + 1; j += 1) {
chunks[i].chunk_offsets.push(getU64());
}
/* If we're at a leaf node, we have data to deal with.
* We might have to uncompress!
*/
if (bt.node_level === 0) {
var length;
var offset;
var sp;
var dp;
for (i = 0; i < bt.entries_used; i += 1) {
length = chunks[i].chunk_size;
offset = bt.keys[i].child_address;
var dst_length = calcChunkSize(link.dims, link.chunk_dims,
chunks[i].chunk_offsets);
if (link.inflate) {
sp = new Uint8Array(abuf, offset, length);
dp = pako.inflate(sp);
switch (link.type) {
case type_enum.INT8:
dp = new Int8Array(dp.buffer);
break;
case type_enum.UINT8:
dp = new Uint8Array(dp.buffer);
break;
case type_enum.INT16:
dp = new Int16Array(dp.buffer);
break;
case type_enum.UINT16:
dp = new Uint16Array(dp.buffer);
break;
case type_enum.INT32:
dp = new Int32Array(dp.buffer);
break;
case type_enum.UINT32:
dp = new Uint32Array(dp.buffer);
break;
case type_enum.FLT:
dp = new Float32Array(dp.buffer);
break;
case type_enum.DBL:
dp = new Float64Array(dp.buffer);
break;
default:
throw new Error('Unknown type code ' + link.type);
}
if (dst_length < dp.length) {
dp = dp.subarray(0, dst_length);
}
if (link.array.length - link.n_filled < dp.length) {
dp = dp.subarray(0, link.array.length - link.n_filled);
console.log("WARNING: Discarding excess data.");
}
link.array.set(dp, link.n_filled);
link.n_filled += dp.length;
if (debug) {
console.log(link.name + " " + sp.length + " " + dp.length + " " + link.n_filled + "/" + link.array.length);
}
}
else {
/* no need to inflate data. */
dp = getArray(link.type, length, offset);
link.array.set(dp, link.n_filled);
link.n_filled += dp.length;
}
}
} else {
for (i = 0; i < bt.entries_used; i += 1) {
seek(bt.keys[i].child_address);
hdf5V1BtreeNode(link);
}
}
}
return bt;
}
function hdf5GroupSymbolTable(lh, link) {
if (!checkSignature("SNOD")) {
throw new Error('Bad or missing SNOD signature');
}
var ver = getU8();
skip(1);
var n_sym = getU16();
if (debug) {
console.log("hdf5GroupSymbolTable V" + ver + " #" + n_sym +
" '" + link.name + "'");
}
var i;
var link_name_offset;
var ohdr_address;
var cache_type;
var child;
var spp;
for (i = 0; i < 2 * superblk.gln_k; i += 1) {
link_name_offset = getOffset();
ohdr_address = getOffset();
cache_type = getU32();
skip(20);
if (i < n_sym) {
child = createLink();
child.hdr_offset = ohdr_address;
if (lh) {
spp = tell();
/* The link name is a zero-terminated string
* starting at the link_name_off relative to
* the beginning of the data segment of the local
* heap.
*/
seek(lh.lh_dseg_off + link_name_offset);
child.name = getString(lh.lh_dseg_len);
seek(spp);
}
if (debug) {
console.log(" " + i + " O " + link_name_offset + " A " +
ohdr_address + " T " + cache_type + " '" +
child.name + "'");
}
link.children.push(child);
}
}
}
/* Read a v1 local heap header. These define relatively small
* regions used primarily for storing symbol names associated with
* a symbol table message.
*/
function hdf5LocalHeap() {
var lh = {};
if (!checkSignature("HEAP")) {
throw new Error('Bad or missing HEAP signature');
}
lh.lh_ver = getU8();
skip(3);
lh.lh_dseg_len = getLength();
lh.lh_flst_len = getLength();
lh.lh_dseg_off = getOffset();
if (debug) {
console.log("LHEAP V" + lh.lh_ver + " " + lh.lh_dseg_len + " " +
lh.lh_flst_len + " " + lh.lh_dseg_off);
}
return lh;
}
/* Process a "dataspace" message. Dataspaces define the
* dimensionality of a dataset or attribute. They define the
* number of dimensions (rank) and the current length of each
* dimension. It is possible to specify a "maximum" length that is
* greater than or equal to the current length, but MINC doesn't
* rely on that feature so these values are ignored. Finally it
* is also possible to specify a "permutation index" that alters
* storage order of the dataset, but again, MINC doesn't rely on
* this feature, so the values are ignored.
*/
function hdf5MsgDataspace(sz, link) {
var cb;
var ver = getU8();
var n_dim = getU8();
var flag = getU8();
if (ver <= 1) {
skip(5);
} else {
skip(1);
}
var n_items = 1;
var dlen = [];
var i;
for (i = 0; i < n_dim; i += 1) {
dlen[i] = getLength();
n_items *= dlen[i];
}
cb = (n_dim * superblk.lensz) + ((ver <= 1) ? 8 : 4);
var dmax = [];
if ((flag & 1) !== 0) {
cb += n_dim * superblk.lensz;
for (i = 0; i < n_dim; i += 1) {
dmax[i] = getLength();
}
}
var dind = [];
if ((flag & 2) !== 0) {
cb += n_dim * superblk.lensz;
for (i = 0; i < n_dim; i += 1) {
dind[i] = getLength();
}
}
var msg = "hdf5MsgDataspace V" + ver + " N" + n_dim + " F" + flag;
if (debug) {
if (n_dim !== 0) {
msg += "[" + dlen.join(', ') + "]";
}
console.log(msg);
}