-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCCR.Exif.TiffUtils.pas
1802 lines (1622 loc) · 59.5 KB
/
CCR.Exif.TiffUtils.pas
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
{**************************************************************************************}
{ }
{ CCR Exif - Delphi class library for reading and writing image metadata }
{ Version 1.5.3 }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 }
{ (the "License"); you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. See the License for the specific }
{ language governing rights and limitations under the License. }
{ }
{ The Original Code is CCR.Exif.TiffUtils.pas. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2009-2014 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
{$I CCR.Exif.inc}
unit CCR.Exif.TiffUtils;
interface
uses
Types, SysUtils, Classes, CCR.Exif.BaseUtils, CCR.Exif.StreamHelper;
type
EInvalidTiffData = class(ECCRExifException);
ETagAlreadyExists = class(EInvalidTiffData);
TTiffTagID = type Word;
{$Z2}
TTiffDataType = (tdByte = 1, tdAscii, tdWord, tdLongWord, tdLongWordFraction,
tdShortInt, tdUndefined, tdSmallInt, tdLongInt, tdLongIntFraction, tdSingle,
tdDouble, tdSubDirectory);
{$Z1}
TTiffDataTypes = set of TTiffDataType;
ITiffTag = interface;
TTiffTag = record const
HeaderSize = 12;
OffsetDataTypes = [tdWord, tdLongWord, {tdLongInt, }tdSubDirectory];
class function IsWellFormed(DataType: TTiffDataType; ElementCount: LongInt): Boolean; overload; static; {$IFDEF CanInline}inline;{$ENDIF}
class function IsWellFormed(const Tag: ITiffTag): Boolean; overload; static; {$IFDEF CanInline}inline;{$ENDIF}
class function MatchOffsetToByteCountID(OffsetTagID: TTiffTagID;
var ByteCountID: TTiffTagID): Boolean; static;
end;
PTiffTagInfo = ^TTiffTagInfo;
TTiffTagInfo = record
public
HeaderOffset, DataOffset: LongWord;
ID: TTiffTagID;
DataType: TTiffDataType;
ElementCount: LongInt;
function DataSize: Integer;
function IsWellFormed: Boolean; overload;{$IFDEF CanInline}inline;{$ENDIF}
end;
TTiffTagInfoDynArray = array of TTiffTagInfo;
TiffString = type AnsiString;
TTiffLongWordFraction = packed record
constructor Create(ANumerator: LongWord; ADenominator: LongWord = 1); overload;
constructor Create(const AQuotient: Currency); overload;
constructor CreateFromString(const AString: string);
class function CreateMissingOrInvalid: TTiffLongWordFraction; static;
function AsString: string; deprecated {$IFDEF DepCom}'Use ToString instead'{$ENDIF};
function MissingOrInvalid: Boolean;
function Quotient: Extended;
function ToString: string;
case Integer of
0: (Numerator, Denominator: LongWord);
1: (PackedValue: Int64);
end;
TTiffLongIntFraction = packed record
constructor Create(ANumerator: LongInt; ADenominator: LongInt = 1); overload;
constructor Create(const AQuotient: Currency); overload;
constructor CreateFromString(const AString: string);
class function CreateMissingOrInvalid: TTiffLongIntFraction; static;
function AsString: string; deprecated {$IFDEF DepCom}'Use ToString instead'{$ENDIF};
function MissingOrInvalid: Boolean;
function Quotient: Extended;
function ToString: string;
case Integer of
0: (Numerator, Denominator: LongInt);
1: (PackedValue: Int64);
end;
ITiffParser = interface;
ITiffDirectory = interface;
ITiffTag = interface(IMetadataBlock)
['{DC9C12D5-EFEF-4B59-9B02-89A757896CCA}']
function GetDataType: TTiffDataType;
function GetParent: ITiffDirectory;
function GetElementCount: LongInt;
function GetID: TTiffTagID;
function GetOriginalDataOffset: LongWord;
property DataType: TTiffDataType read GetDataType;
property ElementCount: LongInt read GetElementCount;
property ID: TTiffTagID read GetID;
property OldDataOffset: LongWord read GetOriginalDataOffset;
property Parent: ITiffDirectory read GetParent;
end;
IFoundTiffTag = interface(ITiffTag)
['{8258F43E-38E8-4FD9-A1D7-D3C42B38F043}']
function GetParser: ITiffParser;
property Parser: ITiffParser read GetParser;
end;
ITiffDirectoryEnumerator = interface
['{7E882310-28E7-4AF3-9978-27D1E5F36D09}']
function GetCurrent: ITiffTag;
function MoveNext: Boolean;
property Current: ITiffTag read GetCurrent;
end;
ITiffDirectory = interface //implemented by both the internal TFoundTiffDirectory below and TExifSection in CCR.Exif.pas
['{3DA5B982-CB8C-412A-8E5F-AD3A98CF345E}']
function GetEnumerator: ITiffDirectoryEnumerator;
function GetIndex: Integer;
function GetParent: ITiffDirectory;
function GetTagCount: Integer;
function FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean;
function TagExists(TagID: TTiffTagID; ValidDataTypes: TTiffDataTypes =
[Low(TTiffDataType)..High(TTiffDataType)]; MinElementCount: LongInt = 1;
MaxElementCount: LongInt = MaxLongInt): Boolean;
property Index: Integer read GetIndex;
property Parent: ITiffDirectory read GetParent;
property TagCount: Integer read GetTagCount;
end;
IFoundTiffDirectory = interface(ITiffDirectory)
['{A8B5DB5F-2084-437C-872D-0139DE7C3E54}']
function GetIndex: Integer;
function GetLoadErrors: TMetadataLoadErrors;
function GetParser: ITiffParser;
function GetTagInfo: TTiffTagInfoDynArray;
function IsLastDirectoryInFile: Boolean;
function IsExifThumbailDirectory: Boolean;
function TryLoadExifThumbnail(const Dest: IStreamPersist): Boolean;
property LoadErrors: TMetadataLoadErrors read GetLoadErrors;
property Parser: ITiffParser read GetParser;
property TagInfo: TTiffTagInfoDynArray read GetTagInfo;
end;
TTiffParserEnumerator = {$IFDEF NoRecEnumBug}record{$ELSE}class sealed{$ENDIF}
strict private
FCurrent: IFoundTiffDirectory;
FMaxPossibleOffset: Int64;
FNextIndex: Integer;
FNextOffset: LongInt;
FSource: ITiffParser;
public
constructor Create(const ASource: ITiffParser; const AMaxPossibleOffset: Int64;
const ANextOffset: LongInt);
function MoveNext: Boolean;
property Current: IFoundTiffDirectory read FCurrent;
end;
ITiffParser = interface
function GetBasePosition: Int64;
function GetEndianness: TEndianness;
function GetEnumerator: TTiffParserEnumerator;
function GetStream: TStream;
procedure LoadTagData(const TagInfo: TTiffTagInfo; var Buffer); overload;
function ParseSubDirectory(const OffsetTag: ITiffTag;
out Directory: IFoundTiffDirectory): Boolean; overload;
function ParseSubDirectory(const Parent: ITiffDirectory;
const OffsetTag: TTiffTagInfo; out Directory: IFoundTiffDirectory): Boolean; overload;
property BasePosition: Int64 read GetBasePosition;
property Endianness: TEndianness read GetEndianness;
property Stream: TStream read GetStream;
end;
ITiffRewriteCallback = interface;
TTiffDirectoryRewriter = class sealed
protected type
TTagToWrite = class abstract
strict private
FNewDataOffset: LongWord;
FInfo: TTiffTagInfo;
FParent: TTiffDirectoryRewriter;
protected
property Info: TTiffTagInfo read FInfo;
public
constructor Create(AParent: TTiffDirectoryRewriter; const AInfo: TTiffTagInfo); overload;
constructor Create(AParent: TTiffDirectoryRewriter; AID: TTiffTagID;
ADataType: TTiffDataType; AElementCount: LongInt; AOriginalDataOffset: LongWord = 0); overload;
function DataSize: Integer; inline;
procedure WriteData(Stream: TStream; Endianness: TEndianness); virtual; abstract;
property DataType: TTiffDataType read FInfo.DataType;
property ElementCount: LongInt read FInfo.ElementCount;
property ID: TTiffTagID read FInfo.ID;
property NewDataOffset: LongWord read FNewDataOffset write FNewDataOffset;
property OldDataOffset: LongWord read FInfo.DataOffset;
property Parent: TTiffDirectoryRewriter read FParent;
end;
TImageItem = record
ByteCount: 0..High(LongInt);
OldOffset, NewOffset: LongWord;
end;
TImageInfo = array of TImageItem;
strict private
FDoneInitialization: Boolean;
FImageInfo: TImageInfo;
FNewIFDOffset: LongWord;
FRewriteSource: Boolean;
FSource: ITiffDirectory;
FSourceInfo: TTiffTagInfoDynArray;
FSourceParser: ITiffParser;
FTagsToWrite: TObjectList;
procedure AddTag(Tag: TTagToWrite); overload;
function FindTagIndex(AID: TTiffTagID; out Index: Integer): Boolean;
function GetTag(Index: Integer): TTagToWrite;
function GetTagCount: Integer;
protected
constructor Create(const Source: ITiffDirectory; const Callback: ITiffRewriteCallback);
function FindTagToWrite(ID: TTiffTagID; var Tag: TTagToWrite): Boolean;
function HasImageData: Boolean; inline;
function ProtectMakerNote(var MakerNoteTag: TTagToWrite): Boolean; //looks for the ttExifOffset sub-dir, then ttMakerNote under that, checking the data type and size
procedure InitializeImageInfo(const Offsets, ByteCounts: array of LongWord);
procedure InitializeNewOffsets(var NextOffset: LongWord; ProtectedTag: TTagToWrite);
procedure Write(AStream: TStream; const ABasePosition: Int64;
AEndianness: TEndianness; ANextIFDOffset: LongWord);
property ImageInfo: TImageInfo read FImageInfo;
property NewIFDOffset: LongWord read FNewIFDOffset write FNewIFDOffset;
property RewriteSource: Boolean read FRewriteSource;
property TagCount: Integer read GetTagCount;
property Tags[Index: Integer]: TTagToWrite read GetTag;
public
destructor Destroy; override;
procedure AddTag(ID: TTiffTagID; const DataSource: IStreamPersist;
DataType: TTiffDataType = tdUndefined); overload;
procedure AddTag(const Source: ITiffTag); overload;
procedure AddSubDirectory(OffsetID: TTiffTagID; const SubDirectory: ITiffDirectory;
const Callback: ITiffRewriteCallback = nil);
procedure IgnoreDirectory;
property Source: ITiffDirectory read FSource;
end;
ITiffRewriteCallback = interface
['{55D2E445-1E18-4887-A004-947F16B696D1}']
procedure AddNewTags(Rewriter: TTiffDirectoryRewriter);
procedure RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID;
DataType: TTiffDataType; var Rewrite: Boolean);
end;
TSimpleTiffRewriteCallbackImpl = class(TAggregatedObject, ITiffRewriteCallback)
strict private //Internal helper class for TIPTCData and TXMPPacket that
FMetadataTagID: TTiffTagID; //standardises the implementation of ITiffRewriteCallback.
function GetOwner: IStreamPersistEx; inline;
protected
{ ITiffRewriteCallback }
procedure AddNewTags(Rewriter: TTiffDirectoryRewriter);
procedure RewritingOldTag(const Source: ITiffDirectory; TagID: TTiffTagID;
DataType: TTiffDataType; var Rewrite: Boolean);
public
constructor Create(const AOwner: IStreamPersistEx; AMetadataTagID: TTiffTagID);
property Owner: IStreamPersistEx read GetOwner;
end;
const
TiffElementSizes: array[TTiffDataType] of Integer = (
1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4);
function HasTiffHeader(Stream: TStream; var Endianness: TEndianness;
MoveOnSuccess: Boolean = False): Boolean; overload;
function HasTiffHeader(Stream: TStream; MoveOnSuccess: Boolean = False): Boolean; overload; inline;
function ParseTiff(Stream: TStream; StreamOwnership: TStreamOwnership = soReference): ITiffParser; overload;
function ParseTiff(const FileName: string): ITiffParser; overload; inline;
function ParseTiffDirectory(Stream: TStream; Endianness: TEndianness;
const BasePosition, Offset, InternalOffset: Int64): IFoundTiffDirectory;
procedure RewriteTiff(InStream, OutStream: TStream; const Callback: ITiffRewriteCallback);
procedure WriteTiffHeader(Stream: TStream; Endianness: TEndianness;
FirstDirectoryOffset: LongWord = 8);
implementation
uses Math, RTLConsts, CCR.Exif.Consts, CCR.Exif.TagIDs;
function TryLoadJpegImageFromStream(const AJpegImage: IStreamPersist; AStream: TStream): Boolean;
var
JpegSize: Int64;
Temp: TMemoryStream;
begin
try
JpegSize := GetJPEGDataSize(AStream);
if JpegSize = (AStream.Size - AStream.Position) then
AJpegImage.LoadFromStream(AStream)
else
begin
Temp := TMemoryStream.Create;
try
Temp.Size := JpegSize;
AStream.ReadBuffer(Temp.Memory^, JpegSize);
AJpegImage.LoadFromStream(Temp);
finally
Temp.Free;
end;
end;
Result := True;
except
on Exception do Result := False;
end;
end;
type
TFoundTiffDirectory = class;
TFoundTiffTag = class(TMetadataBlock, ITiffTag)
strict private
FParent: TFoundTiffDirectory;
FParentIntf: ITiffDirectory; //need a 'hard' intf ref to ensure the parent is kept alive
FSourcePtr: ^TTiffTagInfo;
protected
function GetDataType: TTiffDataType;
function GetElementCount: LongInt;
function GetOriginalDataOffset: LongWord;
function GetID: TTiffTagID;
function GetParent: ITiffDirectory;
function HasIPTCBlockID: Boolean; override;
function HasXMPBlockID: Boolean; override;
public
constructor Create(AParent: TFoundTiffDirectory; AIndex: Integer); overload;
constructor Create(AID: TTiffTagID; ADataType: TTiffDataType;
const ADataSource: IStreamPersist); overload;
destructor Destroy; override;
property DataType: TTiffDataType read GetDataType;
property ElementCount: LongInt read GetElementCount;
property ID: TTiffTagID read GetID;
property Parent: TFoundTiffDirectory read FParent;
end;
TFoundTiffDirectoryEnumerator = class(TInterfacedObject, ITiffDirectoryEnumerator)
strict private
FCurrentIndex: Integer;
FSource: TFoundTiffDirectory;
protected
function GetCurrent: ITiffTag;
function MoveNext: Boolean;
public
constructor Create(Source: TFoundTiffDirectory);
end;
TFoundTiffDirectory = class(TInterfacedObject, ITiffDirectory, IFoundTiffDirectory)
strict private
FIndex: Integer;
FLoadErrors: TMetadataLoadErrors;
FParent: ITiffDirectory;
FParser: ITiffParser;
FTags: TTiffTagInfoDynArray;
protected
FMoreToFollow: Boolean;
constructor Create(const AParser: ITiffParser; const AParent: ITiffDirectory; AIndex: Integer;
const Tags: TTiffTagInfoDynArray; const LoadErrors: TMetadataLoadErrors); overload;
function GetEnumerator: ITiffDirectoryEnumerator;
function GetIndex: Integer;
function GetLoadErrors: TMetadataLoadErrors;
function GetParent: ITiffDirectory;
function GetParser: ITiffParser;
function LoadSubDirectory(OffsetTagID: TTiffTagID): ITiffDirectory;
function GetTagCount: Integer;
function GetTagInfo: TTiffTagInfoDynArray;
function FindTag(TagID: TTiffTagID; out Index: Integer): Boolean; overload; inline;
function FindTag(TagID: TTiffTagID; out ParsedTag: ITiffTag): Boolean; overload;
function IndexOfTag(TagID: TTiffTagID): Integer;
function IsExifThumbailDirectory: Boolean;
function IsLastDirectoryInFile: Boolean; inline;
function TagExists(TagID: TTiffTagID; ValidDataTypes: TTiffDataTypes =
[Low(TTiffDataType)..High(TTiffDataType)]; MinElementCount: LongInt = 1;
MaxElementCount: LongInt = MaxLongInt): Boolean;
function TryLoadExifThumbnail(Dest: TStream): Boolean; overload;
function TryLoadExifThumbnail(const Dest: IStreamPersist): Boolean; overload;
public
constructor Create(const AParser: ITiffParser; const AParent: ITiffDirectory;
AIndex: Integer; const AOffset: Int64; const AInternalOffset: Int64 = 0); overload;
class function TryCreate(const AParser: ITiffParser; const AParent: ITiffDirectory;
AIndex: Integer; const AOffset: Int64; out Instance: IFoundTiffDirectory): Boolean; static;
property Parser: ITiffParser read FParser;
property TagInfo: TTiffTagInfoDynArray read FTags;
end;
TTiffParser = class(TInterfacedObject, ITiffParser)
strict private
FBasePosition, FMaxOffsetValue: Int64;
FEndianness: TEndianness;
FFirstDirOffset: LongInt;
FStream: TStream;
FStreamOwnership: TStreamOwnership;
protected
function GetBasePosition: Int64;
function GetEndianness: TEndianness;
function GetEnumerator: TTiffParserEnumerator;
function GetStream: TStream;
procedure LoadTagData(const TagInfo: TTiffTagInfo; var Buffer); overload;
function ParseSubDirectory(const OffsetTag: ITiffTag;
out Directory: IFoundTiffDirectory): Boolean; overload;
function ParseSubDirectory(const Parent: ITiffDirectory; const OffsetTag: TTiffTagInfo;
out Directory: IFoundTiffDirectory): Boolean; overload;
public
constructor Create(AStream: TStream; AStreamOwnership: TStreamOwnership); overload;
constructor Create(AStream: TStream; const ABasePosition: Int64;
AEndianness: TEndianness); overload;
destructor Destroy; override;
property BasePosition: Int64 read FBasePosition;
property Endianness: TEndianness read FEndianness;
property Stream: TStream read FStream;
end;
TInternaTiffTagToWrite = class(TTiffDirectoryRewriter.TTagToWrite)
strict private
FParser: ITiffParser;
strict protected
Kind: (itNormal, itImageOffsets, itImageByteCounts);
public
constructor Create(AParent: TTiffDirectoryRewriter; const AParser: ITiffParser;
const ATagInfo: TTiffTagInfo);
procedure WriteData(Stream: TStream; Endianness: TEndianness); override;
property Info;
property Parser: ITiffParser read FParser;
end;
TExternalTiffTagToWrite = class(TTiffDirectoryRewriter.TTagToWrite)
strict protected
FDataSize: Integer;
FTag: ITiffTag;
public
constructor Create(AOwner: TTiffDirectoryRewriter; const ATag: ITiffTag); overload;
constructor Create(AOwner: TTiffDirectoryRewriter; AID: TTiffTagID;
ADataType: TTiffDataType; const ADataSource: IStreamPersist); overload;
procedure WriteData(Stream: TStream; Endianness: TEndianness); override;
property Source: ITiffTag read FTag;
end;
TTiffSubDirToWrite = class(TTiffDirectoryRewriter.TTagToWrite)
strict private
FDirectory: TTiffDirectoryRewriter;
public
constructor Create(AOwner: TTiffDirectoryRewriter; AOffsetID: TTiffTagID;
ADirectory: TTiffDirectoryRewriter);
destructor Destroy; override;
procedure WriteData(Stream: TStream; Endianness: TEndianness); override;
property Directory: TTiffDirectoryRewriter read FDirectory;
end;
{ TTiffTag }
{$Q-}
class function TTiffTag.IsWellFormed(DataType: TTiffDataType; ElementCount: LongInt): Boolean;
begin
case Ord(DataType) of
Ord(Low(DataType))..Ord(High(DataType)):
Result := (LongInt(ElementCount * TiffElementSizes[DataType]) >= 0);
else Result := False;
end;
end;
{$IFDEF OverflowCheckingOn}{$Q+}{$ENDIF}
class function TTiffTag.IsWellFormed(const Tag: ITiffTag): Boolean;
begin
Result := IsWellFormed(Tag.DataType, Tag.ElementCount);
end;
class function TTiffTag.MatchOffsetToByteCountID(OffsetTagID: TTiffTagID;
var ByteCountID: TTiffTagID): Boolean;
begin
Result := True;
case OffsetTagID of
ttStripOffsets: ByteCountID := ttStripByteCounts;
ttTileOffsets: ByteCountID := ttTileOffsets;
ttThumbnailOffset: ByteCountID := ttThumbnailSize;
else Result := False;
end;
end;
{ TTiffTagInfo }
function TTiffTagInfo.DataSize: Integer;
begin
if IsWellFormed then
Result := ElementCount * TiffElementSizes[DataType]
else
Result := 0;
end;
function TTiffTagInfo.IsWellFormed: Boolean;
begin
Result := TTiffTag.IsWellFormed(DataType, ElementCount);
end;
{ TTiffLongXXXFraction }
function GCD(A, B: Int64): Int64;
var
Temp: Int64;
begin
while B <> 0 do
begin
Temp := B;
B := A mod B;
A := Temp;
end;
Result := A;
end;
procedure CurrencyToFraction(const Source: Currency; var N, D: Int64);
var
Factor: Int64;
begin
N := Trunc(Source * 10000);
D := 10000;
Factor := GCD(N, D);
N := N div Factor;
D := D div Factor;
end;
constructor TTiffLongIntFraction.Create(ANumerator, ADenominator: LongInt);
begin
Numerator := ANumerator;
Denominator := ADenominator;
end;
constructor TTiffLongIntFraction.Create(const AQuotient: Currency);
var
N, D: Int64;
begin
CurrencyToFraction(AQuotient, N, D);
{$RANGECHECKS ON}
Numerator := N;
Denominator := D;
{$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF}
end;
constructor TTiffLongIntFraction.CreateFromString(const AString: string);
var
DivSignPos: Integer;
Quotient: Currency;
Valid: Boolean;
begin
DivSignPos := Pos('/', AString);
if DivSignPos <> 0 then
Valid := TryStrToInt(Copy(AString, 1, DivSignPos - 1), Numerator) and
TryStrToInt(Copy(AString, DivSignPos + 1, MaxInt), Denominator)
else
begin
Valid := TryStrToCurr(AString, Quotient);
if Valid then
try
Create(Quotient);
except
on ERangeError do Valid := False;
end;
end;
if not Valid then
PackedValue := 0;
end;
class function TTiffLongIntFraction.CreateMissingOrInvalid: TTiffLongIntFraction;
begin
Result.Numerator := 0;
Result.Denominator := 0;
end;
function TTiffLongIntFraction.AsString: string;
begin
Result := ToString;
end;
function TTiffLongIntFraction.MissingOrInvalid: Boolean;
begin
Result := (Denominator = 0);
end;
function TTiffLongIntFraction.Quotient: Extended;
begin
if MissingOrInvalid then
Result := 0
else
Result := Numerator / Denominator
end;
function TTiffLongIntFraction.ToString: string;
begin
if MissingOrInvalid then
Result := ''
else if Denominator = 1 then
Result := IntToStr(Numerator)
else
FmtStr(Result, '%d/%d', [Numerator, Denominator]);
end;
function TryStrToLongWord(const S: string; var Value: LongWord): Boolean;
var
Int64Value: Int64;
begin
Result := TryStrToInt64(S, Int64Value) and (Int64Value >= 0) and
(Int64Value <= High(Value));
if Result then Value := LongWord(Int64Value);
end;
constructor TTiffLongWordFraction.Create(ANumerator: LongWord; ADenominator: LongWord);
begin
Numerator := ANumerator;
Denominator := ADenominator;
end;
constructor TTiffLongWordFraction.Create(const AQuotient: Currency);
var
N, D: Int64;
begin
CurrencyToFraction(AQuotient, N, D);
{$RANGECHECKS ON}
Numerator := N;
Denominator := D;
{$IFDEF RangeCheckingOff}{$RANGECHECKS OFF}{$ENDIF}
end;
constructor TTiffLongWordFraction.CreateFromString(const AString: string);
var
DivSignPos: Integer;
Quotient: Currency;
Valid: Boolean;
begin
DivSignPos := Pos('/', AString);
if DivSignPos <> 0 then
Valid := TryStrToLongWord(Copy(AString, 1, DivSignPos - 1), Numerator) and
TryStrToLongWord(Copy(AString, DivSignPos + 1, MaxInt), Denominator)
else
begin
Valid := TryStrToCurr(AString, Quotient);
if Valid then
try
Create(Quotient);
except
on ERangeError do Valid := False;
end;
end;
if not Valid then
PackedValue := 0;
end;
class function TTiffLongWordFraction.CreateMissingOrInvalid: TTiffLongWordFraction;
begin
Result.Numerator := 0;
Result.Denominator := 0;
end;
function TTiffLongWordFraction.AsString: string;
begin
Result := ToString;
end;
function TTiffLongWordFraction.MissingOrInvalid: Boolean;
begin
Result := (Denominator = 0);
end;
function TTiffLongWordFraction.Quotient: Extended;
begin
if MissingOrInvalid then
Result := 0
else
Result := Numerator / Denominator
end;
function TTiffLongWordFraction.ToString: string;
begin
if MissingOrInvalid then
Result := ''
else if Denominator = 1 then
Result := IntToStr(Numerator)
else
FmtStr(Result, '%d/%d', [Numerator, Denominator]);
end;
{ TIFF parsing routines }
function HasTiffHeader(Stream: TStream; var Endianness: TEndianness;
MoveOnSuccess: Boolean = False): Boolean; overload;
var
Buffer: array[0..1] of Word;
BytesRead: Integer;
begin
Result := False;
BytesRead := Stream.Read(Buffer, SizeOf(Buffer));
if BytesRead = SizeOf(Buffer) then
case Buffer[0] of
TiffSmallEndianCode, TiffBigEndianCode: //accept small endian marker when meant big endian and vice versa
case Buffer[1] of
TiffMagicNum:
begin
Endianness := SmallEndian;
Result := True;
end;
TiffMagicNumBigEndian:
begin
Endianness := BigEndian;
Result := True;
end;
end;
end;
if not Result or not MoveOnSuccess then
Stream.Seek(-BytesRead, soCurrent);
end;
function HasTiffHeader(Stream: TStream; MoveOnSuccess: Boolean = False): Boolean; overload;
var
Endianness: TEndianness;
begin
Result := HasTiffHeader(Stream, Endianness, MoveOnSuccess)
end;
{
LoadTiffDirectory - sanity checking:
- We check the reported tag count is theoretically possible up front.
- Data offsets are validated.
- Two bad tag headers in a row, and any further parsing is aborted.
- General aim is to avoid an exception being raised. This is because it becomes
annoying in general use otherwise, Exif data in the wild frequently being badly
formed in some fashion...
}
function LoadTiffDirectory(Stream: TStream; Endianness: TEndianness;
const BasePosition, Offset, InternalOffset: Int64;
out LoadErrors: TMetadataLoadErrors): TTiffTagInfoDynArray; overload;
var
I, TagCount: Integer;
MaxTagCount, StartPos, StreamSize, Offset64: Int64;
begin
LoadErrors := [];
Result := nil;
StartPos := BasePosition + Offset;
StreamSize := Stream.Seek(0, soEnd);
if (StartPos < 0) or (StartPos + 2 > StreamSize) then
begin
LoadErrors := [leBadOffset];
Exit;
end;
MaxTagCount := (StreamSize - StartPos - 2) div TTiffTag.HeaderSize;
Stream.Position := StartPos;
TagCount := Stream.ReadWord(Endianness);
if TagCount > MaxTagCount then
begin
TagCount := MaxTagCount;
Include(LoadErrors, leBadTagCount);
end;
SetLength(Result, TagCount);
for I := 0 to TagCount - 1 do
begin
Result[I].HeaderOffset := Stream.Position - BasePosition;
Result[I].ID := Stream.ReadWord(Endianness);
Word(Result[I].DataType) := Stream.ReadWord(Endianness);
Result[I].ElementCount := Stream.ReadLongInt(Endianness);
if Result[I].DataSize > 4 then //DataSize will validate DataType for us
begin
Offset64 := Stream.ReadLongWord(Endianness) + InternalOffset;
if (Offset64 < 8) or (Offset64 + BasePosition < 0) or
(Offset64 + Result[I].DataSize + BasePosition > StreamSize) then
Result[I].ElementCount := -1
else
Result[I].DataOffset := Offset64;
end
else
begin
Result[I].DataOffset := Result[I].HeaderOffset + 8;
Stream.Seek(4, soCurrent);
end;
if not Result[I].IsWellFormed then
if (I = 0) or Result[I - 1].IsWellFormed then
begin
Include(LoadErrors, leBadTagHeader);
if (I = 0) and (leBadTagCount in LoadErrors) then
begin
Result := nil;
Exit;
end;
end
else
begin
Include(LoadErrors, leBadTagCount);
SetLength(Result, I);
Exit;
end;
end;
end;
function LoadTiffDirectory(const Parser: ITiffParser; const Offset: Int64;
out LoadErrors: TMetadataLoadErrors): TTiffTagInfoDynArray; overload; inline;
begin
Result := LoadTiffDirectory(Parser.Stream, Parser.Endianness, Parser.BasePosition,
Offset, 0, LoadErrors);
end;
function InitLoadOffsetArray(DataType: TTiffDataType; ElementCount: LongInt;
out ArrayResult: TLongWordDynArray): Boolean; inline;
begin
Assert((ElementCount >= 0) and (DataType in TTiffTag.OffsetDataTypes));
SetLength(ArrayResult, ElementCount);
Result := (ArrayResult <> nil);
end;
function LoadOffsetArray(const Source: ITiffParser;
const TagInfo: TTiffTagInfo): TLongWordDynArray; overload;
var
WordArray: TWordDynArray;
I: Integer;
begin
if not InitLoadOffsetArray(TagInfo.DataType, TagInfo.ElementCount, Result) then Exit;
if TagInfo.DataType = tdWord then
begin
SetLength(WordArray, TagInfo.ElementCount);
Source.LoadTagData(TagInfo, WordArray[0]);
for I := 0 to TagInfo.ElementCount - 1 do
Result[I] := WordArray[I];
end
else
Source.LoadTagData(TagInfo, Result[0]);
end;
function LoadOffsetArray(const Tag: ITiffTag): TLongWordDynArray; overload;
var
DataPtr: PWordArray;
I: LongInt;
begin
if not InitLoadOffsetArray(Tag.DataType, Tag.ElementCount, Result) then Exit;
DataPtr := Tag.Data.Memory;
if Tag.DataType = tdWord then
for I := 0 to High(Result) do
Result[I] := DataPtr[I]
else
Move(DataPtr[0], Result[0], Length(Result) * 4);
end;
function SeekToExifThumbnail(const Parser: ITiffParser;
const OffsetTag: TTiffTagInfo): Boolean;
begin
Result := False;
if not (OffsetTag.DataType in TTiffTag.OffsetDataTypes) or
(OffsetTag.ElementCount <> 1) then Exit;
Parser.Stream.Position := Parser.BasePosition + LoadOffsetArray(Parser, OffsetTag)[0];
if HasJPEGHeader(Parser.Stream) then Result := True;
end;
procedure WriteTiffTagData(DataType: TTiffDataType; ElementCount: Longint;
DataPtr: Pointer; Dest: TStream; Endianness: TEndianness);
var
I, DataSize: Integer;
begin
DataSize := TiffElementSizes[DataType] * ElementCount;
if DataType = tdDouble then
for I := 0 to ElementCount - 1 do
Dest.WriteDouble(PDoubleArray(DataPtr)[I], Endianness)
else
case TiffElementSizes[DataType] of
1: Dest.WriteBuffer(DataPtr^, ElementCount);
2: for I := 0 to ElementCount - 1 do
Dest.WriteWord(PWordArray(DataPtr)[I], Endianness);
else
for I := 0 to DataSize div 4 - 1 do
Dest.WriteLongWord(PLongWordArray(DataPtr)[I], Endianness)
end;
for I := 3 downto DataSize do
Dest.WriteByte(0);
end;
{ TFoundTiffTag }
constructor TFoundTiffTag.Create(AParent: TFoundTiffDirectory; AIndex: Integer);
begin
Assert((AParent <> nil) and (AIndex >= 0));
inherited Create;
FParent := AParent;
FParentIntf := AParent;
FSourcePtr := @AParent.TagInfo[AIndex];
Data.SetSize(FSourcePtr.DataSize);
AParent.Parser.LoadTagData(FSourcePtr^, Data.Memory^);
Data.DisableChanges := True;
end;
constructor TFoundTiffTag.Create(AID: TTiffTagID; ADataType: TTiffDataType;
const ADataSource: IStreamPersist);
begin
inherited Create;
New(FSourcePtr);
FSourcePtr.ID := AID;
FSourcePtr.DataType := ADataType;
if ADataSource <> nil then
begin
ADataSource.SaveToStream(Data);
FSourcePtr.ElementCount := LongInt(Data.Size div TiffElementSizes[ADataType]);
end
else
begin
FSourcePtr.ElementCount := 1;
Data.Size := TiffElementSizes[ADataType];
FillChar(Data.Memory^, TiffElementSizes[ADataType], 0);
end;
end;
destructor TFoundTiffTag.Destroy;
begin
if (FParent = nil) and (FSourcePtr <> nil) then Dispose(FSourcePtr);
inherited;
end;
function TFoundTiffTag.GetDataType: TTiffDataType;
begin
Result := FSourcePtr.DataType;
end;
function TFoundTiffTag.GetElementCount: LongInt;
begin
Result := FSourcePtr.ElementCount;
end;
function TFoundTiffTag.GetID: TTiffTagID;
begin
Result := FSourcePtr.ID;
end;
function TFoundTiffTag.GetOriginalDataOffset: LongWord;
begin
Result := FSourcePtr.DataOffset;
end;
function TFoundTiffTag.HasIPTCBlockID: Boolean;
begin
Result := (FSourcePtr.ID = ttIPTC);
end;
function TFoundTiffTag.HasXMPBlockID: Boolean;
begin
Result := (FSourcePtr.ID = ttXMP);
end;
function TFoundTiffTag.GetParent: ITiffDirectory;
begin
Result := FParentIntf;
end;
{ TFoundTiffDirectoryEnumerator }
constructor TFoundTiffDirectoryEnumerator.Create(Source: TFoundTiffDirectory);
begin
FCurrentIndex := -1;
FSource := Source;
end;
function TFoundTiffDirectoryEnumerator.GetCurrent: ITiffTag;
begin
Result := TFoundTiffTag.Create(FSource, FCurrentIndex);
end;
function TFoundTiffDirectoryEnumerator.MoveNext: Boolean;
begin
Result := (FCurrentIndex < High(FSource.TagInfo));
if Result then Inc(FCurrentIndex);
end;
{ TFoundTiffDirectory }
constructor TFoundTiffDirectory.Create(const AParser: ITiffParser; const AParent: ITiffDirectory;
AIndex: Integer; const AOffset: Int64; const AInternalOffset: Int64 = 0);
begin
inherited Create;
FTags := LoadTiffDirectory(AParser.Stream, AParser.Endianness,
AParser.BasePosition, AOffset, AInternalOffset, FLoadErrors);
FIndex := AIndex;
FParser := AParser;
FParent := AParent;
end;
constructor TFoundTiffDirectory.Create(const AParser: ITiffParser; const AParent: ITiffDirectory;
AIndex: Integer; const Tags: TTiffTagInfoDynArray; const LoadErrors: TMetadataLoadErrors);
begin
inherited Create;
FLoadErrors := LoadErrors;
FTags := Tags;
FIndex := AIndex;
FParser := AParser;
FParent := AParent;
end;
class function TFoundTiffDirectory.TryCreate(const AParser: ITiffParser;