/
OMEXMLReader.java
430 lines (372 loc) · 13.4 KB
/
OMEXMLReader.java
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
/*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2016 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package loci.formats.in;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Vector;
import loci.common.CBZip2InputStream;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.common.xml.BaseHandler;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.MissingLibraryException;
import loci.formats.codec.CodecOptions;
import loci.formats.codec.JPEG2000Codec;
import loci.formats.codec.JPEGCodec;
import loci.formats.codec.ZlibCodec;
import loci.formats.meta.MetadataStore;
import loci.formats.ome.OMEXMLMetadata;
import loci.formats.services.OMEXMLService;
import loci.formats.services.OMEXMLServiceImpl;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.helpers.DefaultHandler;
import com.google.common.io.BaseEncoding;
/**
* OMEXMLReader is the file format reader for OME-XML files.
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class OMEXMLReader extends FormatReader {
// -- Fields --
// compression value and offset for each BinData element
private Vector<BinData> binData;
private Vector<Long> binDataOffsets;
private Vector<String> compression;
private String omexml;
private boolean hasSPW = false;
// -- Constructor --
/** Constructs a new OME-XML reader. */
public OMEXMLReader() {
super("OME-XML", new String[] {"ome", "ome.xml"});
domains = FormatTools.NON_GRAPHICS_DOMAINS;
suffixNecessary = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 64;
String xml = stream.readString(blockLen);
return xml.startsWith("<?xml") && xml.indexOf("<OME") >= 0;
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
if (checkSuffix(name, "companion.ome")) {
// pass binary-only files along to the OME-TIFF reader
return false;
}
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#getDomains() */
@Override
public String[] getDomains() {
FormatTools.assertId(currentId, true, 1);
return hasSPW ? new String[] {FormatTools.HCS_DOMAIN} :
FormatTools.NON_SPECIAL_DOMAINS;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
if (binDataOffsets.size() == 0) return buf;
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int index = no;
int series = getSeries();
for (int i=0; i<series; i++) {
index += core.get(i).imageCount;
}
if (index >= binDataOffsets.size()) {
index = binDataOffsets.size() - 1;
}
long offset = binDataOffsets.get(index).longValue();
String compress = compression.get(index);
in.seek(offset);
int depth = FormatTools.getBytesPerPixel(getPixelType());
int planeSize = getSizeX() * getSizeY() * depth;
CodecOptions options = new CodecOptions();
options.width = getSizeX();
options.height = getSizeY();
options.bitsPerSample = depth * 8;
options.channels = getRGBChannelCount();
options.maxBytes = planeSize;
options.littleEndian = isLittleEndian();
options.interleaved = isInterleaved();
String encoded = in.readString("<");
encoded = encoded.trim();
if (encoded.length() == 0 || encoded.equals("<")) {
LOGGER.debug("No pixel data for plane #{}", no);
return buf;
}
encoded = encoded.substring(0, encoded.length() - 1);
byte[] pixels = BaseEncoding.base64().decode(encoded);
// return a blank plane if no pixel data was stored
if (pixels.length == 0) {
LOGGER.debug("No pixel data for plane #{}", no);
return buf;
}
// TODO: Create a method uncompress to handle all compression methods
if (compress.equals("bzip2")) {
byte[] tempPixels = pixels;
pixels = new byte[tempPixels.length - 2];
System.arraycopy(tempPixels, 2, pixels, 0, pixels.length);
ByteArrayInputStream bais = new ByteArrayInputStream(pixels);
CBZip2InputStream bzip = new CBZip2InputStream(bais);
pixels = new byte[planeSize];
bzip.read(pixels, 0, pixels.length);
tempPixels = null;
bais.close();
bzip.close();
bais = null;
bzip = null;
}
else if (compress.equals("zlib")) {
pixels = new ZlibCodec().decompress(pixels, options);
}
else if (compress.equals("J2K")) {
pixels = new JPEG2000Codec().decompress(pixels, options);
}
else if (compress.equals("JPEG")) {
pixels = new JPEGCodec().decompress(pixels, options);
}
for (int row=0; row<h; row++) {
int off = (row + y) * getSizeX() * depth + x * depth;
System.arraycopy(pixels, off, buf, row * w * depth, w * depth);
}
pixels = null;
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
compression = null;
binDataOffsets = null;
binData = null;
omexml = null;
hasSPW = false;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
in.setEncoding("ASCII");
binData = new Vector<BinData>();
binDataOffsets = new Vector<Long>();
compression = new Vector<String>();
DefaultHandler handler = new OMEXMLHandler();
try {
RandomAccessInputStream s = new RandomAccessInputStream(id);
XMLTools.parseXML(s, handler);
s.close();
}
catch (IOException e) {
throw new FormatException("Malformed OME-XML", e);
}
int lineNumber = 1;
for (BinData bin : binData) {
int line = bin.getRow();
int col = bin.getColumn();
while (lineNumber < line) {
in.readLine();
lineNumber++;
}
binDataOffsets.add(in.getFilePointer() + col - 1);
}
LOGGER.info("Populating metadata");
OMEXMLMetadata omexmlMeta;
OMEXMLService service;
try {
ServiceFactory factory = new ServiceFactory();
service = factory.getInstance(OMEXMLService.class);
omexmlMeta = service.createOMEXMLMetadata(omexml);
}
catch (DependencyException de) {
throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
}
catch (ServiceException se) {
throw new FormatException(se);
}
hasSPW = omexmlMeta.getPlateCount() > 0;
addGlobalMeta("Is SPW file", hasSPW);
// TODO
//Hashtable originalMetadata = omexmlMeta.getOriginalMetadata();
//if (originalMetadata != null) metadata = originalMetadata;
int numDatasets = omexmlMeta.getImageCount();
int oldSeries = getSeries();
core.clear();
for (int i=0; i<numDatasets; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
setSeries(i);
Integer w = omexmlMeta.getPixelsSizeX(i).getValue();
Integer h = omexmlMeta.getPixelsSizeY(i).getValue();
Integer t = omexmlMeta.getPixelsSizeT(i).getValue();
Integer z = omexmlMeta.getPixelsSizeZ(i).getValue();
Integer c = omexmlMeta.getPixelsSizeC(i).getValue();
if (w == null || h == null || t == null || z == null | c == null) {
throw new FormatException("Image dimensions not found");
}
Boolean endian = null;
if (binData.size() > 0) {
endian = omexmlMeta.getPixelsBinDataBigEndian(i, 0);
}
String pixType = omexmlMeta.getPixelsType(i).toString();
ms.dimensionOrder = omexmlMeta.getPixelsDimensionOrder(i).toString();
ms.sizeX = w.intValue();
ms.sizeY = h.intValue();
ms.sizeT = t.intValue();
ms.sizeZ = z.intValue();
ms.sizeC = c.intValue();
ms.imageCount = getSizeZ() * getSizeC() * getSizeT();
ms.littleEndian = endian == null ? false : !endian.booleanValue();
ms.rgb = false;
ms.interleaved = false;
ms.indexed = false;
ms.falseColor = true;
ms.pixelType = FormatTools.pixelTypeFromString(pixType);
ms.orderCertain = true;
if (omexmlMeta.getPixelsSignificantBits(i) != null) {
ms.bitsPerPixel = omexmlMeta.getPixelsSignificantBits(i).getValue();
}
}
setSeries(oldSeries);
// populate assigned metadata store with the
// contents of the internal OME-XML metadata object
MetadataStore store = getMetadataStore();
service.convertMetadata(omexmlMeta, store);
MetadataTools.populatePixels(store, this, false, false);
}
// -- Helper class --
class OMEXMLHandler extends BaseHandler {
private StringBuffer xmlBuffer;
private String currentQName;
private Locator locator;
public OMEXMLHandler() {
xmlBuffer = new StringBuffer();
}
@Override
public void characters(char[] ch, int start, int length) {
if (currentQName.indexOf("BinData") < 0) {
xmlBuffer.append(new String(ch, start, length));
}
}
@Override
public void endElement(String uri, String localName, String qName) {
xmlBuffer.append("</");
xmlBuffer.append(qName);
xmlBuffer.append(">");
}
@Override
public void startElement(String ur, String localName, String qName,
Attributes attributes)
{
currentQName = qName;
if (qName.indexOf("BinData") == -1) {
xmlBuffer.append("<");
xmlBuffer.append(qName);
for (int i=0; i<attributes.getLength(); i++) {
String key = XMLTools.escapeXML(attributes.getQName(i));
String value = XMLTools.escapeXML(attributes.getValue(i));
if (key.equals("BigEndian")) {
String endian = value.toLowerCase();
if (!endian.equals("true") && !endian.equals("false")) {
// hack for files that specify 't' or 'f' instead of
// 'true' or 'false'
if (endian.startsWith("t")) endian = "true";
else if (endian.startsWith("f")) endian = "false";
}
value = endian;
}
xmlBuffer.append(" ");
xmlBuffer.append(key);
xmlBuffer.append("=\"");
xmlBuffer.append(value);
xmlBuffer.append("\"");
}
xmlBuffer.append(">");
}
else {
binData.add(
new BinData(locator.getLineNumber(), locator.getColumnNumber()));
String compress = attributes.getValue("Compression");
compression.add(compress == null ? "" : compress);
xmlBuffer.append("<");
xmlBuffer.append(qName);
for (int i=0; i<attributes.getLength(); i++) {
String key = XMLTools.escapeXML(attributes.getQName(i));
String value = XMLTools.escapeXML(attributes.getValue(i));
if (key.equals("Length")) value = "0";
xmlBuffer.append(" ");
xmlBuffer.append(key);
xmlBuffer.append("=\"");
xmlBuffer.append(value);
xmlBuffer.append("\"");
}
xmlBuffer.append(">");
}
}
@Override
public void endDocument() {
omexml = xmlBuffer.toString();
}
@Override
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
}
class BinData {
private int row;
private int column;
public BinData(int row, int column) {
this.row = row;
this.column = column;
}
public int getRow() { return row; }
public int getColumn() { return column; }
}
}