forked from openpreserve/jpylyzer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathboxvalidator.py
2168 lines (1618 loc) · 76.1 KB
/
boxvalidator.py
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
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import division
import uuid
import math
import config
import etpatch as ET
import byteconv as bc
from shared import listOccurrencesAreContiguous
from shared import printWarning
class BoxValidator:
# Marker tags/codes that identify all sub-boxes as hexadecimal strings
#(Correspond to "Box Type" values, see ISO/IEC 15444-1 Section I.4)
typeMap = {
b'\x6a\x70\x32\x69': "intellectualPropertyBox",
b'\x78\x6d\x6c\x20': "xmlBox",
b'\x75\x75\x69\x64': "uuidBox",
b'\x75\x69\x6e\x66': "uuidInfoBox",
b'\x6a\x50\x20\x20': "signatureBox",
b'\x66\x74\x79\x70': "fileTypeBox",
b'\x6a\x70\x32\x68': "jp2HeaderBox",
b'\x69\x68\x64\x72': "imageHeaderBox",
b'\x62\x70\x63\x63': "bitsPerComponentBox",
b'\x63\x6f\x6c\x72': "colourSpecificationBox",
b'\x70\x63\x6c\x72': "paletteBox",
b'\x63\x6d\x61\x70': "componentMappingBox",
b'\x63\x64\x65\x66': "channelDefinitionBox",
b'\x72\x65\x73\x20': "resolutionBox",
b'\x6a\x70\x32\x63': "contiguousCodestreamBox",
b'\x72\x65\x73\x63': "captureResolutionBox",
b'\x72\x65\x73\x64': "displayResolutionBox",
b'\x75\x6c\x73\x74': "uuidListBox",
b'\x75\x72\x6c\x20': "urlBox",
b'\xff\x51': "siz",
b'\xff\x52': "cod",
b'\xff\x5c': "qcd",
b'\xff\x64': "com",
b'\xff\x90': "tilePart",
'icc': 'icc',
'startOfTile': 'sot'
}
# Reverse access of typemap for quick lookup
boxTagMap = {v:k for k, v in typeMap.items()}
def __init__(self, bType, boxContents, startOffset = None):
if bType in self.typeMap:
self.boxType = self.typeMap[bType]
elif bType == "JP2":
self.characteristics = ET.Element("properties")
self.tests = ET.Element("tests")
self.boxType = "JP2"
else:
self.boxType = 'unknownBox'
if self.boxType != "JP2":
self.characteristics = ET.Element(self.boxType)
self.tests = ET.Element(self.boxType)
self.boxContents = boxContents
self.startOffset = startOffset
self.returnOffset = None
self.isValid = None
self.bTypeString = bType
def validate(self):
try:
to_call = getattr(self, "validate_" + self.boxType)
except AttributeError:
printWarning("ignoring '" + self.boxType + "' (validator function not yet implemented)" )
else:
to_call()
if self.isValid is not None:
return (self.isValid, self.tests, self.characteristics)
elif self.returnOffset is None:
return (self.tests, self.characteristics)
else:
return (self.tests, self.characteristics, self.returnOffset)
def _isValid(self):
for elt in self.tests.iter():
if elt.text == False:
# File didn't pass this test, so not valid
return(False)
return(True)
def _getBox(self, byteStart, noBytes):
# Parse JP2 box and return information on its
# size, type and contents
# Box length (4 byte unsigned integer)
boxLengthValue = bc.bytesToUInt(self.boxContents[byteStart:byteStart+4])
# Box type
boxType = self.boxContents[byteStart+4:byteStart+8]
# Start byte of box contents
contentsStartOffset = 8
# Read extended box length if box length value equals 1
# In that case contentsStartOffset should also be 16 (not 8!)
# (See ISO/IEC 15444-1 Section I.4)
if boxLengthValue == 1:
boxLengthValue = bc.bytesToULongLong(self.boxContents[byteStart+8:byteStart+16])
contentsStartOffset = 16
# For the very last box in a file boxLengthValue may equal 0, so we need
# to calculate actual value
if boxLengthValue == 0:
boxLengthValue = noBytes-byteStart
# End byte for current box
byteEnd = byteStart + boxLengthValue
# Contents of this box as a byte object (i.e. 'DBox' in ISO/IEC 15444-1 Section I.4)
boxContents = self.boxContents[byteStart+contentsStartOffset:byteEnd]
return (boxLengthValue, boxType, byteEnd, boxContents)
def _getMarkerSegment(self,offset):
# Read marker segment that starts at offset and return marker, size,
# contents and start offset of next marker
# First 2 bytes: 16 bit marker
marker = self.boxContents[offset:offset+2]
# Check if this is a delimiting marker segment
if marker in [b'\xff\x4f',b'\xff\x93',b'\xff\xd9',b'\xff\x92']:
# Zero-length markers: SOC, SOD, EOC, EPH
length=0
else:
# Not a delimiting marker, so remainder contains some data
length=bc.bytesToUShortInt(self.boxContents[offset+2:offset+4])
# Contents of marker segment (excluding marker) to binary string
contents=self.boxContents[offset+2:offset + 2 +length]
if length== -9999:
# If length couldn't be determined because of decode error,
# return bogus value for offsetNext (calling function should
# handle this further!)
offsetNext=-9999
else:
# Offset value start of next marker segment
offsetNext=offset+length+2
return(marker,length,contents,offsetNext)
def _calculateCompressionRatio(self, noBytes,bPCDepthValues,height,width):
# Computes compression ratio
# noBytes: size of compressed image in bytes
# bPCDepthValues: list with bits per component for each component
# height, width: image height, width
# Total bits per pixel
bitsPerPixel = 0
for i in range(len(bPCDepthValues)):
bitsPerPixel += bPCDepthValues[i]
# Convert to bytes per pixel
bytesPerPixel = bitsPerPixel/8
# Uncompressed image size
sizeUncompressed = bytesPerPixel*height*width
# Compression ratio
if noBytes != 0:
compressionRatio = sizeUncompressed / noBytes
else:
# Obviously something going wrong here ...
compressionRatio = -9999
return(compressionRatio)
def _getBitValue(self, n, p):
# Get the bit value of denary (base 10) number n at the equivalent binary
# position p (binary count starts at position 1 from the left)
# Only works if n can be expressed as 8 bits !!!
# Word length in bits
wordLength=8
# Shift = word length - p
shift=wordLength-p
return (n >> shift) & 1
def testFor(self, testType, testResult):
# Add testResult node to tests element tree
#print(config.outputVerboseFlag)
if config.outputVerboseFlag == False:
# Non-verbose output: only add results of tests that failed
if testResult==False:
self.tests.appendChildTagWithText(testType, testResult)
else:
# Verbose output, add results of all tests
self.tests.appendChildTagWithText(testType, testResult)
def addCharacteristic(self, characteristic, charValue):
# Add characteristic node to characteristics element tree
self.characteristics.appendChildTagWithText(characteristic, charValue)
# Validator functions for boxes
def validate_unknownBox(self):
# Although jpylyzer doesn't "know" anything about this box, we
# can at least report the 4 characters from the Box Type field
# (TBox) here
boxType=self.bTypeString
# If boxType contains any device control characters (e.g. because of
# file corruption), replace them with printable character
if bc.containsControlCharacters(boxType):
boxType=bc.replaceControlCharacters(boxType)
# Decode to string with Latin encoding
# Elementtree will deal with any non-ASCII characters by replacing
# them with numeric entity references
boxType=boxType.decode("iso-8859-15","strict")
# Add (cleaned up) boxType string to output
self.addCharacteristic( "boxType", boxType)
# Print warning message to screen
printWarning("ignoring unknown box")
def validate_signatureBox(self):
# Signature box (ISO/IEC 15444-1 Section I.5.2)
# Check box size, which should be 4 bytes
self.testFor("boxLengthIsValid", len(self.boxContents) == 4)
# Signature *not* added to characteristics output, because it contains non-printable characters)
self.testFor("signatureIsValid", self.boxContents[0:4] == b'\x0d\x0a\x87\x0a')
def validate_fileTypeBox(self):
# File type box (ISO/IEC 15444-1 Section I.5.2)
# Determine number of compatibility fields from box length
numberOfCompatibilityFields=(len(self.boxContents)-8)/4
# This should never produce a decimal number (would indicate missing data)
self.testFor("boxLengthIsValid", numberOfCompatibilityFields == int(numberOfCompatibilityFields))
# Brand value
br = self.boxContents[0:4]
self.addCharacteristic( "br", br)
# Is brand value valid?
self.testFor("brandIsValid", br == b'\x6a\x70\x32\x20')
# Minor version
minV = bc.bytesToUInt(self.boxContents[4:8])
self.addCharacteristic("minV", minV)
# Value should be 0
# Note that conforming readers should continue to process the file
# even if this field contains siome other value
self.testFor("minorVersionIsValid", minV == 0)
# Compatibility list (one or more 4-byte fields)
# Create list object and store all entries as separate list elements
cLList = []
offset = 8
for i in range(int(numberOfCompatibilityFields)):
cL = self.boxContents[offset:offset+4]
self.addCharacteristic("cL", cL)
cLList.append(cL)
offset += 4
# Compatibility list should contain at least one field with mandatory value.
# List is considered valid if this value is found.
self.testFor("compatibilityListIsValid", b'\x6a\x70\x32\x20' in cLList)
def validate_jp2HeaderBox(self):
# JP2 header box (superbox) (ISO/IEC 15444-1 Section I.5.3)
# List for storing box type identifiers
subBoxTypes = []
noBytes = len(self.boxContents)
byteStart = 0
bytesTotal = 0
# Dummy value
boxLengthValue = 10
while byteStart < noBytes and boxLengthValue != 0:
boxLengthValue, boxType, byteEnd, subBoxContents = self._getBox(byteStart, noBytes)
# Validate sub-boxes
resultBox, characteristicsBox = BoxValidator(boxType, subBoxContents).validate()
byteStart = byteEnd
# Add to list of box types
subBoxTypes.append(boxType)
# Add analysis results to test results tree
self.tests.appendIfNotEmpty(resultBox)
# Add extracted characteristics to characteristics tree
self.characteristics.append(characteristicsBox)
# Do all required header boxes exist?
self.testFor("containsImageHeaderBox", self.boxTagMap['imageHeaderBox'] in subBoxTypes)
self.testFor("containsColourSpecificationBox", self.boxTagMap['colourSpecificationBox'] in subBoxTypes)
# If bPCSign equals 1 and bPCDepth equals 128 (equivalent to bPC field being
# 255), this box should contain a Bits Per Components box
sign = self.characteristics.findElementText('imageHeaderBox/bPCSign')
depth = self.characteristics.findElementText('imageHeaderBox/bPCDepth')
if sign == 1 and depth == 128:
self.testFor("containsBitsPerComponentBox", self.boxTagMap['bitsPerComponentBox'] in subBoxTypes)
# Is the first box an Image Header Box?
try:
firstJP2HeaderBoxIsImageHeaderBox=subBoxTypes[0] == self.boxTagMap['imageHeaderBox']
except:
firstJP2HeaderBoxIsImageHeaderBox=False
self.testFor("firstJP2HeaderBoxIsImageHeaderBox",firstJP2HeaderBoxIsImageHeaderBox)
# Some boxes can have multiple instances, whereas for others only one
# is allowed
self.testFor("noMoreThanOneImageHeaderBox", subBoxTypes.count(self.boxTagMap['imageHeaderBox']) <= 1)
self.testFor("noMoreThanOneBitsPerComponentBox", subBoxTypes.count(self.boxTagMap['bitsPerComponentBox']) <= 1)
self.testFor("noMoreThanOnePaletteBox", subBoxTypes.count(self.boxTagMap['paletteBox']) <= 1)
self.testFor("noMoreThanOneComponentMappingBox", subBoxTypes.count(self.boxTagMap['componentMappingBox']) <= 1)
self.testFor("noMoreThanOneChannelDefinitionBox", subBoxTypes.count(self.boxTagMap['channelDefinitionBox']) <= 1)
self.testFor("noMoreThanOneResolutionBox", subBoxTypes.count(self.boxTagMap['resolutionBox']) <= 1)
# In case of multiple colour specification boxes, they should appear contiguously
# within the header box
colourSpecificationBoxesAreContiguous=listOccurrencesAreContiguous(subBoxTypes, self.boxTagMap['colourSpecificationBox'])
self.testFor("colourSpecificationBoxesAreContiguous",colourSpecificationBoxesAreContiguous)
# If JP2 Header box contains a Palette Box, it should also contain a component
# mapping box, and vice versa
if (self.boxTagMap['paletteBox'] in subBoxTypes and self.boxTagMap['componentMappingBox'] not in subBoxTypes) \
or (self.boxTagMap['componentMappingBox'] in subBoxTypes and self.boxTagMap['paletteBox'] not in subBoxTypes):
paletteAndComponentMappingBoxesOnlyTogether=False
else:
paletteAndComponentMappingBoxesOnlyTogether=True
self.testFor("paletteAndComponentMappingBoxesOnlyTogether",paletteAndComponentMappingBoxesOnlyTogether)
# Validator functions for boxes in JP2 Header superbox
def validate_imageHeaderBox(self):
# Image header box (ISO/IEC 15444-1 Section I.5.3.1)
# This is a fixed-length box that contains generic image info.
# Check box length (14 bytes, excluding box length/type fields)
self.testFor("boxLengthIsValid", len(self.boxContents) == 14)
# Image height and width (both as unsigned integers)
height = bc.bytesToUInt(self.boxContents[0:4])
self.addCharacteristic("height", height)
width = bc.bytesToUInt(self.boxContents[4:8])
self.addCharacteristic("width", width)
# Height and width should be within range 1 - (2**32)-1
self.testFor("heightIsValid", 1 <= height <= (2**32)-1)
self.testFor("widthIsValid", 1 <= width <= (2**32)-1)
# Number of components (unsigned short integer)
nC = bc.bytesToUShortInt(self.boxContents[8:10])
self.addCharacteristic("nC", nC)
# Number of components should be in range 1 - 16384 (including limits)
self.testFor("nCIsValid", 1 <= nC <= 16384)
# Bits per component (unsigned character)
bPC = bc.bytesToUnsignedChar(self.boxContents[10:11])
# Most significant bit indicates whether components are signed (1)
# or unsigned (0).
bPCSign = self._getBitValue(bPC, 1)
self.addCharacteristic("bPCSign", bPCSign)
# Remaining bits indicate (bit depth - 1). Extracted by applying bit mask of
# 01111111 (=127)
bPCDepth = (bPC & 127) + 1
self.addCharacteristic("bPCDepth", bPCDepth)
# Bits per component field is valid if:
# 1. bPCDepth in range 1-38 (including limits)
# 2. OR bPC equal 255 (indicating that components vary in bit depth)
bPCDepthIsWithinAllowedRange = 1 <= bPCDepth <= 38
bitDepthIsVariable = 1 <= bPC <= 255
if bPCDepthIsWithinAllowedRange == True or bitDepthIsVariable == True:
bPCIsValid=True
else:
bPCIsValid=False
self.testFor("bPCIsValid",bPCIsValid)
# Compression type (unsigned character)
c = bc.bytesToUnsignedChar(self.boxContents[11:12])
self.addCharacteristic("c", c)
# Value should always be 7
self.testFor("cIsValid", c == 7)
# Colourspace unknown field (unsigned character)
unkC = bc.bytesToUnsignedChar(self.boxContents[12:13])
self.addCharacteristic("unkC", unkC)
# Value should be 0 or 1
self.testFor("unkCIsValid", 0 <= unkC <= 1)
# Intellectual Property field (unsigned character)
iPR = bc.bytesToUnsignedChar(self.boxContents[13:14])
self.addCharacteristic("iPR",iPR)
# Value should be 0 or 1
self.testFor("iPRIsValid", 0 <= iPR <= 1)
def validate_bitsPerComponentBox(self):
# bits per component box (ISO/IEC 15444-1 Section I.5.3.2)
# Optional box that specifies bit depth of each component
# Number of bPC field (each field is 1 byte)
numberOfBPFields = len(self.boxContents)
# Validate all entries
for i in range(numberOfBPFields):
# Bits per component (unsigned character)
bPC = bc.bytesToUnsignedChar(self.boxContents[i:i+1])
# Most significant bit indicates whether components are signed (1)
# or unsigned (0). Extracted by applying bit mask of 10000000 (=128)
bPCSign = self._getBitValue(bPC, 1)
self.addCharacteristic("bPCSign",bPCSign)
# Remaining bits indicate (bit depth - 1). Extracted by applying bit mask of
# 01111111 (=127)
bPCDepth=(bPC & 127) + 1
self.addCharacteristic("bPCDepth",bPCDepth)
# Bits per component field is valid if bPCDepth in range 1-38 (including limits)
self.testFor("bPCIsValid", 1 <= bPCDepth <= 38)
def validate_colourSpecificationBox(self):
# Colour specification box (ISO/IEC 15444-1 Section I.5.3.3)
# This box defines one method for interpreting colourspace of decompressed
# image data
# Length of this box
length = len(self.boxContents)
# Specification method (unsigned character)
meth = bc.bytesToUnsignedChar(self.boxContents[0:1])
self.addCharacteristic("meth",meth)
# Value should be 1 (enumerated colourspace) or 2 (restricted ICC profile)
self.testFor("methIsValid", 1 <= meth <= 2)
# Precedence (unsigned character)
prec = bc.bytesToUnsignedChar(self.boxContents[1:2])
self.addCharacteristic("prec",prec)
# Value shall be 0 (but conforming readers should ignore it)
self.testFor("precIsValid", prec == 0)
# Colourspace approximation (unsigned character)
approx = bc.bytesToUnsignedChar(self.boxContents[2:3])
self.addCharacteristic("approx",approx)
# Value shall be 0 (but conforming readers should ignore it)
self.testFor("approxIsValid",approx == 0)
# Colour space info: enumerated CS or embedded ICC profile,
# depending on value of meth
if meth == 1:
# Enumerated colour space field (long integer)
enumCS = bc.bytesToUInt(self.boxContents[3:length])
self.addCharacteristic("enumCS",enumCS)
# (Note: this will also trap any cases where enumCS is more/less than 4
# bytes, as bc.bytesToUInt will return bogus negative value, which in turn is
# handled by statement below)
# Legal values: 16,17, 18
self.testFor("enumCSIsValid", enumCS in [16,17,18])
elif meth == 2:
# Restricted ICC profile
profile = self.boxContents[3:length]
# Extract ICC profile properties as element object
tests, iccCharacteristics = BoxValidator('icc', profile).validate() #self.getICCCharacteristics(profile)
self.characteristics.append(iccCharacteristics)
# Profile size property should equal actual profile size
profileSize = iccCharacteristics.findElementText('profileSize')
self.testFor("iccSizeIsValid", profileSize == len(profile))
# Profile class must be 'input' or 'display'
profileClass = iccCharacteristics.findElementText('profileClass')
self.testFor("iccPermittedProfileClass", profileClass in [b'scnr',b'mntr'])
# List of tag signatures may not contain "AToB0Tag", which indicates
# an N-component LUT based profile, which is not allowed in JP2
# Step 1: create list of all "tag" elements
tagSignatureElements = iccCharacteristics.findall("tag")
# Step 2: create list of all tag signatures and fill it
tagSignatures=[]
for i in range(len(tagSignatureElements)):
tagSignatures.append(tagSignatureElements[i].text)
# Step 3: verify non-existence of "AToB0Tag"
self.testFor("iccNoLUTBasedProfile", b'A2B0' not in tagSignatures)
elif meth == 3:
# ICC profile embedded using "Any ICC" method. Belongs to Part 2 of the
# standard (JPX), so if we get here by definition this is not valid JP2!
profile = self.boxContents[3:length]
# Extract ICC profile properties as element object
tests, iccCharacteristics = BoxValidator('icc', profile).validate() #self.getICCCharacteristics(profile)
self.characteristics.append(iccCharacteristics)
def validate_icc(self):
# Extracts characteristics (property-value pairs) of ICC profile
# Note that although values are stored in 'text' property of sub-elements,
# they may have a type other than 'text' (binary string, integers, lists)
# This means that some post-processing (conversion to text) is needed to
# write these property-value pairs to XML
# Profile header properties (note: incomplete at this stage!)
# Size in bytes
profileSize=bc.bytesToUInt(self.boxContents[0:4])
self.addCharacteristic("profileSize",profileSize)
# Preferred CMM type
preferredCMMType=self.boxContents[4:8]
self.addCharacteristic("preferredCMMType",preferredCMMType)
# Profile version: major revision
profileMajorRevision=bc.bytesToUnsignedChar(self.boxContents[8:9])
# Profile version: minor revision
profileMinorRevisionByte=bc.bytesToUnsignedChar(self.boxContents[9:10])
# Minor revision: first 4 bits of profileMinorRevisionByte
# (Shift bits 4 positions to right, logical shift not arithemetic shift!)
profileMinorRevision=profileMinorRevisionByte >> 4
# Bug fix revision: last 4 bits of profileMinorRevisionByte
# (apply bit mask of 00001111 = 15)
profileBugFixRevision=profileMinorRevisionByte & 15
# Construct text string with profile version
profileVersion="%s.%s.%s" % (profileMajorRevision, profileMinorRevision, profileBugFixRevision)
self.addCharacteristic("profileVersion",profileVersion)
# Bytes 10 and 11 are reserved an set to zero(ignored here)
# Profile class (or device class)
profileClass=self.boxContents[12:16]
self.addCharacteristic("profileClass",profileClass)
# Colour space
colourSpace=self.boxContents[16:20]
self.addCharacteristic("colourSpace",colourSpace)
# Profile connection space
profileConnectionSpace=self.boxContents[20:24]
self.addCharacteristic("profileConnectionSpace",profileConnectionSpace)
# Date and time fields
year=bc.bytesToUShortInt(self.boxContents[24:26])
month=bc.bytesToUnsignedChar(self.boxContents[27:28])
day=bc.bytesToUnsignedChar(self.boxContents[29:30])
hour=bc.bytesToUnsignedChar(self.boxContents[31:32])
minute=bc.bytesToUnsignedChar(self.boxContents[33:34])
second=bc.bytesToUnsignedChar(self.boxContents[35:36])
dateString="%d/%02d/%02d" % (year, month, day)
timeString="%02d:%02d:%02d" % (hour, minute, second)
dateTimeString="%s, %s" % (dateString, timeString)
self.addCharacteristic("dateTimeString",dateTimeString)
# Profile signature
profileSignature=self.boxContents[36:40]
self.addCharacteristic("profileSignature",profileSignature)
# Primary platform
primaryPlatform=self.boxContents[40:44]
self.addCharacteristic("primaryPlatform",primaryPlatform)
# Profile flags (bytes 44-47; only first byte read here as remaing bytes
# don't contain any meaningful information)
profileFlags=bc.bytesToUnsignedChar(self.boxContents[44:45])
# Embedded profile (0 if not embedded, 1 if embedded in file)
embeddedProfile=self._getBitValue(profileFlags,1)
self.addCharacteristic("embeddedProfile",embeddedProfile)
# Profile cannot be used independently from embedded colour data
# (1 if true, 0 if false)
profileCannotBeUsedIndependently=self._getBitValue(profileFlags,2)
self.addCharacteristic("profileCannotBeUsedIndependently",profileCannotBeUsedIndependently)
# Device manufacturer
deviceManufacturer=self.boxContents[48:52]
self.addCharacteristic("deviceManufacturer",deviceManufacturer)
# Device model
deviceModel=self.boxContents[52:56]
self.addCharacteristic("deviceModel",deviceModel)
# Device attributes (bytes 56-63; only first byte read here as remaing bytes
# don't contain any meaningful information)
deviceAttributes=bc.bytesToUnsignedChar(self.boxContents[56:57])
# Transparency (1 = transparent; 0 = reflective)
transparency=self._getBitValue(deviceAttributes,1)
self.addCharacteristic("transparency",transparency)
# Glossiness (1 = matte; 0 = glossy)
glossiness=self._getBitValue(deviceAttributes,2)
self.addCharacteristic("glossiness",glossiness)
# Media polarity (1 = negative; 0 = positive)
polarity=self._getBitValue(deviceAttributes,3)
self.addCharacteristic("polarity",polarity)
# Media colour (1 = black & white; 0 = colour)
colour=self._getBitValue(deviceAttributes,4)
self.addCharacteristic("colour",colour)
# Rendering intent (bytes 64-67, only least-significant 2 bytes used)
renderingIntent=bc.bytesToUShortInt(self.boxContents[66:68])
self.addCharacteristic("renderingIntent",renderingIntent)
# Profile connection space illuminants (X, Y, Z)
connectionSpaceIlluminantX=round(bc.bytesToUInt(self.boxContents[68:72])/65536,4)
self.addCharacteristic("connectionSpaceIlluminantX",connectionSpaceIlluminantX)
connectionSpaceIlluminantY=round(bc.bytesToUInt(self.boxContents[72:76])/65536,4)
self.addCharacteristic("connectionSpaceIlluminantY",connectionSpaceIlluminantY)
connectionSpaceIlluminantZ=round(bc.bytesToUInt(self.boxContents[76:80])/65536,4)
self.addCharacteristic("connectionSpaceIlluminantZ",connectionSpaceIlluminantZ)
# Profile creator
profileCreator=self.boxContents[80:84]
self.addCharacteristic("profileCreator",profileCreator)
# Profile ID (as hexadecimal string)
profileID=bc.bytesToHex(self.boxContents[84:100])
self.addCharacteristic("profileID",profileID)
# Number of tags (tag count)
tagCount=bc.bytesToUInt(self.boxContents[128:132])
# List of tag signatures, offsets and sizes
# All local to this function; all property exports through "characteristics"
# element object!
tagSignatures=[]
tagOffsets=[]
tagSizes=[]
# Offset of start of first tag
tagStart=132
for i in range(tagCount):
# Extract tag signature (as binary string) for each entry
tagSignature=self.boxContents[tagStart:tagStart+4]
tagOffset=bc.bytesToUInt(self.boxContents[tagStart+4:tagStart+8])
tagSize=bc.bytesToUInt(self.boxContents[tagStart+8:tagStart+12])
self.addCharacteristic("tag",tagSignature)
# Add to list
tagSignatures.append(tagSignature)
tagOffsets.append(tagOffset)
tagSizes.append(tagSize)
# Start offset of next tag
tagStart +=12
# Get profile description from profile description tag
# The following code could go wrong in case tagSignatures doesn't
# contain description fields (e.g. if profile is corrupted); try block
# will capture any such errors.
try:
i = tagSignatures.index(b'desc')
descStartOffset=tagOffsets[i]
descSize=tagSizes[i]
descTag=self.boxContents[descStartOffset:descStartOffset+descSize]
# Note that description of this tag is missing from recent versions of
# standard; following code based on older version:
# ICC.1:2001-04 File Format for Color Profiles [REVISION of ICC.1:1998-09]
# Length of description (including terminating null character)
descriptionLength=bc.bytesToUInt(descTag[8:12])
# Description as binary string (excluding terminating null char)
description=descTag[12:12+descriptionLength-1]
except:
description=""
self.addCharacteristic("description",description)
def validate_paletteBox(self):
# Palette box (ISO/IEC 15444-1 Section I.5.3.4)
# Optional box that specifies a palette
# Number of entries in the table (each field is 2 bytes)
nE = bc.bytesToUShortInt(self.boxContents[0:2])
self.addCharacteristic("nE",nE)
# nE within range 1-1024
self.testFor("nEIsValid", 1 <= nE <= 1024)
# Number of palette columns
nPC=bc.bytesToUnsignedChar(self.boxContents[2:3])
self.addCharacteristic("nPC",nPC)
# nPC within range 1-255
self.testFor("nPCIsValid", 1 <= nPC <= 255)
# Following parameters are repeated for each column
for i in range(nPC):
# Bit depth of values created by column i
b = bc.bytesToUnsignedChar(self.boxContents[3+i:4+i])
# Most significant bit indicates whether palette column is signed (1)
# or unsigned (0). Extracted by applying bit mask of 10000000 (=128)
bSign = self._getBitValue(b, 1)
self.addCharacteristic("bSign",bSign)
# Remaining bits indicate (bit depth - 1). Extracted by applying bit mask of
# 01111111 (=127)
bDepth=(b & 127) + 1
self.addCharacteristic("bDepth",bDepth)
# Bits depth field is valid if bDepth in range 1-38 (including limits)
self.testFor("bDepthIsValid", 1 <= bDepth <= 38)
# If bDepth is not a multiple of 8 bits add padding bits
# E.g. if bDepth is 10, bDepthPadded will be 16 bits, and
# C value will be stored in low 10 bits of 16-bit field
bDepthPadded=math.ceil(bDepth/8)*8
bytesPadded=int(bDepthPadded/8)
# Start offset of cP entries for this column
offset=nPC+3+i*(nE*bytesPadded)
for j in range(nE):
# Get bytes for this entry
cPAsBytes=self.boxContents[offset:offset+bytesPadded]
# Convert to integer (cP could be *any* length so we cannot rely
# on struct.unpack!)
cP=bc.bytesToInteger(cPAsBytes)
self.addCharacteristic("cP",cP)
offset += bytesPadded
def validate_componentMappingBox(self):
# Component mapping box (ISO/IEC 15444-1 Section I.5.3.5)
# This box defines how image channels are identified from actual components
# Determine number of channels from box length
numberOfChannels=int(len(self.boxContents)/4)
offset=0
# Loop through box contents and validate fields
for i in range(numberOfChannels):
# Component index
cMP=bc.bytesToUShortInt(self.boxContents[offset:offset+2])
self.addCharacteristic("cMP",cMP)
# Allowed range: 0 - 16384
self.testFor("cMPIsValid", 0 <= cMP <= 16384)
# Specifies how channel is generated from codestream component
mTyp = bc.bytesToUnsignedChar(self.boxContents[offset+2:offset+3])
self.addCharacteristic("mTyp",mTyp)
# Allowed range: 0 - 1
self.testFor("mTypIsValid", 0 <= mTyp <= 1)
# Palette component index
pCol = bc.bytesToUnsignedChar(self.boxContents[offset+3:offset+4])
self.addCharacteristic("pCol",pCol)
# If mTyp equals 0, pCol should be 0 as well
if mTyp ==0:
pColIsValid = pCol ==0
else:
pColIsValid=True
self.testFor("pColIsValid", pColIsValid)
offset += 4
def validate_channelDefinitionBox(self):
# Channel definition box (ISO/IEC 15444-1 Section I.5.3.6)
# This box specifies the meaning of the samples in each channel in the image
# Number of channel descriptions (short integer)
n = bc.bytesToUShortInt(self.boxContents[0:2])
self.addCharacteristic("n",n)
# Allowed range: 1 - 65535
self.testFor("nIsValid", 1 <= n <= 65535)
# Each channel description is made up of three 2-byte fields, so check
# if size of box contents matches n
boxLengthIsValid = len(self.boxContents) - 2 == n * 6
self.testFor("boxLengthIsValid",boxLengthIsValid)
# Loop through box contents and validate fields
offset = 2
for i in range(n):
# Channel index
cN=bc.bytesToUShortInt(self.boxContents[offset:offset+2])
self.addCharacteristic("cN",cN)
# Allowed range: 0 - 65535
self.testFor("cNIsValid", 0 <= cN <= 65535)
# Channel type
cTyp = bc.bytesToUShortInt(self.boxContents[offset+2:offset+4])
self.addCharacteristic("cTyp",cTyp)
# Allowed range: 0 - 65535
self.testFor("cTypIsValid", 0 <= cTyp <= 65535)
# Channel Association
cAssoc = bc.bytesToUShortInt(self.boxContents[offset+4:offset+6])
self.addCharacteristic("cAssoc",cAssoc)
# Allowed range: 0 - 65535
self.testFor("cAssocIsValid", 0 <= cTyp <= 65535)
offset += 6
def validate_resolutionBox(self):
# Resolution box (superbox)(ISO/IEC 15444-1 Section I.5.3.7
# Specifies the capture and/or default display grid resolutions of
# the image.
# Marker tags/codes that identify all sub-boxes as hexadecimal strings
tagCaptureResolutionBox=b'\x72\x65\x73\x63'
tagDisplayResolutionBox=b'\x72\x65\x73\x64'
# List for storing box type identifiers
subBoxTypes=[]
noBytes = len(self.boxContents)
byteStart = 0
bytesTotal = 0
# Dummy value
boxLengthValue = 10
while byteStart < noBytes and boxLengthValue != 0:
boxLengthValue, boxType, byteEnd, subBoxContents = self._getBox(byteStart, noBytes)
# validate sub boxes
resultBox, characteristicsBox = BoxValidator(boxType, subBoxContents).validate()
byteStart = byteEnd
# Add to list of box types
subBoxTypes.append(boxType)
# Add analysis results to test results tree
self.tests.appendIfNotEmpty(resultBox)
# Add extracted characteristics to characteristics tree
self.characteristics.append(characteristicsBox)
# This box contains either one Capture Resolution box, one Default Display
# resolution box, or one of both
self.testFor("containsCaptureOrDisplayResolutionBox", tagCaptureResolutionBox in subBoxTypes or tagDisplayResolutionBox in subBoxTypes)
self.testFor("noMoreThanOneCaptureResolutionBox", subBoxTypes.count(tagCaptureResolutionBox) <= 1)
self.testFor("noMoreThanOneDisplayResolutionBox", subBoxTypes.count(tagDisplayResolutionBox) <= 1)
# Validator functions for boxes in Resolution box
def validate_captureResolutionBox(self):
# Capture Resolution Box (ISO/IEC 15444-1 Section I.5.3.7.1)
# Check box size, which should be 10 bytes
self.testFor("boxLengthIsValid", len(self.boxContents) == 10)
# Vertical / horizontal grid resolution numerators and denominators:
# all values within range 1-65535
# Vertical grid resolution numerator (2 byte integer)
vRcN = bc.bytesToUShortInt(self.boxContents[0:2])
self.addCharacteristic("vRcN", vRcN)
self.testFor("vRcNIsValid", 1 <= vRcN <= 65535)
# Vertical grid resolution denominator (2 byte integer)
vRcD = bc.bytesToUShortInt(self.boxContents[2:4])
self.addCharacteristic("vRcD", vRcD)
self.testFor("vRcDIsValid", 1 <= vRcD <= 65535)
# Horizontal grid resolution numerator (2 byte integer)
hRcN = bc.bytesToUShortInt(self.boxContents[4:6])
self.addCharacteristic("hRcN", hRcN)
self.testFor("hRcNIsValid", 1 <= hRcN <= 65535)
# Horizontal grid resolution denominator (2 byte integer)
hRcD = bc.bytesToUShortInt(self.boxContents[6:8])
self.addCharacteristic("hRcD", hRcD)
self.testFor("hRcDIsValid", 1 <= hRcD <= 65535)
# Vertical / horizontal grid resolution exponents:
# values within range -128-127
# Vertical grid resolution exponent (1 byte signed integer)
vRcE = bc.bytesToSignedChar(self.boxContents[8:9])
self.addCharacteristic("vRcE", vRcE)
self.testFor("vRcEIsValid", -128 <= vRcE <= 127)
# Horizontal grid resolution exponent (1 byte signed integer)
hRcE = bc.bytesToSignedChar(self.boxContents[9:10])
self.addCharacteristic("hRcE", hRcE)
self.testFor("hRcEIsValid", -128 <= hRcE <= 127)
# Include vertical and horizontal resolution values in pixels per meter
# and pixels per inch in output
vRescInPixelsPerMeter = (vRcN/vRcD) * (10**(vRcE))
self.addCharacteristic("vRescInPixelsPerMeter", round(vRescInPixelsPerMeter,2))
hRescInPixelsPerMeter = (hRcN/hRcD) * (10**(hRcE))
self.addCharacteristic("hRescInPixelsPerMeter", round(hRescInPixelsPerMeter,2))
vRescInPixelsPerInch = vRescInPixelsPerMeter * 25.4e-3
self.addCharacteristic("vRescInPixelsPerInch", round(vRescInPixelsPerInch,2))
hRescInPixelsPerInch = hRescInPixelsPerMeter * 25.4e-3
self.addCharacteristic("hRescInPixelsPerInch", round(hRescInPixelsPerInch,2))
def validate_displayResolutionBox(self):
# Default Display Resolution Box (ISO/IEC 15444-1 Section I.5.3.7.2)
# Check box size, which should be 10 bytes
self.testFor("boxLengthIsValid", len(self.boxContents) == 10)
# Vertical / horizontal grid resolution numerators and denominators:
# all values within range 1-65535
# Vertical grid resolution numerator (2 byte integer)
vRdN = bc.bytesToUShortInt(self.boxContents[0:2])
self.addCharacteristic("vRdN", vRdN)
self.testFor("vRdNIsValid", 1 <= vRdN <= 65535)
# Vertical grid resolution denominator (2 byte integer)
vRdD = bc.bytesToUShortInt(self.boxContents[2:4])
self.addCharacteristic("vRdD", vRdD)