File Coverage

blib/lib/Image/ExifTool/WriteExif.pl
Criterion Covered Total %
statement 1004 1473 68.1
branch 579 1020 56.7
condition 406 816 49.7
subroutine 11 18 61.1
pod 0 15 0.0
total 2000 3342 59.8


line stmt bran cond sub pod time code
1             #------------------------------------------------------------------------------
2             # File: WriteExif.pl
3             #
4             # Description: Write EXIF meta information
5             #
6             # Revisions: 12/13/2004 - P. Harvey Created
7             #------------------------------------------------------------------------------
8              
9             package Image::ExifTool::Exif;
10              
11 42     42   371 use strict;
  42         108  
  42         2633  
12 42         4063 use vars qw($VERSION $AUTOLOAD @formatSize @formatName %formatNumber
13 42     42   298 %compression %photometricInterpretation %orientation);
  42         100  
14              
15 42     42   302 use Image::ExifTool::Fixup;
  42         95  
  42         1235620  
16              
17             # some information may be stored in different IFD's with the same meaning.
18             # Use this lookup to decide when we should delete information that is stored
19             # in another IFD when we write it to the preferred IFD.
20             my %crossDelete = (
21             ExifIFD => 'IFD0',
22             IFD0 => 'ExifIFD',
23             );
24              
25             # mandatory tag default values
26             my %mandatory = (
27             IFD0 => {
28             # (optional as of 3.0) 0x011a => 72, # XResolution
29             # (optional as of 3.0) 0x011b => 72, # YResolution
30             # (optional as of 3.0) 0x0128 => 2, # ResolutionUnit (inches)
31             0x0213 => 1, # YCbCrPositioning (centered)
32             # 0x8769 => ????, # ExifOffset
33             },
34             IFD1 => {
35             0x0103 => 6, # Compression (JPEG)
36             0x011a => 72, # XResolution
37             0x011b => 72, # YResolution
38             0x0128 => 2, # ResolutionUnit (inches)
39             },
40             ExifIFD => {
41             0x9000 => '0232', # ExifVersion
42             0x9101 => "1 2 3 0",# ComponentsConfiguration
43             # (optional as of 3.0) 0xa000 => '0100', # FlashpixVersion
44             0xa001 => 0xffff, # ColorSpace (uncalibrated)
45             # 0xa002 => ????, # ExifImageWidth
46             # 0xa003 => ????, # ExifImageHeight
47             },
48             GPS => {
49             0x0000 => '2 3 0 0',# GPSVersionID
50             },
51             InteropIFD => {
52             0x0002 => '0100', # InteropVersion (from the DCF spec, not the EXIF spec)
53             },
54             );
55              
56             #------------------------------------------------------------------------------
57             # Inverse print conversion for OffsetTime tags
58             # Inputs: 0) input time zone or date/time value, 1) ExifTool ref
59             # Returns: Time zone string for writing to EXIF
60             sub InverseOffsetTime($$)
61             {
62 0     0 0 0 my ($val, $et) = @_;
63 0 0       0 $val = $et->TimeNow() if lc($val) eq 'now';
64 0 0       0 return '+00:00' if $val =~ /Z$/;
65 0 0       0 return sprintf('%s%.2d:%.2d',$1,$2,$3) if $val =~ /([-+])(\d{1,2}):?(\d{2})/;
66 0         0 return undef;
67             }
68              
69             #------------------------------------------------------------------------------
70             # Inverse print conversion for LensInfo
71             # Inputs: 0) lens info string
72             # Returns: PrintConvInv of string
73             sub ConvertLensInfo($)
74             {
75 7     7 0 25 my $val = shift;
76 7         52 my @a = GetLensInfo($val, 1); # (allow unknown "?" values)
77 7 100       50 return @a ? join(' ', @a) : $val;
78             }
79              
80             #------------------------------------------------------------------------------
81             # Get binary CFA Pattern from a text string
82             # Inputs: Print-converted CFA pattern (eg. '[Blue,Green][Green,Red]')
83             # Returns: CFA pattern as a string of numbers
84             sub GetCFAPattern($)
85             {
86 1     1 0 4 my $val = shift;
87 1         8 my @rows = split /\]\s*\[/, $val;
88 1 50       8 @rows or warn("Rows not properly bracketed by '[]'\n"), return undef;
89 1         4 my @cols = split /,/, $rows[0];
90 1 50       6 @cols or warn("Colors not separated by ','\n"), return undef;
91 1         3 my $ny = @cols;
92 1         4 my @a = (scalar(@rows), scalar(@cols));
93 1         13 my %cfaLookup = (red=>0, green=>1, blue=>2, cyan=>3, magenta=>4, yellow=>5, white=>6);
94 1         2 my $row;
95 1         4 foreach $row (@rows) {
96 2         7 @cols = split /,/, $row;
97 2 50       25 @cols == $ny or warn("Inconsistent number of colors in each row\n"), return undef;
98 2         6 foreach (@cols) {
99 4         9 tr/ \]\[//d; # remove remaining brackets and any spaces
100 4         10 my $c = $cfaLookup{lc($_)};
101 4 50       10 defined $c or warn("Unknown color '${_}'\n"), return undef;
102 4         11 push @a, $c;
103             }
104             }
105 1         19 return "@a";
106             }
107              
108             #------------------------------------------------------------------------------
109             # validate raw values for writing
110             # Inputs: 0) ExifTool ref, 1) tagInfo hash ref, 2) raw value ref
111             # Returns: error string or undef (and possibly changes value) on success
112             sub CheckExif($$$)
113             {
114 6343     6343 0 14506 my ($et, $tagInfo, $valPtr) = @_;
115 6343   66     35385 my $format = $$tagInfo{Format} || $$tagInfo{Writable} || $$tagInfo{Table}{WRITABLE};
116 6343 100 66     26079 if (not $format or $format eq '1') {
117 129 50       642 if ($$tagInfo{Groups}{0} eq 'MakerNotes') {
118 129         475 return undef; # OK to have no format for makernotes
119             } else {
120 0         0 return 'No writable format';
121             }
122             }
123 6214         30524 return Image::ExifTool::CheckValue($valPtr, $format, $$tagInfo{Count});
124             }
125              
126             #------------------------------------------------------------------------------
127             # encode exif ASCII/Unicode text from UTF8 or Latin
128             # Inputs: 0) ExifTool ref, 1) text string
129             # Returns: encoded string
130             # Note: MUST be called Raw conversion time so the EXIF byte order is known!
131             sub EncodeExifText($$)
132             {
133 13     13 0 70 my ($et, $val) = @_;
134             # does the string contain special characters?
135 13 50       78 if ($val =~ /[\x80-\xff]/) {
136 0         0 my $order = $et->GetNewValue('ExifUnicodeByteOrder');
137 0         0 return "UNICODE\0" . $et->Encode($val,'UTF16',$order);
138             } else {
139 13         158 return "ASCII\0\0\0$val";
140             }
141             }
142              
143             #------------------------------------------------------------------------------
144             # rebuild maker notes to properly contain all value data
145             # (some manufacturers put value data outside maker notes!!)
146             # Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
147             # Returns: new maker note data (and creates MAKER_NOTE_FIXUP), or undef on error
148             sub RebuildMakerNotes($$$)
149             {
150 23     23 0 115 my ($et, $dirInfo, $tagTablePtr) = @_;
151 23         92 my $dirStart = $$dirInfo{DirStart};
152 23         72 my $dirLen = $$dirInfo{DirLen};
153 23         83 my $dataPt = $$dirInfo{DataPt};
154 23   100     149 my $dataPos = $$dirInfo{DataPos} || 0;
155 23         54 my $rtnValue;
156 23         269 my %subdirInfo = %$dirInfo;
157              
158 23         108 delete $$et{MAKER_NOTE_FIXUP};
159              
160             # don't need to rebuild text, BinaryData or PreviewImage maker notes
161 23         65 my $tagInfo = $$dirInfo{TagInfo};
162 23         72 my $subdir = $$tagInfo{SubDirectory};
163 23   100     211 my $proc = $$subdir{ProcessProc} || $$tagTablePtr{PROCESS_PROC} || \&ProcessExif;
164 23 0 66     2577 if (($proc ne \&ProcessExif and $$tagInfo{Name} =~ /Text/) or
      33        
      33        
      33        
      33        
165             $proc eq \&Image::ExifTool::ProcessBinaryData or
166             ($$tagInfo{PossiblePreview} and $dirLen > 6 and
167             substr($$dataPt, $dirStart, 3) eq "\xff\xd8\xff"))
168             {
169 0         0 return substr($$dataPt, $dirStart, $dirLen);
170             }
171 23         112 my $saveOrder = GetByteOrder();
172 23         173 my $loc = Image::ExifTool::MakerNotes::LocateIFD($et,\%subdirInfo);
173 23 50       106 if (defined $loc) {
174 23         391 my $makerFixup = $subdirInfo{Fixup} = Image::ExifTool::Fixup->new;
175             # create new exiftool object to rewrite the directory without changing it
176 23         183 my $newTool = Image::ExifTool->new;
177             $newTool->Options(
178             IgnoreMinorErrors => $$et{OPTIONS}{IgnoreMinorErrors},
179             FixBase => $$et{OPTIONS}{FixBase},
180 23         224 );
181 23         161 $newTool->Init(); # must do this before calling WriteDirectory()!
182             # don't copy over preview image
183 23         228 $newTool->SetNewValue(PreviewImage => '');
184             # copy all transient members over in case they are used for writing
185             # (Make, Model, etc)
186 23         1245 foreach (grep /[a-z]/, keys %$et) {
187 284         934 $$newTool{$_} = $$et{$_};
188             }
189             # fix base offsets if specified
190 23         244 $newTool->Options(FixBase => $et->Options('FixBase'));
191             # set GENERATE_PREVIEW_INFO flag so PREVIEW_INFO will be generated
192 23         101 $$newTool{GENERATE_PREVIEW_INFO} = 1;
193             # drop any large tags
194 23         92 $$newTool{DropTags} = 1;
195             # initialize other necessary data members
196 23         119 $$newTool{FILE_TYPE} = $$et{FILE_TYPE};
197 23         99 $$newTool{TIFF_TYPE} = $$et{TIFF_TYPE};
198             # rewrite maker notes
199 23         216 $rtnValue = $newTool->WriteDirectory(\%subdirInfo, $tagTablePtr);
200 23 50 33     216 if (defined $rtnValue and length $rtnValue) {
201             # add the dummy/empty preview image if necessary
202 23 50       161 if ($$newTool{PREVIEW_INFO}) {
203 0         0 $makerFixup->SetMarkerPointers(\$rtnValue, 'PreviewImage', length($rtnValue));
204 0         0 $rtnValue .= $$newTool{PREVIEW_INFO}{Data};
205 0         0 delete $$newTool{PREVIEW_INFO};
206             }
207             # add makernote header
208 23 100       103 if ($loc) {
209 9         41 my $hdr = substr($$dataPt, $dirStart, $loc);
210             # special case: convert Pentax/Samsung DNG maker notes to JPEG style
211             # (in JPEG, Pentax makernotes are absolute and start with "AOC\0" for some
212             # models, but in DNG images they are stored in tag 0xc634 of IFD0 and
213             # start with either "PENTAX \0" or "SAMSUNG\0")
214 9 50 33     81 if ($$dirInfo{Parent} eq 'IFD0' and $hdr =~ /^(PENTAX |SAMSUNG)\0/) {
215             # convert to JPEG-style AOC maker notes if used by this model
216             # (Note: this expression also appears in Exif.pm)
217 0 0       0 if ($$et{Model} =~ /\b(K(-[57mrx]|(10|20|100|110|200)D|2000)|GX(10|20))\b/) {
218 0         0 $hdr =~ s/^(PENTAX |SAMSUNG)\0/AOC\0/;
219             # save fixup because AOC maker notes have absolute offsets
220 0         0 $$et{MAKER_NOTE_FIXUP} = $makerFixup;
221             }
222             }
223 9         37 $rtnValue = $hdr . $rtnValue;
224             # adjust fixup for shift in start position
225 9         29 $$makerFixup{Start} += length $hdr;
226             }
227             # shift offsets according to original position of maker notes,
228             # and relative to the makernotes Base
229             $$makerFixup{Shift} += $dataPos + $dirStart +
230 23         138 $$dirInfo{Base} - $subdirInfo{Base};
231             # repair incorrect offsets if offsets were fixed
232 23   50     148 $$makerFixup{Shift} += $subdirInfo{FixedBy} || 0;
233             # fix up pointers to the specified offset
234 23         135 $makerFixup->ApplyFixup(\$rtnValue);
235             # save fixup information unless offsets were relative
236 23 100       1475 unless ($subdirInfo{Relative}) {
237             # set shift so offsets are all relative to start of maker notes
238 19         61 $$makerFixup{Shift} -= $dataPos + $dirStart;
239 19         493 $$et{MAKER_NOTE_FIXUP} = $makerFixup; # save fixup for later
240             }
241             }
242             }
243 23         173 SetByteOrder($saveOrder);
244              
245 23         462 return $rtnValue;
246             }
247              
248             #------------------------------------------------------------------------------
249             # Sort IFD directory entries
250             # Inputs: 0) data reference, 1) directory start, 2) number of entries,
251             # 3) flag to treat 0 as a valid tag ID (as opposed to an empty IFD entry)
252             sub SortIFD($$$;$)
253             {
254 0     0 0 0 my ($dataPt, $dirStart, $numEntries, $allowZero) = @_;
255 0         0 my ($index, %entries);
256             # split the directory into separate entries
257 0         0 for ($index=0; $index<$numEntries; ++$index) {
258 0         0 my $entry = $dirStart + 2 + 12 * $index;
259 0         0 my $tagID = Get16u($dataPt, $entry);
260 0         0 my $entryData = substr($$dataPt, $entry, 12);
261             # silly software can pad directories with zero entries -- put these at the end
262 0 0 0     0 $tagID = 0x10000 unless $tagID or $index == 0 or $allowZero;
      0        
263             # add new entry (allow for duplicate tag ID's, which shouldn't normally happen)
264 0 0       0 if ($entries{$tagID}) {
265 0         0 $entries{$tagID} .= $entryData;
266             } else {
267 0         0 $entries{$tagID} = $entryData;
268             }
269             }
270             # sort the directory entries
271 0         0 my @sortedTags = sort { $a <=> $b } keys %entries;
  0         0  
272             # generate the sorted IFD
273 0         0 my $newDir = '';
274 0         0 foreach (@sortedTags) {
275 0         0 $newDir .= $entries{$_};
276             }
277             # replace original directory with new, sorted one
278 0         0 substr($$dataPt, $dirStart + 2, 12 * $numEntries) = $newDir;
279             }
280              
281             #------------------------------------------------------------------------------
282             # Validate IFD entries (strict validation to test possible chained IFD's)
283             # Inputs: 0) dirInfo ref (must have RAF set), 1) optional DirStart
284             # Returns: true if IFD looks OK
285             sub ValidateIFD($;$)
286             {
287 0     0 0 0 my ($dirInfo, $dirStart) = @_;
288 0 0       0 my $raf = $$dirInfo{RAF} or return 0;
289 0         0 my $base = $$dirInfo{Base};
290 0 0 0     0 $dirStart = $$dirInfo{DirStart} || 0 unless defined $dirStart;
291 0   0     0 my $offset = $dirStart + ($$dirInfo{DataPos} || 0);
292 0         0 my ($buff, $index);
293 0 0 0     0 $raf->Seek($offset + $base, 0) and $raf->Read($buff,2) == 2 or return 0;
294 0         0 my $numEntries = Get16u(\$buff,0);
295 0 0 0     0 $numEntries > 1 and $numEntries < 64 or return 0;
296 0         0 my $len = 12 * $numEntries;
297 0 0       0 $raf->Read($buff, $len) == $len or return 0;
298 0         0 my $lastID = -1;
299 0         0 for ($index=0; $index<$numEntries; ++$index) {
300 0         0 my $entry = 12 * $index;
301 0         0 my $tagID = Get16u(\$buff, $entry);
302 0 0 0     0 $tagID > $lastID or $$dirInfo{AllowOutOfOrderTags} or return 0;
303 0         0 my $format = Get16u(\$buff, $entry+2);
304 0 0 0     0 $format > 0 and $format <= 13 or return 0;
305 0         0 my $count = Get32u(\$buff, $entry+4);
306 0 0       0 $count > 0 or return 0;
307 0         0 $lastID = $tagID;
308             }
309 0         0 return 1;
310             }
311              
312             #------------------------------------------------------------------------------
313             # Get sorted list of offsets used in IFD
314             # Inputs: 0) data ref, 1) directory start, 2) dataPos, 3) IFD entries, 4) tag table ref
315             # Returns: 0) sorted list of offsets (only offsets after the end of the IFD)
316             # 1) hash of list indices keyed by offset value
317             # Notes: This is used in a patch to fix the count for tags in Kodak SubIFD3
318             sub GetOffList($$$$$)
319             {
320 0     0 0 0 my ($dataPt, $dirStart, $dataPos, $numEntries, $tagTablePtr) = @_;
321 0         0 my $ifdEnd = $dirStart + 2 + 12 * $numEntries + $dataPos;
322 0         0 my ($index, $offset, %offHash);
323 0         0 for ($index=0; $index<$numEntries; ++$index) {
324 0         0 my $entry = $dirStart + 2 + 12 * $index;
325 0         0 my $format = Get16u($dataPt, $entry + 2);
326 0 0 0     0 next if $format < 1 or $format > 13;
327 0         0 my $count = Get16u($dataPt, $entry + 4);
328 0         0 my $size = $formatSize[$format] * $count;
329 0 0       0 if ($size <= 4) {
330 0         0 my $tagID = Get16u($dataPt, $entry);
331 0 0 0     0 next unless ref $$tagTablePtr{$tagID} eq 'HASH' and $$tagTablePtr{$tagID}{FixCount};
332             }
333 0         0 my $offset = Get16u($dataPt, $entry + 8);
334 0 0       0 $offHash{$offset} = 1 if $offset >= $ifdEnd;
335             }
336             # set offset hash values to indices in list
337 0         0 my @offList = sort keys %offHash;
338 0         0 $index = 0;
339 0         0 foreach $offset (@offList) {
340 0         0 $offHash{$offset} = $index++;
341             }
342 0         0 return(\@offList, \%offHash);
343             }
344              
345             #------------------------------------------------------------------------------
346             # Update TIFF_END member if defined
347             # Inputs: 0) ExifTool ref, 1) end of valid TIFF data
348             sub UpdateTiffEnd($$)
349             {
350 332     332 0 934 my ($et, $end) = @_;
351 332 100 100     2009 if (defined $$et{TIFF_END} and
352             $$et{TIFF_END} < $end)
353             {
354 278         733 $$et{TIFF_END} = $end;
355             }
356             }
357              
358             #------------------------------------------------------------------------------
359             # Validate image data size
360             # Inputs: 0) ExifTool ref, 1) validate info hash ref,
361             # 2) flag to issue error (ie. we're writing)
362             # - issues warning or error if problems found
363             sub ValidateImageData($$$;$)
364             {
365 85     85 0 194 local $_;
366 85         342 my ($et, $vInfo, $dirName, $errFlag) = @_;
367              
368             # determine the expected size of the image data for an uncompressed image
369             # (0x102 BitsPerSample, 0x103 Compression and 0x115 SamplesPerPixel
370             # all default to a value of 1 if they don't exist)
371 85 100 100     999 if ((not defined $$vInfo{0x103} or $$vInfo{0x103} eq '1') and
      100        
      66        
      66        
      66        
372             $$vInfo{0x100} and $$vInfo{0x101} and ($$vInfo{0x117} or $$vInfo{0x145}))
373             {
374 5   100     29 my $samplesPerPix = $$vInfo{0x115} || 1;
375 5 50       38 my @bitsPerSample = $$vInfo{0x102} ? split(' ',$$vInfo{0x102}) : (1) x $samplesPerPix;
376 5   33     21 my $byteCountInfo = $$vInfo{0x117} || $$vInfo{0x145};
377 5         14 my $byteCounts = $$byteCountInfo[1];
378 5         11 my $totalBytes = 0;
379 5         27 $totalBytes += $_ foreach split ' ', $byteCounts;
380 5         12 my $minor;
381 5 50 33     83 $minor = 1 if $$et{DOC_NUM} or $$et{FILE_TYPE} ne 'TIFF';
382 5 50       22 unless (@bitsPerSample == $samplesPerPix) {
383 0 0 0     0 unless ($$et{FILE_TYPE} eq 'EPS' and @bitsPerSample == 1) {
384             # (just a warning for this problem)
385 0 0       0 my $s = $samplesPerPix eq '1' ? '' : 's';
386 0         0 $et->Warn("$dirName BitsPerSample should have $samplesPerPix value$s", $minor);
387             }
388 0         0 push @bitsPerSample, $bitsPerSample[0] while @bitsPerSample < $samplesPerPix;
389 0         0 foreach (@bitsPerSample) {
390 0 0       0 $et->Warn("$dirName BitsPerSample values are different", $minor) if $_ ne $bitsPerSample[0];
391 0 0 0     0 $et->Warn("Invalid $dirName BitsPerSample value", $minor) if $_ < 1 or $_ > 32;
392             }
393             }
394 5         12 my $bitsPerPixel = 0;
395 5         22 $bitsPerPixel += $_ foreach @bitsPerSample;
396 5         24 my $expectedBytes = int(($$vInfo{0x100} * $$vInfo{0x101} * $bitsPerPixel + 7) / 8);
397 5 100 66     36 if ($expectedBytes != $totalBytes and
398             # (this problem seems normal for certain types of RAW files...)
399             $$et{TIFF_TYPE} !~ /^(K25|KDC|MEF|ORF|SRF)$/)
400             {
401 1         3 my ($adj, $minor);
402 1 50       6 if ($expectedBytes > $totalBytes) {
403 1         4 $adj = 'Under'; # undersized is a bigger problem because we may lose data
404 1 50       5 $minor = 0 unless $errFlag;
405             } else {
406 0         0 $adj = 'Over';
407 0         0 $minor = 1;
408             }
409 1         9 my $msg = "${adj}sized $dirName $$byteCountInfo[0]{Name} ($totalBytes bytes, but expected $expectedBytes)";
410 1 50       25 if (not defined $minor) {
411             # this is a serious error if we are writing the file and there
412             # is a chance that we may not copy all of the image data
413             # (but make it minor to allow the file to be written anyway)
414 1         11 $et->Error($msg, 1);
415             } else {
416 0         0 $et->Warn($msg, $minor);
417             }
418             }
419             }
420             }
421              
422             #------------------------------------------------------------------------------
423             # Add specified image data to ImageDataHash hash
424             # Inputs: 0) ExifTool ref, 1) dirInfo ref, 2) lookup for [tagInfo,value] based on tagID
425             sub AddImageDataHash($$$)
426             {
427 0     0 0 0 my ($et, $dirInfo, $offsetInfo) = @_;
428 0         0 my ($tagID, $offset, $buff);
429              
430 0         0 my $verbose = $et->Options('Verbose');
431 0         0 my $hash = $$et{ImageDataHash};
432 0         0 my $raf = $$dirInfo{RAF};
433              
434 0         0 foreach $tagID (sort keys %$offsetInfo) {
435 0 0       0 next unless ref $$offsetInfo{$tagID} eq 'ARRAY'; # ignore scalar tag values used for Validate
436 0         0 my $tagInfo = $$offsetInfo{$tagID}[0];
437 0 0       0 next unless $$tagInfo{IsImageData}; # only consider image data
438 0         0 my $sizeID = $$tagInfo{OffsetPair};
439 0         0 my @sizes;
440 0 0 0     0 if ($$tagInfo{NotRealPair}) {
    0          
441 0         0 @sizes = 999999999; # (Panasonic hack: raw data runs to end of file)
442             } elsif ($sizeID and $$offsetInfo{$sizeID}) {
443 0         0 @sizes = split ' ', $$offsetInfo{$sizeID}[1];
444             } else {
445 0         0 next;
446             }
447 0         0 my @offsets = split ' ', $$offsetInfo{$tagID}[1];
448 0 0       0 $sizes[0] = 999999999 if $$tagInfo{NotRealPair};
449 0         0 my $total = 0;
450 0         0 foreach $offset (@offsets) {
451 0         0 my $size = shift @sizes;
452 0 0 0     0 next unless $offset =~ /^\d+$/ and $size and $size =~ /^\d+$/ and $size;
      0        
      0        
453 0 0       0 next unless $raf->Seek($offset, 0); # (offset is absolute)
454 0         0 $total += $et->ImageDataHash($raf, $size);
455             }
456 0 0       0 if ($verbose) {
457 0         0 my $name = "$$dirInfo{DirName}:$$tagInfo{Name}";
458 0         0 $name =~ s/Offsets?|Start$//;
459 0         0 $et->VPrint(0, "$$et{INDENT}(ImageDataHash: $total bytes of $name data)\n");
460             }
461             }
462             }
463              
464             #------------------------------------------------------------------------------
465             # Handle error while writing EXIF
466             # Inputs: 0) ExifTool ref, 1) error string, 2) tag table ref
467             # Returns: undef on fatal error, or '' if minor error is ignored
468             sub ExifErr($$$)
469             {
470 0     0 0 0 my ($et, $errStr, $tagTablePtr) = @_;
471             # MakerNote errors are minor by default
472 0   0     0 my $minor = ($$tagTablePtr{GROUPS}{0} eq 'MakerNotes' or $$et{FILE_TYPE} eq 'MOV');
473 0 0 0     0 if ($$tagTablePtr{VARS} and $$tagTablePtr{VARS}{MINOR_ERRORS}) {
474 0 0 0     0 $et->Warn("$errStr. IFD dropped.") and return '' if $minor;
475 0         0 $minor = 1;
476             }
477 0 0       0 return undef if $et->Error($errStr, $minor);
478 0         0 return '';
479             }
480              
481             #------------------------------------------------------------------------------
482             # Read/Write IFD with TIFF-like header (used by DNG 1.2)
483             # Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
484             # Returns: Reading: 1 on success, otherwise returns 0 and sets a Warning
485             # Writing: new data block or undef on error
486             sub ProcessTiffIFD($$$)
487             {
488 0     0 0 0 my ($et, $dirInfo, $tagTablePtr) = @_;
489 0 0       0 $et or return 1; # allow dummy access
490 0         0 my $raf = $$dirInfo{RAF};
491 0   0     0 my $base = $$dirInfo{Base} || 0;
492 0         0 my $dirName = $$dirInfo{DirName};
493 0   0     0 my $magic = $$dirInfo{Subdir}{Magic} || 0x002a;
494 0         0 my $buff;
495              
496             # structured with a TIFF-like header and relative offsets
497 0 0 0     0 $raf->Seek($base, 0) and $raf->Read($buff, 8) == 8 or return 0;
498 0 0 0     0 unless (SetByteOrder(substr($buff,0,2)) and Get16u(\$buff, 2) == $magic) {
499 0         0 my $msg = "Invalid $dirName header";
500 0 0       0 if ($$dirInfo{IsWriting}) {
501 0         0 $et->Error($msg);
502 0         0 return undef;
503             } else {
504 0         0 $et->Warn($msg);
505 0         0 return 0;
506             }
507             }
508 0         0 my $offset = Get32u(\$buff, 4);
509             my %dirInfo = (
510             DirName => $$dirInfo{DirName},
511             Parent => $$dirInfo{Parent},
512 0         0 Base => $base,
513             DataPt => \$buff,
514             DataLen => length $buff,
515             DataPos => 0,
516             DirStart => $offset,
517             DirLen => length($buff) - $offset,
518             RAF => $raf,
519             NewDataPos => 8,
520             );
521 0 0       0 if ($$dirInfo{IsWriting}) {
522             # rewrite the Camera Profile IFD
523 0         0 my $newDir = WriteExif($et, \%dirInfo, $tagTablePtr);
524             # don't add header if error writing directory ($newDir is undef)
525             # or if directory is being deleted ($newDir is empty)
526 0 0       0 return $newDir unless $newDir;
527             # return directory with TIFF-like header
528 0         0 return GetByteOrder() . Set16u($magic) . Set32u(8) . $newDir;
529             }
530 0 0       0 if ($$et{HTML_DUMP}) {
531 0 0       0 my $tip = sprintf("Byte order: %s endian\nIdentifier: 0x%.4x\n%s offset: 0x%.4x",
532             (GetByteOrder() eq 'II') ? 'Little' : 'Big', $magic, $dirName, $offset);
533 0         0 $et->HDump($base, 8, "$dirName header", $tip, 0);
534             }
535 0         0 return ProcessExif($et, \%dirInfo, $tagTablePtr);
536             }
537              
538             #------------------------------------------------------------------------------
539             # Write EXIF directory
540             # Inputs: 0) ExifTool object ref, 1) source dirInfo ref, 2) tag table ref
541             # Returns: Exif data block (may be empty if no Exif data) or undef on error
542             # Notes: Increments ExifTool CHANGED flag for each tag changed. Also updates
543             # TIFF_END if defined with location of end of original TIFF image.
544             # Returns IFD data in the following order:
545             # 1. IFD0 directory followed by its data
546             # 2. SubIFD directory followed by its data, thumbnail and image
547             # 3. GlobalParameters, EXIF, GPS, Interop IFD's each with their data
548             # 4. IFD1,IFD2,... directories each followed by their data
549             # 5. Thumbnail and/or image data for each IFD, with IFD0 image last
550             sub WriteExif($$$)
551             {
552 8710     8710 0 18572 my ($et, $dirInfo, $tagTablePtr) = @_;
553 8710 100       38450 $et or return 1; # allow dummy access to autoload this package
554 335         811 my $origDirInfo = $dirInfo; # save original dirInfo
555 335         1043 my $dataPt = $$dirInfo{DataPt};
556 335 100       1212 unless ($dataPt) {
557 36         137 my $emptyData = '';
558 36         112 $dataPt = \$emptyData;
559             }
560 335   100     1811 my $dataPos = $$dirInfo{DataPos} || 0;
561 335   100     1774 my $dirStart = $$dirInfo{DirStart} || 0;
562 335   66     1386 my $dataLen = $$dirInfo{DataLen} || length($$dataPt);
563 335   100     1649 my $dirLen = $$dirInfo{DirLen} || ($dataLen - $dirStart);
564 335   100     1479 my $base = $$dirInfo{Base} || 0;
565 335         702 my $firstBase = $base;
566 335         816 my $raf = $$dirInfo{RAF};
567 335   50     1426 my $dirName = $$dirInfo{DirName} || 'unknown';
568 335   66     3176 my $fixup = $$dirInfo{Fixup} || Image::ExifTool::Fixup->new;
569 335   100     1565 my $imageDataFlag = $$dirInfo{ImageData} || '';
570 335         1774 my $verbose = $et->Options('Verbose');
571 335         1182 my $out = $et->Options('TextOut');
572 335         1086 my $noMandatory = $et->Options('NoMandatory');
573 335         1349 my ($nextIfdPos, %offsetData, $inMakerNotes);
574 335         0 my (@offsetInfo, %validateInfo, %xDelete, $strEnc);
575 335         737 my $deleteAll = 0;
576 335         722 my $newData = ''; # initialize buffer to receive new directory data
577 335         667 my @imageData; # image data blocks to copy later if requested
578 335         839 my $name = $$dirInfo{Name};
579 335 100 100     2630 $name = $dirName unless $name and $dirName eq 'MakerNotes' and $name !~ /^MakerNote/;
      100        
580              
581             # save byte order of existing EXIF
582 335 100 100     2433 $$et{SaveExifByteOrder} = GetByteOrder() if $dirName eq 'IFD0' or $dirName eq 'ExifIFD';
583              
584             # set encoding for strings
585 335 100       2124 $strEnc = $et->Options('CharsetEXIF') if $$tagTablePtr{GROUPS}{0} eq 'EXIF';
586              
587             # allow multiple IFD's in IFD0-IFD1-IFD2... chain
588 335 100 66     3170 $$dirInfo{Multi} = 1 if $dirName =~ /^(IFD0|SubIFD)$/ and not defined $$dirInfo{Multi};
589 335 100       1528 $inMakerNotes = 1 if $$tagTablePtr{GROUPS}{0} eq 'MakerNotes';
590 335         746 my $ifd;
591              
592             #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
593             # loop through each IFD
594             #
595 335         882 for ($ifd=0; ; ++$ifd) { # loop through multiple IFD's
596              
597             # make sure that Compression and SubfileType are defined for this IFD (for Condition's)
598 383         1380 $$et{Compression} = $$et{SubfileType} = '';
599              
600             # save pointer to start of this IFD within the newData
601 383         978 my $newStart = length($newData);
602 383         979 my @subdirs; # list of subdirectory data and tag table pointers
603             # determine if directory is contained within our data
604             my $mustRead;
605 383 100 66     2879 if ($dirStart < 0 or $dirStart > $dataLen-2) {
    50          
606 122         345 $mustRead = 1;
607             } elsif ($dirLen >= 2) {
608 261         1098 my $len = 2 + 12 * Get16u($dataPt, $dirStart);
609 261 50       1015 $mustRead = 1 if $dirStart + $len > $dataLen;
610             }
611             # read IFD from file if necessary
612 383 100       1255 if ($mustRead) {
613 122 100 33     792 if ($raf) {
    50          
614             # read the count of entries in this IFD
615 38         129 my $offset = $dirStart + $dataPos;
616 38         90 my ($buff, $buf2);
617 38 50 33     250 unless ($raf->Seek($offset + $base, 0) and $raf->Read($buff,2) == 2) {
618 0         0 return ExifErr($et, "Bad IFD or truncated file in $name", $tagTablePtr);
619             }
620 38         230 my $len = 12 * Get16u(\$buff,0);
621             # (also read next IFD pointer if available)
622 38 50       179 unless ($raf->Read($buf2, $len+4) >= $len) {
623 0         0 return ExifErr($et, "Error reading $name", $tagTablePtr);
624             }
625 38         144 $buff .= $buf2;
626             # make copy of dirInfo since we're going to modify it
627 38         675 my %newDirInfo = %$dirInfo;
628 38         183 $dirInfo = \%newDirInfo;
629             # update directory parameters for the newly loaded IFD
630 38         153 $dataPt = $$dirInfo{DataPt} = \$buff;
631 38         133 $dirStart = $$dirInfo{DirStart} = 0;
632 38         122 $dataPos = $$dirInfo{DataPos} = $offset;
633 38         114 $dataLen = $$dirInfo{DataLen} = length $buff;
634 38         154 $dirLen = $$dirInfo{DirLen} = $dataLen;
635             # only account for nextIFD pointer if we are going to use it
636 38 50 66     437 $len += 4 if $dataLen==$len+6 and ($$dirInfo{Multi} or $buff =~ /\0{4}$/);
      66        
637 38         243 UpdateTiffEnd($et, $offset+$base+2+$len);
638             } elsif ($dirLen and $dirStart + 4 >= $dataLen) {
639             # error if we can't load IFD (unless we are creating
640             # from scratch, in which case dirLen will be zero)
641 0 0       0 my $str = $et->Options('IgnoreMinorErrors') ? 'Deleted bad' : 'Bad';
642 0         0 $et->Error("$str $name directory", 1);
643             }
644             }
645 383         1078 my ($index, $dirEnd, $numEntries, %hasOldID, $unsorted);
646 383 100       1261 if ($dirStart + 4 < $dataLen) {
647 292         892 $numEntries = Get16u($dataPt, $dirStart);
648 292         812 $dirEnd = $dirStart + 2 + 12 * $numEntries;
649 292 50       999 if ($dirEnd > $dataLen) {
650 0         0 my $n = int(($dataLen - $dirStart - 2) / 12);
651 0         0 my $rtn = ExifErr($et, "Truncated $name directory", $tagTablePtr);
652 0 0 0     0 return undef unless $n and defined $rtn;
653 0         0 $numEntries = $n; # continue processing the entries we have
654             }
655             # create lookup for existing tag ID's and determine if directory is sorted
656 292         643 my $lastID = -1;
657 292         1054 for ($index=0; $index<$numEntries; ++$index) {
658 4721         9432 my $tagID = Get16u($dataPt, $dirStart + 2 + 12 * $index);
659 4721         11522 $hasOldID{$tagID} = 1;
660             # check for proper sequence (but ignore null entries at end)
661 4721 100 100     9029 $unsorted = 1 if $tagID < $lastID and ($tagID or $$tagTablePtr{0});
      100        
662 4721         9385 $lastID = $tagID;
663             }
664             # sort entries if out-of-order (but not in maker notes IFDs or RAW files)
665 292 50 33     1718 if ($unsorted and not ($inMakerNotes or $et->IsRawType())) {
      66        
666 0         0 SortIFD($dataPt, $dirStart, $numEntries, $$tagTablePtr{0});
667 0         0 $et->Warn("Entries in $name were out of sequence. Fixed.",1);
668 0         0 $unsorted = 0;
669             }
670             } else {
671 91         546 $numEntries = 0;
672 91         263 $dirEnd = $dirStart;
673             }
674              
675             # loop through new values and accumulate all information for this IFD
676 383         934 my (%set, %mayDelete, $tagInfo, %hasNewID);
677 383         1311 my $wrongDir = $crossDelete{$dirName};
678 383         2544 my @newTagInfo = $et->GetNewTagInfoList($tagTablePtr);
679 383         1116 foreach $tagInfo (@newTagInfo) {
680 2057         4005 my $tagID = $$tagInfo{TagID};
681 2057         4018 $hasNewID{$tagID} = 1;
682             # must evaluate Condition later when we have all DataMember's available
683 2057 100 100     8298 $set{$tagID} = (ref $$tagTablePtr{$tagID} eq 'ARRAY' or $$tagInfo{Condition}) ? '' : $tagInfo;
684             }
685              
686             # fix base offsets (some cameras incorrectly write maker notes in IFD0)
687 383 100 100     3070 if ($dirName eq 'MakerNotes' and $$dirInfo{Parent} =~ /^(ExifIFD|IFD0)$/ and
      66        
      66        
      66        
688             $$et{TIFF_TYPE} !~ /^(ARW|SR2)$/ and not $$et{LeicaTrailerPos} and
689             Image::ExifTool::MakerNotes::FixBase($et, $dirInfo))
690             {
691             # update local variables from fixed values
692 2         5 $base = $$dirInfo{Base};
693 2         3 $dataPos = $$dirInfo{DataPos};
694             # changed if ForceWrite tag was was set to "FixBase"
695 2 50       7 ++$$et{CHANGED} if $$et{FORCE_WRITE}{FixBase};
696 2 0 33     8 if ($$et{TIFF_TYPE} eq 'SRW' and $$et{Make} eq 'SAMSUNG' and $$et{Model} eq 'EK-GN120') {
      33        
697 0         0 $et->Error("EK-GN120 SRW files are too buggy to write");
698             }
699             }
700              
701             # initialize variables to handle mandatory tags
702 383         903 my ($mandatory, $allMandatory, $addMandatory);
703 383 50       1761 $mandatory = $mandatory{$dirName} unless $noMandatory;
704 383 100       1255 if ($mandatory) {
705             # use X/Y resolution values from JFIF if available
706 297 100 100     1578 if ($dirName eq 'IFD0' and defined $$et{JFIFYResolution}) {
707 6         26 my %ifd0Vals = %$mandatory;
708 6         47 $ifd0Vals{0x011a} = $$et{JFIFXResolution};
709 6         31 $ifd0Vals{0x011b} = $$et{JFIFYResolution};
710 6         18 $ifd0Vals{0x0128} = $$et{JFIFResolutionUnit} + 1;
711 6         15 $mandatory = \%ifd0Vals;
712             }
713 297         714 $allMandatory = $addMandatory = 0; # initialize to zero
714             # add mandatory tags if creating a new directory
715 297 100       1021 unless ($numEntries) {
716 91         411 foreach (keys %$mandatory) {
717 174 100       734 defined $set{$_} or $set{$_} = $$tagTablePtr{$_};
718             }
719             }
720             } else {
721 86         232 undef $deleteAll; # don't remove directory (no mandatory entries)
722             }
723 383         918 my ($addDirs, @newTags);
724 383 100       1226 if ($inMakerNotes) {
725 74         192 $addDirs = { }; # can't currently add new directories in MakerNotes
726             # allow non-permanent makernotes tags to be added
727             # (note: we may get into trouble if there are too many of these
728             # because we allow out-of-order tags in MakerNote IFD's but our
729             # logic to add new tags relies on ordered entries)
730 74         316 foreach (keys %set) {
731 41 100       137 next unless $set{$_};
732 36         85 my $perm = $set{$_}{Permanent};
733 36 50 66     148 push @newTags, $_ if defined $perm and not $perm;
734             }
735 74 50       350 @newTags = sort { $a <=> $b } @newTags if @newTags > 1;
  0         0  
736             } else {
737             # get a hash of directories we will be writing in this one
738 309         1970 $addDirs = $et->GetAddDirHash($tagTablePtr, $dirName);
739             # make a union of tags & dirs (can set whole dirs, like MakerNotes)
740 309         3620 my %allTags = ( %set, %$addDirs );
741             # make sorted list of new tags to be added
742 309         2655 @newTags = sort { $a <=> $b } keys(%allTags);
  7252         11046  
743             }
744 383         1339 my $dirBuff = ''; # buffer for directory data
745 383         954 my $valBuff = ''; # buffer for value data
746 383         796 my @valFixups; # list of fixups for offsets in valBuff
747             # fixup for offsets in dirBuff
748 383         3255 my $dirFixup = Image::ExifTool::Fixup->new;
749 383         834 my $entryBasedFixup;
750 383         1015 my $lastTagID = -1;
751 383         2575 my ($oldInfo, $oldFormat, $oldFormName, $oldCount, $oldSize, $oldValue, $oldImageData);
752 383         0 my ($readFormat, $readFormName, $readCount); # format for reading old value(s)
753 383         0 my ($entry, $valueDataPt, $valueDataPos, $valueDataLen, $valuePtr, $valEnd);
754 383         0 my ($offList, $offHash, $ignoreCount, $fixCount);
755 383         815 my $oldID = -1;
756 383         888 my $newID = -1;
757              
758             # patch for Canon EOS 40D firmware 1.0.4 bug (incorrect directory counts)
759 383 50 66     2066 if ($inMakerNotes and $$et{Model} eq 'Canon EOS 40D') {
760 0         0 my $fmt = Get16u($dataPt, $dirStart + 2 + 12 * ($numEntries - 1) + 2);
761 0 0 0     0 if ($fmt < 1 or $fmt > 13) {
762             # adjust the number of directory entries
763 0         0 --$numEntries;
764 0         0 $dirEnd -= 12;
765 0         0 $ignoreCount = 1;
766             }
767             }
768             #..............................................................................
769             # loop through entries in new directory
770             #
771 383         1016 $index = 0;
772 383         895 Entry: for (;;) {
773              
774 7022 100 100     25851 if (defined $oldID and $oldID == $newID) {
775             #
776             # read next entry from existing directory
777             #
778 5104 100       11157 if ($index < $numEntries) {
779 4721         9369 $entry = $dirStart + 2 + 12 * $index;
780 4721         12204 $oldID = Get16u($dataPt, $entry);
781 4721         11815 $readFormat = $oldFormat = Get16u($dataPt, $entry+2);
782 4721         13017 $readCount = $oldCount = Get32u($dataPt, $entry+4);
783 4721         8838 undef $oldImageData;
784 4721 0 33     20531 if (($oldFormat < 1 or $oldFormat > 13) and $oldFormat != 129 and not ($oldFormat == 16 and $$et{Make} eq 'Apple' and $inMakerNotes)) {
      33        
      0        
      33        
785 0         0 my $msg = "Bad format ($oldFormat) for $name entry $index";
786             # patch to preserve invalid directory entries in SubIFD3 of
787             # various Kodak Z-series cameras (Z812, Z1085IS, Z1275)
788             # and some Sony cameras such as the DSC-P10
789 0 0 0     0 if ($dirName eq 'MakerNotes' and (($$et{Make}=~/KODAK/i and
      0        
790             $$dirInfo{Name} and $$dirInfo{Name} eq 'SubIFD3') or
791             ($numEntries == 12 and $$et{Make} eq 'SONY' and $index >= 8)))
792             {
793 0         0 $dirBuff .= substr($$dataPt, $entry, 12);
794 0         0 ++$index;
795 0         0 $newID = $oldID; # we wrote this
796 0         0 $et->Warn($msg, 1);
797 0         0 next;
798             }
799             # don't write out null directory entry
800 0 0 0     0 if ($oldFormat==0 and $index and $oldCount==0) {
      0        
801 0   0     0 $ignoreCount = ($ignoreCount || 0) + 1;
802             # must keep same directory size to avoid messing up our fixed offsets
803 0 0       0 $dirBuff .= ("\0" x 12) if $$dirInfo{FixBase};
804 0         0 ++$index;
805 0         0 $newID = $oldID; # pretend we wrote this
806 0         0 next;
807             }
808 0         0 return ExifErr($et, $msg, $tagTablePtr);
809             }
810 4721         13013 $readFormName = $oldFormName = $formatName[$oldFormat];
811 4721         7527 $valueDataPt = $dataPt;
812 4721         7315 $valueDataPos = $dataPos;
813 4721         7157 $valueDataLen = $dataLen;
814 4721         7533 $valuePtr = $entry + 8;
815             # try direct method first for speed
816 4721         12555 $oldInfo = $$tagTablePtr{$oldID};
817 4721 100 100     22035 if (ref $oldInfo ne 'HASH' or $$oldInfo{Condition}) {
818             # must get unknown tags too
819             # (necessary so we don't miss a tag we want to Drop)
820 585         2630 my $unk = $et->Options(Unknown => 1);
821 585         2592 $oldInfo = $et->GetTagInfo($tagTablePtr, $oldID);
822 585         2331 $et->Options(Unknown => $unk);
823             }
824             # patch incorrect count in Kodak SubIFD3 tags
825 4721 50 100     20797 if ($oldCount < 2 and $oldInfo and $$oldInfo{FixCount}) {
      66        
826 0 0       0 $offList or ($offList, $offHash) = GetOffList($dataPt, $dirStart, $dataPos,
827             $numEntries, $tagTablePtr);
828 0         0 my $i = $$offHash{Get32u($dataPt, $valuePtr)};
829 0 0 0     0 if (defined $i and $i < $#$offList) {
830 0         0 $oldCount = int(($$offList[$i+1] - $$offList[$i]) / $formatSize[$oldFormat]);
831 0 0 0     0 $fixCount = ($fixCount || 0) + 1 if $oldCount != $readCount;
832             }
833             }
834 4721         9178 $oldSize = $oldCount * $formatSize[$oldFormat];
835 4721         7198 my $readFromFile;
836 4721 100       10550 if ($oldSize > 4) {
837 2151         5174 $valuePtr = Get32u($dataPt, $valuePtr);
838             # fix valuePtr if necessary
839 2151 50       6416 if ($$dirInfo{FixOffsets}) {
840 0 0       0 $valEnd or $valEnd = $dataPos + $dirStart + 2 + 12 * $numEntries + 4;
841 0         0 my ($tagID, $size, $wFlag) = ($oldID, $oldSize, 1);
842             #### eval FixOffsets ($valuePtr, $valEnd, $size, $tagID, $wFlag)
843 0         0 eval $$dirInfo{FixOffsets};
844 0 0       0 unless (defined $valuePtr) {
845 0 0       0 unless ($$et{DropTags}) {
846 0 0       0 my $tagStr = $oldInfo ? $$oldInfo{Name} : sprintf("tag 0x%.4x",$oldID);
847 0 0       0 return undef if $et->Error("Bad $name offset for $tagStr", $inMakerNotes);
848             }
849 0         0 ++$index; $oldID = $newID; next; # drop this tag
  0         0  
  0         0  
850             }
851             }
852             # offset shouldn't point into TIFF or IFD header
853 2151         4153 my $suspect = ($valuePtr < 8);
854             # convert offset to pointer in $$dataPt
855 2151 100 66     14285 if ($$dirInfo{EntryBased} or (ref $$tagTablePtr{$oldID} eq 'HASH' and
      66        
856             $$tagTablePtr{$oldID}{EntryBased}))
857             {
858 5         24 $valuePtr += $entry;
859             } else {
860 2146         3986 $valuePtr -= $dataPos;
861             }
862             # value shouldn't overlap our directory
863 2151 50 66     6073 $suspect = 1 if $valuePtr < $dirEnd and $valuePtr+$oldSize > $dirStart;
864             # get value by seeking in file if we are allowed
865 2151 100 100     8246 if ($valuePtr < 0 or $valuePtr+$oldSize > $dataLen) {
866 226         476 my ($pos, $tagStr, $invalidPreview, $tmpInfo, $leicaTrailer);
867 226 100       609 if ($oldInfo) {
    50          
868 218         599 $tagStr = $$oldInfo{Name};
869 218         479 $leicaTrailer = $$oldInfo{LeicaTrailer};
870             } elsif (defined $oldInfo) {
871 8         55 $tmpInfo = $et->GetTagInfo($tagTablePtr, $oldID, \ '', $oldFormName, $oldCount);
872 8 50       48 if ($tmpInfo) {
873 8         28 $tagStr = $$tmpInfo{Name};
874 8         25 $leicaTrailer = $$tmpInfo{LeicaTrailer};
875             }
876             }
877 226 50       732 $tagStr or $tagStr = sprintf("tag 0x%.4x",$oldID);
878             # allow PreviewImage to run outside EXIF segment in JPEG images
879 226 50       674 if (not $raf) {
880 0 0       0 if ($tagStr eq 'PreviewImage') {
    0          
881 0         0 $raf = $$et{RAF};
882 0 0       0 if ($raf) {
883 0         0 $pos = $raf->Tell();
884 0 0 0     0 if ($oldInfo and $$oldInfo{ChangeBase}) {
885             # adjust base offset for this tag only
886             #### eval ChangeBase ($dirStart,$dataPos)
887 0         0 my $newBase = eval $$oldInfo{ChangeBase};
888 0         0 $valuePtr += $newBase;
889             }
890             } else {
891 0         0 $invalidPreview = 1;
892             }
893             } elsif ($leicaTrailer) {
894             # save information about Leica makernote trailer
895             $$et{LeicaTrailer} = {
896 0   0     0 TagInfo => $oldInfo || $tmpInfo,
897             Offset => $base + $valuePtr + $dataPos,
898             Size => $oldSize,
899             Fixup => Image::ExifTool::Fixup->new,
900             },
901             $invalidPreview = 2;
902             # remove SubDirectory to prevent processing (for now)
903 0 0       0 my %copy = %{$oldInfo || $tmpInfo};
  0         0  
904 0         0 delete $copy{SubDirectory};
905 0         0 delete $copy{MakerNotes};
906 0         0 $oldInfo = \%copy;
907             }
908             }
909 226 50 33     987 if ($oldSize > BINARY_DATA_LIMIT and $$origDirInfo{ImageData} and
    50 0        
    0 0        
910             (not defined $oldInfo or ($oldInfo and
911             (not $$oldInfo{SubDirectory} or $$oldInfo{ReadFromRAF}))))
912             {
913             # copy huge data blocks later instead of loading into memory
914 0         0 $oldValue = ''; # dummy empty value
915             # copy this value later unless writing a new value
916 0 0       0 unless (defined $set{$oldID}) {
917 0 0       0 my $pad = $oldSize & 0x01 ? 1 : 0;
918             # save block information to copy later (set directory offset later)
919 0         0 $oldImageData = [$base+$valuePtr+$dataPos, $oldSize, $pad];
920             }
921             } elsif ($raf) {
922 226   33     1133 my $success = ($raf->Seek($base+$valuePtr+$dataPos, 0) and
923             $raf->Read($oldValue, $oldSize) == $oldSize);
924 226 50       687 if (defined $pos) {
925 0         0 $raf->Seek($pos, 0);
926 0         0 undef $raf;
927             # (sony A700 has 32-byte header on PreviewImage)
928 0 0 0     0 unless ($success and $oldValue =~ /^(\xff\xd8\xff|(.|.{33})\xd8\xff\xdb)/s) {
929 0         0 $invalidPreview = 1;
930 0         0 $success = 1; # continue writing directory anyway
931             }
932             }
933 226 50       657 unless ($success) {
934 0         0 my $wrn = sprintf("Error reading value for $name entry $index, ID 0x%.4x", $oldID);
935 0         0 my $truncOK;
936 0 0 0     0 if ($oldInfo and not $$oldInfo{Unknown}) {
937 0         0 $wrn .= " $$oldInfo{Name}";
938 0         0 $truncOK = $$oldInfo{TruncateOK};
939             }
940 0 0 0     0 return undef if $et->Error($wrn, $inMakerNotes || $truncOK);
941 0 0       0 unless ($truncOK) {
942 0         0 ++$index; $oldID = $newID; next; # drop this tag
  0         0  
  0         0  
943             }
944             }
945             } elsif (not $invalidPreview) {
946 0 0       0 return undef if $et->Error("Bad $name offset for $tagStr", $inMakerNotes);
947 0         0 ++$index; $oldID = $newID; next; # drop this tag
  0         0  
  0         0  
948             }
949 226 50       578 if ($invalidPreview) {
950             # set value for invalid preview
951 0 0       0 if ($$et{FILE_TYPE} eq 'JPEG') {
952             # define dummy value for preview (or Leica MakerNote) to write later
953             # (value must be larger than 4 bytes to generate PREVIEW_INFO,
954             # and an even number of bytes so it won't be padded)
955 0         0 $oldValue = 'LOAD_PREVIEW';
956             } else {
957 0         0 $oldValue = 'none';
958 0         0 $oldSize = length $oldValue;
959             }
960 0         0 $valuePtr = 0;
961             } else {
962 226         910 UpdateTiffEnd($et, $base+$valuePtr+$dataPos+$oldSize);
963             }
964             # update pointers for value just read from file
965 226         547 $valueDataPt = \$oldValue;
966 226         414 $valueDataPos = $valuePtr + $dataPos;
967 226         410 $valueDataLen = $oldSize;
968 226         394 $valuePtr = 0;
969 226         484 $readFromFile = 1;
970             }
971 2151 100       5510 if ($suspect) {
972 2 50       7 my $tagStr = $oldInfo ? $$oldInfo{Name} : sprintf('tag 0x%.4x', $oldID);
973 2         5 my $str = "Suspicious $name offset for $tagStr";
974 2 50       4 if ($inMakerNotes) {
975 2         9 $et->Warn($str, 1);
976             } else {
977 0 0       0 return undef if $et->Error($str, 1);
978             }
979             }
980             }
981             # read value if we haven't already
982 4721 100       15381 $oldValue = substr($$valueDataPt, $valuePtr, $oldSize) unless $readFromFile;
983             # get tagInfo using value if necessary
984 4721 100 66     17463 if (defined $oldInfo and not $oldInfo) {
985 162         610 my $unk = $et->Options(Unknown => 1);
986 162         737 $oldInfo = $et->GetTagInfo($tagTablePtr, $oldID, \$oldValue, $oldFormName, $oldCount);
987 162         896 $et->Options(Unknown => $unk);
988             # now that we have the value, we can resolve the Condition to finally
989             # determine whether we want to delete this tag or not
990 162 0 33     763 if ($mayDelete{$oldID} and $oldInfo and (not @newTags or $newTags[0] != $oldID)) {
      0        
      33        
991 0         0 my $nvHash = $et->GetNewValueHash($oldInfo, $dirName);
992 0 0 0     0 if (not $nvHash and $wrongDir) {
993             # delete from wrong directory if necessary
994 0         0 $nvHash = $et->GetNewValueHash($oldInfo, $wrongDir);
995 0 0       0 $nvHash and $xDelete{$oldID} = 1;
996             }
997 0 0       0 if ($nvHash) {
998             # we want to delete this tag after all, so insert it into our list
999 0         0 $set{$oldID} = $oldInfo;
1000 0         0 unshift @newTags, $oldID;
1001             }
1002             }
1003             }
1004             # make sure we are handling the 'ifd' format properly
1005 4721 50 66     18536 if (($oldFormat == 13 or $oldFormat == 18) and
      33        
      66        
1006             (not $oldInfo or not $$oldInfo{SubIFD}))
1007             {
1008 0         0 my $str = sprintf('%s tag 0x%.4x IFD format not handled', $name, $oldID);
1009 0         0 $et->Error($str, $inMakerNotes);
1010             }
1011             # override format we use to read the value if specified
1012 4721 50       10412 if ($oldInfo) {
1013             # check for tags which must be integers
1014 4721 50 100     21551 if (($$oldInfo{IsOffset} or $$oldInfo{SubIFD}) and
      66        
1015             not $intFormat{$oldFormName})
1016             {
1017 0         0 $et->Error("Invalid format ($oldFormName) for $name $$oldInfo{Name}", $inMakerNotes);
1018 0         0 ++$index; $oldID = $newID; next; # drop this tag
  0         0  
  0         0  
1019             }
1020 4721 50 100     10879 if ($$oldInfo{Drop} and $$et{DropTags} and
      33        
      66        
1021             ($$oldInfo{Drop} == 1 or $$oldInfo{Drop} < $oldSize))
1022             {
1023 4         11 ++$index; $oldID = $newID; next; # drop this tag
  4         8  
  4         9  
1024             }
1025 4717 100       11443 if ($$oldInfo{Format}) {
1026 289         708 $readFormName = $$oldInfo{Format};
1027 289         920 $readFormat = $formatNumber{$readFormName};
1028 289 50       790 unless ($readFormat) {
1029             # we aren't reading in a standard EXIF format, so rewrite in old format
1030 0         0 $readFormName = $oldFormName;
1031 0         0 $readFormat = $oldFormat;
1032             }
1033 289 50       895 if ($$oldInfo{FixedSize}) {
1034 0 0       0 $oldSize = $$oldInfo{FixedSize} if $$oldInfo{FixedSize};
1035 0         0 $oldValue = substr($$valueDataPt, $valuePtr, $oldSize);
1036             }
1037             # adjust number of items to read if format size changed
1038 289         792 $readCount = $oldSize / $formatSize[$readFormat];
1039             }
1040             }
1041 4717 50 33     12138 if ($oldID <= $lastTagID and not ($inMakerNotes or $et->IsRawType())) {
      66        
1042 0 0       0 my $str = $oldInfo ? "$$oldInfo{Name} tag" : sprintf('tag 0x%x',$oldID);
1043 0 0       0 if ($oldID == $lastTagID) {
1044 0         0 $et->Warn("Duplicate $str in $name");
1045             # put this tag back into the newTags list if necessary
1046 0 0       0 unshift @newTags, $oldID if defined $set{$oldID};
1047             } else {
1048 0         0 $et->Warn("\u$str out of sequence in $name");
1049             }
1050             }
1051 4717         7877 $lastTagID = $oldID;
1052 4717         8170 ++$index; # increment index for next time
1053             } else {
1054 383         944 undef $oldID; # no more existing entries
1055             }
1056             }
1057             #
1058             # write out all new tags, up to and including this one
1059             #
1060 7018         12908 $newID = $newTags[0];
1061 7018         10492 my $isNew; # -1=tag is old, 0=tag same as existing, 1=tag is new
1062 7018 100       17922 if (not defined $oldID) {
    100          
1063 2140 100       5137 last unless defined $newID;
1064 1757         2756 $isNew = 1;
1065             } elsif (not defined $newID) {
1066             # maker notes will have no new tags defined
1067 3252 100       8116 if (defined $set{$oldID}) {
1068 35         91 $newID = $oldID;
1069 35         76 $isNew = 0;
1070             } else {
1071 3217         5230 $isNew = -1;
1072             }
1073             } else {
1074 1626         2920 $isNew = $oldID <=> $newID;
1075             # special logic needed if directory has out-of-order entries
1076 1626 50 33     4026 if ($unsorted and $isNew) {
1077 0 0 0     0 if ($isNew > 0 and $hasOldID{$newID}) {
1078             # we wanted to create the new tag, but an old tag
1079             # does exist with this ID, so defer writing the new tag
1080 0         0 $isNew = -1;
1081             }
1082 0 0 0     0 if ($isNew < 0 and $hasNewID{$oldID}) {
1083             # we wanted to write the old tag, but we have
1084             # a new tag with this ID, so move it up in the order
1085 0         0 my @tmpTags = ( $oldID );
1086 0   0     0 $_ == $oldID or push @tmpTags, $_ foreach @newTags;
1087 0         0 @newTags = @tmpTags;
1088 0         0 $newID = $oldID;
1089 0         0 $isNew = 0;
1090             }
1091             }
1092             }
1093 6635         10882 my $newInfo = $oldInfo;
1094 6635         9881 my $newFormat = $oldFormat;
1095 6635         10601 my $newFormName = $oldFormName;
1096 6635         9441 my $newCount = $oldCount;
1097 6635         11119 my $ifdFormName;
1098             my $newValue;
1099 6635 100       15781 my $newValuePt = $isNew >= 0 ? \$newValue : \$oldValue;
1100 6635         11463 my $isOverwriting;
1101              
1102 6635 100       15403 if ($isNew >= 0) {
1103             # add, edit or delete this tag
1104 2201         3625 shift @newTags; # remove from list
1105 2201         5189 my $curInfo = $set{$newID};
1106             # don't allow MakerNotes to be added to ExifIFD of CR3 file
1107 2201 50 100     5892 next if $newID == 0x927c and $isNew > 0 and $$et{FileType} eq 'CR3';
      66        
1108 2201 100 100     5073 unless ($curInfo or $$addDirs{$newID}) {
1109             # we can finally get the specific tagInfo reference for this tag
1110             # (because we can now evaluate the Condition statement since all
1111             # DataMember's have been obtained for tags up to this one)
1112 110         556 $curInfo = $et->GetTagInfo($tagTablePtr, $newID);
1113 110 100 66     692 if (defined $curInfo and not $curInfo) {
1114             # need value to evaluate the condition
1115             # (tricky because we need the tagInfo ref to get the value,
1116             # so we must loop through all new tagInfo's...)
1117 24         86 foreach $tagInfo (@newTagInfo) {
1118 526 100       1297 next unless $$tagInfo{TagID} == $newID;
1119 25         157 my $val = $et->GetNewValue($tagInfo);
1120 25 50       107 defined $val or $mayDelete{$newID} = 1, next;
1121             # must convert to binary for evaluating in Condition
1122 25   100     157 my $fmt = $$tagInfo{Format} || $$tagInfo{Writable};
1123 25 100       118 if ($fmt) {
1124 24         188 $val = WriteValue($val, $fmt, $$tagInfo{Count});
1125 24 50       119 defined $val or $mayDelete{$newID} = 1, next;
1126             }
1127 25         142 $curInfo = $et->GetTagInfo($tagTablePtr, $newID, \$val, $oldFormName, $oldCount);
1128 25 50       103 if ($curInfo) {
1129 25 100       138 last if $curInfo eq $tagInfo;
1130 4         14 undef $curInfo;
1131             }
1132             }
1133             # may want to delete this, but we need to see the old value first
1134 24 100       95 $mayDelete{$newID} = 1 unless $curInfo;
1135             }
1136             # don't set this tag unless valid for the current condition
1137 110 100 100     805 if ($curInfo and $$et{NEW_VALUE}{$curInfo}) {
1138 83         288 $set{$newID} = $curInfo;
1139             } else {
1140 27 100       117 next if $isNew > 0;
1141 1         3 $isNew = -1;
1142 1         2 undef $curInfo;
1143             }
1144             }
1145 2175 100       4511 if ($curInfo) {
    100          
1146 2102 100       5230 if ($$curInfo{WriteCondition}) {
1147 6         13 my $self = $et; # set $self to be used in eval
1148             #### eval WriteCondition ($self)
1149 6 50       713 unless (eval $$curInfo{WriteCondition}) {
1150 0 0       0 $@ and warn $@;
1151 0         0 goto NoWrite; # GOTO !
1152             }
1153             }
1154 2102         3026 my $nvHash;
1155 2102 50       9492 $nvHash = $et->GetNewValueHash($curInfo, $dirName) if $isNew >= 0;
1156 2102 100 66     8232 unless ($nvHash or (defined $$mandatory{$newID} and not $noMandatory)) {
      100        
1157 1100 100       4679 goto NoWrite unless $wrongDir; # GOTO !
1158             # delete stuff from the wrong directory if setting somewhere else
1159 665         1720 $nvHash = $et->GetNewValueHash($curInfo, $wrongDir);
1160             # don't cross delete if not overwriting
1161 665 100       2085 goto NoWrite unless $et->IsOverwriting($nvHash); # GOTO !
1162             # don't cross delete if specifically deleting from the other directory
1163             # (Note: don't call GetValue() here because it shouldn't be called
1164             # if IsOverwriting returns < 0 -- eg. when shifting)
1165 636 100 100     2297 if (not defined $$nvHash{Value} and $$nvHash{WantGroup} and
      100        
1166             lc($$nvHash{WantGroup}) eq lc($wrongDir))
1167             {
1168 2         25 goto NoWrite; # GOTO !
1169             } else {
1170             # remove this tag if found in this IFD
1171 634         1735 $xDelete{$newID} = 1;
1172             }
1173             }
1174             } elsif (not $$addDirs{$newID}) {
1175 467 100       1370 NoWrite: next if $isNew > 0;
1176 3         10 delete $set{$newID};
1177 3         9 $isNew = -1;
1178             }
1179 1711 100 66     5131 if ($set{$newID}) {
    100 33        
    100 66        
    50          
1180             #
1181             # set the new tag value (or 'next' if deleting tag)
1182             #
1183 1636         2724 $newInfo = $set{$newID};
1184 1636         3126 $newCount = $$newInfo{Count};
1185 1636         2812 my ($val, $newVal, $n);
1186 1636         4218 my $nvHash = $et->GetNewValueHash($newInfo, $dirName);
1187 1636 100 66     4080 if ($isNew > 0) {
    100          
1188             # don't create new entry unless requested
1189 1386 100       2988 if ($nvHash) {
1190 616 100       1921 next unless $$nvHash{IsCreating};
1191 530 100       1357 if ($$newInfo{IsOverwriting}) {
1192 1         4 my $proc = $$newInfo{IsOverwriting};
1193 1         10 $isOverwriting = &$proc($et, $nvHash, $val, \$newVal);
1194             } else {
1195 529         1903 $isOverwriting = $et->IsOverwriting($nvHash);
1196             }
1197             } else {
1198 770 100       2611 next if $xDelete{$newID}; # don't create if cross deleting
1199 139         377 $newVal = $$mandatory{$newID}; # get value for mandatory tag
1200 139         304 $isOverwriting = 1;
1201             }
1202             # convert using new format
1203 669 100       1848 if ($$newInfo{Format}) {
1204 73         189 $newFormName = $$newInfo{Format};
1205             # use Writable flag to specify IFD format code
1206 73         188 $ifdFormName = $$newInfo{Writable};
1207             } else {
1208 596         1389 $newFormName = $$newInfo{Writable};
1209 596 50       1496 unless ($newFormName) {
1210 0         0 warn("No format for $name $$newInfo{Name}\n");
1211 0         0 next;
1212             }
1213             }
1214 669         1813 $newFormat = $formatNumber{$newFormName};
1215             } elsif ($nvHash or $xDelete{$newID}) {
1216 241 100       534 unless ($nvHash) {
1217 3         9 $nvHash = $et->GetNewValueHash($newInfo, $wrongDir);
1218             }
1219             # read value
1220 241 50       658 if (length $oldValue >= $oldSize) {
1221 241         834 $val = ReadValue(\$oldValue, 0, $readFormName, $readCount, $oldSize);
1222             } else {
1223 0         0 $val = '';
1224             }
1225             # determine write format (by default, use 'Writable' format)
1226 241         679 my $writable = $$newInfo{Writable};
1227             # (or use existing format if 'Writable' not specified)
1228 241 100 66     1136 $writable = $oldFormName unless $writable and $writable ne '1';
1229             # (and override write format with 'Format' if specified)
1230 241   66     846 my $writeForm = $$newInfo{Format} || $writable;
1231 241 100       653 if ($writeForm ne $newFormName) {
1232             # write in specified format
1233 8         21 $newFormName = $writeForm;
1234 8         24 $newFormat = $formatNumber{$newFormName};
1235             # use different IFD format code if necessary
1236 8 100       37 if ($inMakerNotes) {
    100          
1237             # always preserve IFD format in maker notes
1238 2         6 $ifdFormName = $oldFormName;
1239             } elsif ($writable ne $newFormName) {
1240             # use specified IFD format
1241 2         33 $ifdFormName = $writable;
1242             }
1243             }
1244 241 100 100     881 if ($inMakerNotes and $readFormName ne 'string' and $readFormName ne 'undef') {
      66        
1245             # keep same size in maker notes unless string or binary
1246 26         111 $newCount = $oldCount * $formatSize[$oldFormat] / $formatSize[$newFormat];
1247             }
1248 241 100       666 if ($$newInfo{IsOverwriting}) {
1249 1         3 my $proc = $$newInfo{IsOverwriting};
1250 1         9 $isOverwriting = &$proc($et, $nvHash, $val, \$newVal);
1251             } else {
1252 240         949 $isOverwriting = $et->IsOverwriting($nvHash, $val);
1253             }
1254             }
1255 919 100       2054 if ($isOverwriting) {
1256 904 100       4073 $newVal = $et->GetNewValue($nvHash) unless defined $newVal;
1257             # value undefined if deleting this tag
1258             # (also delete tag if cross-deleting and this isn't a date/time shift)
1259 904 100 66     4236 if (not defined $newVal or ($xDelete{$newID} and not defined $$nvHash{Shift})) {
      100        
1260 22 50 66     162 if (not defined $newVal and $$newInfo{RawConvInv} and defined $$nvHash{Value}) {
      33        
1261             # error in RawConvInv, so rewrite existing tag
1262 0         0 goto NoOverwrite; # GOTO!
1263             }
1264 22 50       176 unless ($isNew) {
1265 22         63 ++$$et{CHANGED};
1266 22         148 $et->VerboseValue("- $dirName:$$newInfo{Name}", $val);
1267             }
1268 22         75 next;
1269             }
1270 882 100 100     2734 if ($newCount and $newCount < 0) {
1271             # set count to number of values if variable
1272 19         72 my @vals = split ' ',$newVal;
1273 19         51 $newCount = @vals;
1274             }
1275             # convert to binary format
1276 882         2948 $newValue = WriteValue($newVal, $newFormName, $newCount);
1277 882 50       2457 unless (defined $newValue) {
1278 0         0 $et->Warn("Invalid value for $dirName:$$newInfo{Name}");
1279 0         0 goto NoOverwrite; # GOTO!
1280             }
1281 882 50       2203 if (length $newValue) {
1282             # limit maximum value length in JPEG images
1283             # (max segment size is 65533 bytes and the min EXIF size is 96 incl an additional IFD entry)
1284 882 50 66     4691 if ($$et{FILE_TYPE} eq 'JPEG' and length($newValue) > 65436 and
      33        
1285             $$newInfo{Name} ne 'PreviewImage')
1286             {
1287 0 0       0 my $name = $$newInfo{MakerNotes} ? 'MakerNotes' : $$newInfo{Name};
1288 0         0 $et->Warn("Writing large value for $name",1);
1289             }
1290             # re-code if necessary
1291 882 50 100     3438 if ($newFormName eq 'utf8') {
    100          
1292 0         0 $newValue = $et->Encode($newValue, 'UTF8');
1293             } elsif ($strEnc and $newFormName eq 'string') {
1294 1         9 $newValue = $et->Encode($newValue, $strEnc);
1295             }
1296             } else {
1297 0         0 $et->Warn("Can't write zero length $$newInfo{Name} in $$tagTablePtr{GROUPS}{1}");
1298 0         0 goto NoOverwrite; # GOTO!
1299             }
1300 882 50       1995 if ($isNew >= 0) {
1301 882         2377 $newCount = length($newValue) / $formatSize[$newFormat];
1302 882         2113 ++$$et{CHANGED};
1303 882 100       2026 if (defined $allMandatory) {
1304             # not all mandatory if we are writing any tag specifically
1305 153 100       479 if ($nvHash) {
1306 82         177 undef $allMandatory;
1307 82         183 undef $deleteAll;
1308             } else {
1309 71         175 ++$addMandatory; # count mandatory tags that we added
1310             }
1311             }
1312 882 100       2053 if ($verbose > 1) {
1313 10 50       26 $et->VerboseValue("- $dirName:$$newInfo{Name}", $val) unless $isNew;
1314 10 50 33     43 if ($$newInfo{OffsetPair} and $newVal eq '4277010157') { # (0xfeedfeed)
1315 0         0 print { $$et{OPTIONS}{TextOut} } " + $dirName:$$newInfo{Name} = \n";
  0         0  
1316             } else {
1317 10 100       31 my $str = $nvHash ? '' : ' (mandatory)';
1318 10         61 $et->VerboseValue("+ $dirName:$$newInfo{Name}", $newVal, $str);
1319             }
1320             }
1321             }
1322             } else {
1323 15 50       47 NoOverwrite: next if $isNew > 0;
1324 15         29 $isNew = -1; # rewrite existing tag
1325             }
1326             # set format for EXIF IFD if different than conversion format
1327 897 100       2422 if ($ifdFormName) {
1328 76         199 $newFormName = $ifdFormName;
1329 76         301 $newFormat = $formatNumber{$newFormName};
1330             }
1331              
1332             } elsif ($isNew > 0) {
1333             #
1334             # create new subdirectory
1335             #
1336             # newInfo may not be defined if we try to add a mandatory tag
1337             # to a directory that doesn't support it (eg. IFD1 in RW2 images)
1338 42 50       272 $newInfo = $$addDirs{$newID} or next;
1339             # make sure we don't try to generate a new MakerNotes directory
1340             # or a SubIFD
1341 42 50 33     322 next if $$newInfo{MakerNotes} or $$newInfo{Name} eq 'SubIFD';
1342 42         363 my $subTable;
1343 42 100       191 if ($$newInfo{SubDirectory}{TagTable}) {
1344 15         109 $subTable = Image::ExifTool::GetTagTable($$newInfo{SubDirectory}{TagTable});
1345             } else {
1346 27         102 $subTable = $tagTablePtr;
1347             }
1348             # create empty source directory
1349 42         274 my %sourceDir = (
1350             Parent => $dirName,
1351             Fixup => Image::ExifTool::Fixup->new,
1352             );
1353 42 100       277 $sourceDir{DirName} = $$newInfo{Groups}{1} if $$newInfo{SubIFD};
1354 42         501 $newValue = $et->WriteDirectory(\%sourceDir, $subTable);
1355             # only add new directory if it isn't empty
1356 42 100 66     349 next unless defined $newValue and length($newValue);
1357             # set the fixup start location
1358 40 100       224 if ($$newInfo{SubIFD}) {
1359             # subdirectory is referenced by an offset in value buffer
1360 36         116 my $subdir = $newValue;
1361 36         181 $newValue = Set32u(0xfeedf00d);
1362             push @subdirs, {
1363             DataPt => \$subdir,
1364             Table => $subTable,
1365             Fixup => $sourceDir{Fixup},
1366 36         454 Offset => length($dirBuff) + 8,
1367             Where => 'dirBuff',
1368             };
1369 36         102 $newFormName = 'int32u';
1370 36         219 $newFormat = $formatNumber{$newFormName};
1371             } else {
1372             # subdirectory goes directly into value buffer
1373 4         16 $sourceDir{Fixup}{Start} += length($valBuff);
1374             # use Writable to set format, otherwise 'undef'
1375 4         12 $newFormName = $$newInfo{Writable};
1376 4 50 33     59 unless ($newFormName and $formatNumber{$newFormName}) {
1377 0         0 $newFormName = 'undef';
1378             }
1379 4         9 $newFormat = $formatNumber{$newFormName};
1380 4         23 push @valFixups, $sourceDir{Fixup};
1381             }
1382             } elsif ($$newInfo{Format} and $$newInfo{Writable} and $$newInfo{Writable} ne '1') {
1383             # use specified write format
1384 4         8 $newFormName = $$newInfo{Writable};
1385 4         11 $newFormat = $formatNumber{$newFormName};
1386             } elsif ($$addDirs{$newID} and $newInfo ne $$addDirs{$newID}) {
1387             # this can happen if we are trying to add a directory that doesn't exist
1388             # in this type of file (eg. try adding a SubIFD tag to an A100 image)
1389 0         0 $isNew = -1;
1390             }
1391             }
1392 5404 100       12155 if ($isNew < 0) {
1393             # just rewrite existing tag
1394 4452         7806 $newID = $oldID;
1395 4452         7688 $newValue = $oldValue;
1396 4452         6797 $newFormat = $oldFormat; # (just in case it changed)
1397 4452         6990 $newFormName = $oldFormName;
1398             # set offset of this entry in the directory so we can update the pointer
1399             # and save block information to copy this large block later
1400 4452 50       10053 if ($oldImageData) {
1401 0         0 $$oldImageData[3] = $newStart + length($dirBuff) + 2;
1402 0         0 push @imageData, $oldImageData;
1403 0         0 $$origDirInfo{ImageData} = \@imageData;
1404             }
1405             }
1406 5404 50       11510 if ($newInfo) {
1407             #
1408             # load necessary data for this tag (thumbnail image, etc)
1409             #
1410 5404 100 100     16275 if ($$newInfo{DataTag} and $isNew >= 0) {
1411 8         24 my $dataTag = $$newInfo{DataTag};
1412             # load data for this tag
1413 8 100 66     53 unless (defined $offsetData{$dataTag} or $dataTag eq 'LeicaTrailer') {
1414             # prefer tag from Composite table if it exists (otherwise
1415             # PreviewImage data would be taken from Extra tag)
1416 4         30 my $compInfo = Image::ExifTool::GetCompositeTagInfo($dataTag);
1417 4   33     29 $offsetData{$dataTag} = $et->GetNewValue($compInfo || $dataTag);
1418 4         10 my $err;
1419 4 50       18 if (defined $offsetData{$dataTag}) {
1420 4         11 my $len = length $offsetData{$dataTag};
1421 4 100       19 if ($dataTag eq 'PreviewImage') {
1422             # must set DEL_PREVIEW flag now if preview fit into IFD
1423 2 50       13 $$et{DEL_PREVIEW} = 1 if $len <= 4;
1424             }
1425             } else {
1426 0         0 $err = "$dataTag not found";
1427             }
1428 4 50       17 if ($err) {
1429 0 0       0 $et->Warn($err) if $$newInfo{IsOffset};
1430 0         0 delete $set{$newID}; # remove from list of tags we are setting
1431 0         0 next;
1432             }
1433             }
1434             }
1435             #
1436             # write maker notes
1437             #
1438 5404 100 100     33999 if ($$newInfo{MakerNotes}) {
    100 66        
    100 100        
    100 100        
      66        
1439             # don't write new makernotes if we are deleting this group
1440 43 50 33     295 if ($$et{DEL_GROUP}{MakerNotes} and
      66        
1441             ($$et{DEL_GROUP}{MakerNotes} != 2 or $isNew <= 0))
1442             {
1443 1 50 0     14 if ($et->IsRawType() and not ($et->IsRawType() == 2 and $dirName eq 'ExifIFD')) {
      33        
1444 0         0 $et->Warn("Can't delete MakerNotes from $$et{FileType}",1);
1445             } else {
1446 1 50       5 if ($isNew <= 0) {
1447 1         4 ++$$et{CHANGED};
1448 1 50       7 $verbose and print $out " Deleting MakerNotes\n";
1449             }
1450 1         5 next;
1451             }
1452             }
1453 42         218 my $saveOrder = GetByteOrder();
1454 42 100 66     299 if ($isNew >= 0 and defined $set{$newID}) {
1455             # we are writing a whole new maker note block
1456             # --> add fixup information if necessary
1457 7         39 my $nvHash = $et->GetNewValueHash($newInfo, $dirName);
1458 7 100 66     57 if ($nvHash and $$nvHash{MAKER_NOTE_FIXUP}) {
1459             # must clone fixup because we will be shifting it
1460 6         39 my $makerFixup = $$nvHash{MAKER_NOTE_FIXUP}->Clone();
1461 6         16 my $valLen = length($valBuff);
1462 6         16 $$makerFixup{Start} += $valLen;
1463 6         18 push @valFixups, $makerFixup;
1464             }
1465             } else {
1466             # update maker notes if possible
1467             my %subdirInfo = (
1468             Base => $base,
1469             DataPt => $valueDataPt,
1470             DataPos => $valueDataPos,
1471             DataLen => $valueDataLen,
1472             DirStart => $valuePtr,
1473             DirLen => $oldSize,
1474             DirName => 'MakerNotes',
1475             Name => $$newInfo{Name},
1476 35         627 Parent => $dirName,
1477             TagInfo => $newInfo,
1478             RAF => $raf,
1479             );
1480 35         115 my ($subTable, $subdir, $loc, $writeProc, $notIFD);
1481 35 50       147 if ($$newInfo{SubDirectory}) {
1482 35         89 my $sub = $$newInfo{SubDirectory};
1483 35 100       157 $subdirInfo{FixBase} = 1 if $$sub{FixBase};
1484 35         161 $subdirInfo{FixOffsets} = $$sub{FixOffsets};
1485 35         163 $subdirInfo{EntryBased} = $$sub{EntryBased};
1486 35 100       139 $subdirInfo{NoFixBase} = 1 if defined $$sub{Base};
1487 35         118 $subdirInfo{AutoFix} = $$sub{AutoFix};
1488 35 100       226 SetByteOrder($$sub{ByteOrder}) if $$sub{ByteOrder};
1489             }
1490             # get the proper tag table for these maker notes
1491 35 50 33     323 if ($oldInfo and $$oldInfo{SubDirectory}) {
1492 35         101 $subTable = $$oldInfo{SubDirectory}{TagTable};
1493 35 50       261 $subTable and $subTable = Image::ExifTool::GetTagTable($subTable);
1494 35         119 $writeProc = $$oldInfo{SubDirectory}{WriteProc};
1495 35         97 $notIFD = $$oldInfo{NotIFD};
1496             } else {
1497 0         0 $et->Warn('Internal problem getting maker notes tag table');
1498             }
1499 35 50 66     231 $writeProc or $writeProc = $$subTable{WRITE_PROC} if $subTable;
1500 35 50       133 $subTable or $subTable = $tagTablePtr;
1501 35 50 66     442 if ($writeProc and
    100 66        
1502             $writeProc eq \&Image::ExifTool::MakerNotes::WriteUnknownOrPreview and
1503             $oldValue =~ /^\xff\xd8\xff/)
1504             {
1505 0         0 $loc = 0;
1506             } elsif (not $notIFD) {
1507             # look for IFD-style maker notes
1508 33         229 $loc = Image::ExifTool::MakerNotes::LocateIFD($et,\%subdirInfo);
1509             }
1510 35 100 66     179 if (defined $loc) {
    100          
    50          
1511             # we need fixup data for this subdirectory
1512 33         266 $subdirInfo{Fixup} = Image::ExifTool::Fixup->new;
1513             # rewrite maker notes
1514 33         110 my $changed = $$et{CHANGED};
1515 33         673 $subdir = $et->WriteDirectory(\%subdirInfo, $subTable, $writeProc);
1516 33 100 100     328 if ($changed == $$et{CHANGED} and $subdirInfo{Fixup}->IsEmpty()) {
1517             # return original data if nothing changed and no fixups
1518 1         2 undef $subdir;
1519             }
1520             } elsif ($$subTable{PROCESS_PROC} and
1521             $$subTable{PROCESS_PROC} eq \&Image::ExifTool::ProcessBinaryData)
1522             {
1523 1         3 my $sub = $$oldInfo{SubDirectory};
1524 1 50       3 if (defined $$sub{Start}) {
1525             #### eval Start ($valuePtr)
1526 1         81 my $start = eval $$sub{Start};
1527 1         4 $loc = $start - $valuePtr;
1528 1         4 $subdirInfo{DirStart} = $start;
1529 1         3 $subdirInfo{DirLen} -= $loc;
1530             } else {
1531 0         0 $loc = 0;
1532             }
1533             # rewrite maker notes
1534 1         24 $subdir = $et->WriteDirectory(\%subdirInfo, $subTable);
1535             } elsif ($notIFD) {
1536 1 50       2 if ($writeProc) {
1537 1         2 $loc = 0;
1538 1         20 $subdir = $et->WriteDirectory(\%subdirInfo, $subTable);
1539             }
1540             } else {
1541 0         0 my $msg = 'Maker notes could not be parsed';
1542 0 0       0 if ($$et{FILE_TYPE} eq 'JPEG') {
1543 0         0 $et->Warn($msg, 1);
1544             } else {
1545 0         0 $et->Error($msg, 1);
1546             }
1547             }
1548 35 100       199 if (defined $subdir) {
1549 34 50       145 length $subdir or SetByteOrder($saveOrder), next;
1550 34         89 my $valLen = length($valBuff);
1551             # restore existing header and substitute the new
1552             # maker notes for the old value
1553 34         380 $newValue = substr($oldValue, 0, $loc) . $subdir;
1554 34         111 my $makerFixup = $subdirInfo{Fixup};
1555 34         90 my $previewInfo = $$et{PREVIEW_INFO};
1556 34 100       274 if ($subdirInfo{Relative}) {
    50          
1557             # apply a one-time fixup to $loc since offsets are relative
1558 5         17 $$makerFixup{Start} += $loc;
1559             # shift all offsets to be relative to new base
1560 5         17 my $baseShift = $valueDataPos + $valuePtr + $base - $subdirInfo{Base};
1561 5         12 $$makerFixup{Shift} += $baseShift;
1562 5         47 $makerFixup->ApplyFixup(\$newValue);
1563 5 50       23 if ($previewInfo) {
1564             # remove all but PreviewImage fixup (since others shouldn't change)
1565 0         0 foreach (keys %{$$makerFixup{Pointers}}) {
  0         0  
1566 0 0       0 /_PreviewImage$/ or delete $$makerFixup{Pointers}{$_};
1567             }
1568             # zero pointer so we can see how it gets shifted later
1569 0         0 $makerFixup->SetMarkerPointers(\$newValue, 'PreviewImage', 0);
1570             # set the pointer to the start of the EXIF information
1571             # add preview image fixup to list of value fixups
1572 0         0 $$makerFixup{Start} += $valLen;
1573 0         0 push @valFixups, $makerFixup;
1574 0         0 $$previewInfo{BaseShift} = $baseShift;
1575 0         0 $$previewInfo{Relative} = 1;
1576             }
1577             # don't shift anything if relative flag set to zero (Pentax patch)
1578             } elsif (not defined $subdirInfo{Relative}) {
1579             # shift offset base if shifted in the original image or if FixBase
1580             # was used, but be careful of automatic FixBase with negative shifts
1581             # since they may lead to negative (invalid) offsets (casio_edit_problem.jpg)
1582 29         108 my $baseShift = $base - $subdirInfo{Base};
1583 29 100 66     265 if ($subdirInfo{AutoFix}) {
    50 0        
      33        
1584 1         2 $baseShift = 0;
1585             } elsif ($subdirInfo{FixBase} and $baseShift < 0 and
1586             # allow negative base shift if offsets are bigger (PentaxOptioWP.jpg)
1587             (not $subdirInfo{MinOffset} or $subdirInfo{MinOffset} + $baseShift < 0))
1588             {
1589 0         0 my $fixBase = $et->Options('FixBase');
1590 0 0       0 if (not defined $fixBase) {
    0          
1591 0 0       0 my $str = $et->Options('IgnoreMinorErrors') ? 'ignored' : 'fix or ignore?';
1592 0         0 $et->Error("MakerNotes offsets may be incorrect ($str)", 1);
1593             } elsif ($fixBase eq '') {
1594 0         0 $et->Warn('Fixed incorrect MakerNotes offsets');
1595 0         0 $baseShift = 0;
1596             }
1597             }
1598 29         96 $$makerFixup{Start} += $valLen + $loc;
1599 29         100 $$makerFixup{Shift} += $baseShift;
1600             # permanently fix makernote offset errors
1601 29   50     200 $$makerFixup{Shift} += $subdirInfo{FixedBy} || 0;
1602 29         85 push @valFixups, $makerFixup;
1603 29 100 100     225 if ($previewInfo and not $$previewInfo{NoBaseShift}) {
1604 4         18 $$previewInfo{BaseShift} = $baseShift;
1605             }
1606             }
1607 34         432 $newValuePt = \$newValue; # write new value
1608             }
1609             }
1610 42         224 SetByteOrder($saveOrder);
1611              
1612             # process existing subdirectory unless we are overwriting it entirely
1613             } elsif ($$newInfo{SubDirectory} and $isNew <= 0 and not $isOverwriting
1614             # don't edit directory if Writable is set to 0
1615             and (not defined $$newInfo{Writable} or $$newInfo{Writable}) and
1616             not $$newInfo{ReadFromRAF})
1617             {
1618              
1619 442         1126 my $subdir = $$newInfo{SubDirectory};
1620 442 100 66     2868 if ($$newInfo{SubIFD}) {
    50 33        
1621             #
1622             # rewrite existing sub IFD's
1623             #
1624 106         242 my $subTable = $tagTablePtr;
1625 106 100       472 if ($$subdir{TagTable}) {
1626 15         116 $subTable = Image::ExifTool::GetTagTable($$subdir{TagTable});
1627             }
1628             # determine directory name for this IFD
1629 106   33     553 my $subdirName = $$newInfo{Groups}{1} || $$newInfo{Name};
1630             # all makernotes directory names must be 'MakerNotes'
1631 106 100       618 $subdirName = 'MakerNotes' if $$subTable{GROUPS}{0} eq 'MakerNotes';
1632             # must handle sub-IFD's specially since the values
1633             # are actually offsets to subdirectories
1634 106 50       346 unless ($readCount) { # can't have zero count
1635 0 0       0 return undef if $et->Error("$name entry $index has zero count", 2);
1636 0         0 next;
1637             }
1638 106         264 my $writeCount = 0;
1639 106         199 my $i;
1640 106         249 $newValue = ''; # reset value because we regenerate it below
1641 106         438 for ($i=0; $i<$readCount; ++$i) {
1642 109         345 my $off = $i * $formatSize[$readFormat];
1643 109         609 my $val = ReadValue($valueDataPt, $valuePtr + $off,
1644             $readFormName, 1, $oldSize - $off);
1645 109         284 my $subdirStart = $val - $dataPos;
1646 109         230 my $subdirBase = $base;
1647 109         247 my $hdrLen;
1648 109 50       463 if (defined $$subdir{Start}) {
1649             #### eval Start ($val)
1650 109         9785 my $newStart = eval $$subdir{Start};
1651 109 50       873 unless (Image::ExifTool::IsInt($newStart)) {
1652 0         0 $et->Error("Bad subdirectory start for $$newInfo{Name}");
1653 0         0 next;
1654             }
1655 109         310 $newStart -= $dataPos;
1656 109         237 $hdrLen = $newStart - $subdirStart;
1657 109         248 $subdirStart = $newStart;
1658             }
1659 109 50       440 if ($$subdir{Base}) {
1660 0         0 my $start = $subdirStart + $dataPos;
1661             #### eval Base ($start,$base)
1662 0         0 $subdirBase += eval $$subdir{Base};
1663             }
1664             # add IFD number if more than one
1665 109 100       359 $subdirName =~ s/\d*$/$i/ if $i;
1666             my %subdirInfo = (
1667             Base => $subdirBase,
1668             DataPt => $dataPt,
1669             DataPos => $dataPos - $subdirBase + $base,
1670             DataLen => $dataLen,
1671             DirStart => $subdirStart,
1672             DirName => $subdirName,
1673             Name => $$newInfo{Name},
1674 109 100       1094 TagInfo => $newInfo,
1675             Parent => $dirName,
1676             Fixup => Image::ExifTool::Fixup->new,
1677             RAF => $raf,
1678             Subdir => $subdir,
1679             # set ImageData only for 1st level SubIFD's
1680             ImageData=> $imageDataFlag eq 'Main' ? 'SubIFD' : undef,
1681             );
1682             # pass on header pointer only for certain sub IFD's
1683 109 100       661 $subdirInfo{HeaderPtr} = $$dirInfo{HeaderPtr} if $$newInfo{SubIFD} == 2;
1684 109 50       403 if ($$subdir{RelativeBase}) {
1685             # apply one-time fixup if offsets are relative (Sony IDC hack)
1686 0         0 delete $subdirInfo{Fixup};
1687 0         0 delete $subdirInfo{ImageData};
1688             }
1689             # is the subdirectory outside our current data?
1690 109 100 66     760 if ($subdirStart < 0 or $subdirStart + 2 > $dataLen) {
1691 15 50       150 if ($raf) {
1692             # reset SubDirectory buffer (we will load it later)
1693 15         52 my $buff = '';
1694 15         53 $subdirInfo{DataPt} = \$buff;
1695 15         55 $subdirInfo{DataLen} = 0;
1696             } else {
1697 0         0 my @err = ("Can't read $subdirName data", $inMakerNotes);
1698 0 0 0     0 if ($$subTable{VARS} and $$subTable{VARS}{MINOR_ERRORS}) {
    0          
1699 0         0 $et->Warn($err[0] . '. Ignored.');
1700             } elsif ($et->Error(@err)) {
1701 0         0 return undef;
1702             }
1703 0         0 next Entry; # don't write this directory
1704             }
1705             }
1706 109         1497 my $subdirData = $et->WriteDirectory(\%subdirInfo, $subTable, $$subdir{WriteProc});
1707 109 50       2336 unless (defined $subdirData) {
1708             # WriteDirectory should have issued an error, but check just in case
1709 0 0       0 $et->Error("Error writing $subdirName") unless $$et{VALUE}{Error};
1710 0         0 return undef;
1711             }
1712             # add back original header if necessary (eg. Ricoh GR)
1713 109 0 33     631 if ($hdrLen and $hdrLen > 0 and $subdirStart <= $dataLen) {
      33        
1714 0         0 $subdirData = substr($$dataPt, $subdirStart - $hdrLen, $hdrLen) . $subdirData;
1715 0         0 $subdirInfo{Fixup}{Start} += $hdrLen;
1716             }
1717 109 100       395 unless (length $subdirData) {
1718 6 50       98 next unless $inMakerNotes;
1719             # don't delete MakerNote Sub-IFD's, write empty IFD instead
1720 0         0 $subdirData = "\0" x 6;
1721             # reset SubIFD ImageData and Fixup just to be safe
1722 0         0 delete $subdirInfo{ImageData};
1723 0         0 delete $subdirInfo{Fixup};
1724             }
1725             # handle data blocks that we will transfer later
1726 103 100       437 if (ref $subdirInfo{ImageData}) {
1727 4         11 push @imageData, @{$subdirInfo{ImageData}};
  4         18  
1728 4         20 $$origDirInfo{ImageData} = \@imageData;
1729             }
1730             # temporarily set value to subdirectory index
1731             # (will set to actual offset later when we know what it is)
1732 103         334 $newValue .= Set32u(0xfeedf00d);
1733 103         264 my ($offset, $where);
1734 103 100       320 if ($readCount > 1) {
1735 5         13 $offset = length($valBuff) + $i * 4;
1736 5         14 $where = 'valBuff';
1737             } else {
1738 98         235 $offset = length($dirBuff) + 8;
1739 98         204 $where = 'dirBuff';
1740             }
1741             # add to list of subdirectories we will append later
1742             push @subdirs, {
1743             DataPt => \$subdirData,
1744             Table => $subTable,
1745             Fixup => $subdirInfo{Fixup},
1746             Offset => $offset,
1747             Where => $where,
1748             ImageData => $subdirInfo{ImageData},
1749 103         1323 };
1750 103         1024 ++$writeCount; # count number of subdirs written
1751             }
1752 106 100       376 next unless length $newValue;
1753             # must change location of subdir offset if we deleted
1754             # a directory and only one remains
1755 100 50 33     397 if ($writeCount < $readCount and $writeCount == 1) {
1756 0         0 $subdirs[-1]{Where} = 'dirBuff';
1757 0         0 $subdirs[-1]{Offset} = length($dirBuff) + 8;
1758             }
1759             # set new format to int32u for IFD
1760 100   100     652 $newFormName = $$newInfo{FixFormat} || 'int32u';
1761 100         318 $newFormat = $formatNumber{$newFormName};
1762 100         301 $newValuePt = \$newValue;
1763              
1764             } elsif ((not defined $$subdir{Start} or
1765             $$subdir{Start} =~ /\$valuePtr/) and
1766             $$subdir{TagTable})
1767             {
1768             #
1769             # rewrite other existing subdirectories ('$valuePtr' type only)
1770             #
1771             # set subdirectory Start and Base
1772 336         771 my $subdirStart = $valuePtr;
1773 336 100       847 if ($$subdir{Start}) {
1774             #### eval Start ($valuePtr)
1775 4         405 $subdirStart = eval $$subdir{Start};
1776             # must adjust directory size if start changed
1777 4         23 $oldSize -= $subdirStart - $valuePtr;
1778             }
1779 336         594 my $subdirBase = $base;
1780 336 100       1073 if ($$subdir{Base}) {
1781 1         3 my $start = $subdirStart + $valueDataPos;
1782             #### eval Base ($start,$base)
1783 1         64 $subdirBase += eval $$subdir{Base};
1784             }
1785 336         2058 my $subFixup = Image::ExifTool::Fixup->new;
1786             my %subdirInfo = (
1787             Base => $subdirBase,
1788             DataPt => $valueDataPt,
1789             DataPos => $valueDataPos - $subdirBase + $base,
1790             DataLen => $valueDataLen,
1791             DirStart => $subdirStart,
1792             DirName => $$subdir{DirName},
1793 336         4172 DirLen => $oldSize,
1794             Parent => $dirName,
1795             Fixup => $subFixup,
1796             RAF => $raf,
1797             TagInfo => $newInfo,
1798             );
1799 336 50       1108 unless ($oldSize) {
1800             # replace with dummy data if empty to prevent WriteDirectory
1801             # routines from accessing data they shouldn't
1802 0         0 my $tmp = '';
1803 0         0 $subdirInfo{DataPt} = \$tmp;
1804 0         0 $subdirInfo{DataLen} = 0;
1805 0         0 $subdirInfo{DirStart} = 0;
1806 0         0 $subdirInfo{DataPos} += $subdirStart;
1807             }
1808 336         1436 my $subTable = Image::ExifTool::GetTagTable($$subdir{TagTable});
1809 336         1126 my $oldOrder = GetByteOrder();
1810 336 100       1104 SetByteOrder($$subdir{ByteOrder}) if $$subdir{ByteOrder};
1811 336         2771 $newValue = $et->WriteDirectory(\%subdirInfo, $subTable, $$subdir{WriteProc});
1812 336         1828 SetByteOrder($oldOrder);
1813 336 100       892 if (defined $newValue) {
1814 274         618 my $hdrLen = $subdirStart - $valuePtr;
1815 274 100       860 if ($hdrLen) {
1816 3         19 $newValue = substr($$valueDataPt, $valuePtr, $hdrLen) . $newValue;
1817 3         12 $$subFixup{Start} += $hdrLen;
1818             }
1819 274         622 $newValuePt = \$newValue;
1820             } else {
1821 62         188 $newValuePt = \$oldValue;
1822             }
1823 336 100       1031 unless (length $$newValuePt) {
1824             # don't delete a previously empty makernote directory
1825 1 50 33     9 next if $oldSize or not $inMakerNotes;
1826             }
1827 335 100 100     1402 if ($$subFixup{Pointers} and $subdirInfo{Base} == $base) {
1828 5         8 $$subFixup{Start} += length $valBuff;
1829 5         25 push @valFixups, $subFixup;
1830             } else {
1831             # apply fixup in case we added a header ($hdrLen above)
1832 330         1780 $subFixup->ApplyFixup(\$newValue);
1833             }
1834             }
1835              
1836             } elsif ($$newInfo{OffsetPair}) {
1837             #
1838             # keep track of offsets
1839             #
1840 158   100     778 my $dataTag = $$newInfo{DataTag} || '';
1841 158 100       676 if ($dataTag eq 'CanonVRD') {
    100          
1842             # must decide now if we will write CanonVRD information
1843 10         34 my $hasVRD;
1844 10 100 33     166 if ($$et{NEW_VALUE}{$Image::ExifTool::Extra{CanonVRD}}) {
    50          
1845             # adding or deleting as a block
1846 1 50       11 $hasVRD = $et->GetNewValue('CanonVRD') ? 1 : 0;
1847             } elsif ($$et{DEL_GROUP}{CanonVRD} or
1848             $$et{DEL_GROUP}{Trailer})
1849             {
1850 0         0 $hasVRD = 0; # deleting as a group
1851             } else {
1852 9         35 $hasVRD = ($$newValuePt ne "\0\0\0\0");
1853             }
1854 10 100       43 if ($hasVRD) {
1855             # add a fixup, and set this offset later
1856 1         8 $dirFixup->AddFixup(length($dirBuff) + 8, $dataTag);
1857             } else {
1858             # there is (or will soon be) no VRD information, so set pointer to zero
1859 9         41 $newValue = "\0" x length($$newValuePt);
1860 9         34 $newValuePt = \$newValue;
1861             }
1862             } elsif ($dataTag eq 'OriginalDecisionData') {
1863             # handle Canon OriginalDecisionData (no associated length tag)
1864             # - I'm going out of my way here to preserve data which is
1865             # invalidated anyway by our edits
1866 7         19 my $odd;
1867 7         49 my $oddInfo = Image::ExifTool::GetCompositeTagInfo('OriginalDecisionData');
1868 7 100 66     120 if ($oddInfo and $$et{NEW_VALUE}{$oddInfo}) {
    100          
1869 1         9 $odd = $et->GetNewValue($dataTag);
1870 1 50       5 if ($verbose > 1) {
1871 0 0       0 print $out " - $dirName:$dataTag\n" if $$newValuePt ne "\0\0\0\0";
1872 0 0       0 print $out " + $dirName:$dataTag\n" if $odd;
1873             }
1874 1         2 ++$$et{CHANGED};
1875             } elsif ($$newValuePt ne "\0\0\0\0") {
1876 1 50       4 if (length($$newValuePt) == 4) {
1877 1         11 require Image::ExifTool::Canon;
1878 1         5 my $offset = Get32u($newValuePt,0);
1879             # absolute offset in JPEG images only
1880 1 50       5 $offset += $base unless $$et{FILE_TYPE} eq 'JPEG';
1881 1         8 $odd = Image::ExifTool::Canon::ReadODD($et, $offset);
1882 1 50       6 $odd = $$odd if ref $odd;
1883             } else {
1884 0         0 $et->Error("Invalid $$newInfo{Name}",1);
1885             }
1886             }
1887 7 100       28 if ($odd) {
1888 2         6 my $newOffset = length($valBuff);
1889             # (ODD offset is absolute in JPEG, so add base offset!)
1890 2 100       11 $newOffset += $base if $$et{FILE_TYPE} eq 'JPEG';
1891 2         7 $newValue = Set32u($newOffset);
1892 2         15 $dirFixup->AddFixup(length($dirBuff) + 8, $dataTag);
1893 2         31 $valBuff .= $odd; # add original decision data
1894             } else {
1895 5         13 $newValue = "\0\0\0\0";
1896             }
1897 7         23 $newValuePt = \$newValue;
1898             } else {
1899 141         348 my $offsetInfo = $offsetInfo[$ifd];
1900             # save original values (for updating TIFF_END later)
1901 141         317 my @vals;
1902 141 100       386 if ($isNew <= 0) {
1903 137         504 my $oldOrder = GetByteOrder();
1904             # Minolta A200 stores these in the wrong byte order!
1905 137 50       494 SetByteOrder($$newInfo{ByteOrder}) if $$newInfo{ByteOrder};
1906 137         564 @vals = ReadValue(\$oldValue, 0, $readFormName, $readCount, $oldSize);
1907 137         575 SetByteOrder($oldOrder);
1908 137 100       881 $validateInfo{$newID} = [$newInfo, join(' ',@vals)] unless $$newInfo{IsOffset};
1909             }
1910             # only support int32 pointers (for now)
1911 141 0 33     537 if ($formatSize[$newFormat] != 4 and $$newInfo{IsOffset}) {
1912 0 0       0 $isNew > 0 and warn("Internal error (Offset not int32)"), return undef;
1913 0 0       0 $newCount != $readCount and warn("Wrong count!"), return undef;
1914             # change to int32
1915 0         0 $newFormName = 'int32u';
1916 0         0 $newFormat = $formatNumber{$newFormName};
1917 0         0 $newValue = WriteValue(join(' ',@vals), $newFormName, $newCount);
1918 0 0       0 unless (defined $newValue) {
1919 0         0 warn "Internal error writing offsets for $$newInfo{Name}\n";
1920 0         0 return undef;
1921             }
1922 0         0 $newValuePt = \$newValue;
1923             }
1924 141 100       505 $offsetInfo or $offsetInfo = $offsetInfo[$ifd] = { };
1925             # save location of valuePtr in new directory
1926             # (notice we add 10 instead of 8 for valuePtr because
1927             # we will put a 2-byte count at start of directory later)
1928 141         399 my $ptr = $newStart + length($dirBuff) + 10;
1929 141 50       422 $newCount or $newCount = 1; # make sure count is set for offsetInfo
1930             # save value pointer and value count for each tag
1931 141         829 $$offsetInfo{$newID} = [$newInfo, $ptr, $newCount, \@vals, $newFormat];
1932             }
1933              
1934             } elsif ($$newInfo{DataMember}) {
1935              
1936             # save any necessary data members (Make, Model, etc)
1937 272         563 my $formatStr = $newFormName;
1938 272         489 my $count = $newCount;
1939             # change to specified format if necessary
1940 272 50 33     1039 if ($$newInfo{Format} and $$newInfo{Format} ne $formatStr) {
1941 0         0 $formatStr = $$newInfo{Format};
1942 0         0 my $format = $formatNumber{$formatStr};
1943             # adjust number of items for new format size
1944 0 0       0 $count = int(length($$newValuePt) / $formatSize[$format]) if $format;
1945             }
1946 272         1281 my $val = ReadValue($newValuePt,0,$formatStr,$count,length($$newValuePt));
1947 272         793 my $conv = $$newInfo{RawConv};
1948 272 50       686 if ($conv) {
1949             # let the RawConv store the (possibly converted) data member
1950 272 50       786 if (ref $conv eq 'CODE') {
1951 0         0 &$conv($val, $et);
1952             } else {
1953 272         542 my ($priority, @grps);
1954 272         875 my ($self, $tag, $tagInfo) = ($et, $$newInfo{Name}, $newInfo);
1955             #### eval RawConv ($self, $val, $tag, $tagInfo, $priority, @grps)
1956 272         42518 eval $conv;
1957             }
1958             } else {
1959 0         0 $$et{$$newInfo{DataMember}} = $val;
1960             }
1961             }
1962             }
1963             #
1964             # write out the directory entry
1965             #
1966 5396         11171 my $newSize = length($$newValuePt);
1967 5396         10379 my $fsize = $formatSize[$newFormat];
1968 5396         8347 my $offsetVal;
1969             # set proper count
1970 5396 50 66     27371 $newCount = int(($newSize + $fsize - 1) / $fsize) unless $oldInfo and $$oldInfo{FixedSize};
1971 5396 100 100     17895 if ($saveForValidate{$newID} and $tagTablePtr eq \%Image::ExifTool::Exif::Main) {
1972 153         752 my @vals = ReadValue(\$newValue, 0, $newFormName, $newCount, $newSize);
1973 153         1007 $validateInfo{$newID} = join ' ',@vals;
1974             }
1975 5396 100       11135 if ($newSize > 4) {
1976             # zero-pad to an even number of bytes (required by EXIF standard)
1977             # and make sure we are a multiple of the format size
1978 2447   100     10344 while ($newSize & 0x01 or $newSize < $newCount * $fsize) {
1979 241         641 $$newValuePt .= "\0";
1980 241         1053 ++$newSize;
1981             }
1982 2447         5143 my $entryBased;
1983 2447 100 33     12967 if ($$dirInfo{EntryBased} or ($newInfo and $$newInfo{EntryBased})) {
      66        
1984 5         7 $entryBased = 1;
1985 5         9 $offsetVal = Set32u(length($valBuff) - length($dirBuff));
1986             } else {
1987 2442         8138 $offsetVal = Set32u(length $valBuff);
1988             }
1989 2447         4634 my ($dataTag, $putFirst);
1990 2447 50       9069 ($dataTag, $putFirst) = @$newInfo{'DataTag','PutFirst'} if $newInfo;
1991 2447 100       5565 if ($dataTag) {
1992 2 100 33     24 if ($dataTag eq 'PreviewImage' and ($$et{FILE_TYPE} eq 'JPEG' or
    50 66        
      33        
1993             $$et{GENERATE_PREVIEW_INFO}))
1994             {
1995             # hold onto the PreviewImage until we can determine if it fits
1996             $$et{PREVIEW_INFO} or $$et{PREVIEW_INFO} = {
1997 1 50       10 Data => $$newValuePt,
1998             Fixup => Image::ExifTool::Fixup->new,
1999             };
2000 1 50       6 $$et{PREVIEW_INFO}{ChangeBase} = 1 if $$newInfo{ChangeBase};
2001 1 50 33     5 if ($$newInfo{IsOffset} and $$newInfo{IsOffset} eq '2') {
2002 0         0 $$et{PREVIEW_INFO}{NoBaseShift} = 1;
2003             }
2004             # use original preview size if we will attempt to load it later
2005 1 50       6 $newCount = $oldCount if $$newValuePt eq 'LOAD_PREVIEW';
2006 1         3 $$newValuePt = '';
2007             } elsif ($dataTag eq 'LeicaTrailer' and $$et{LeicaTrailer}) {
2008 0         0 $$newValuePt = '';
2009             }
2010             }
2011 2447 100 66     6804 if ($putFirst and $$dirInfo{HeaderPtr}) {
2012 1         1 my $hdrPtr = $$dirInfo{HeaderPtr};
2013             # place this value immediately after the TIFF header (eg. IIQ maker notes)
2014 1         4 $offsetVal = Set32u(length $$hdrPtr);
2015 1         17 $$hdrPtr .= $$newValuePt;
2016             } else {
2017 2446         6203 $valBuff .= $$newValuePt; # add value data to buffer
2018             # must save a fixup pointer for every pointer in the directory
2019 2446 100       5582 if ($entryBased) {
2020 5 100       10 $entryBasedFixup or $entryBasedFixup = Image::ExifTool::Fixup->new;
2021 5         13 $entryBasedFixup->AddFixup(length($dirBuff) + 8, $dataTag);
2022             } else {
2023 2441         11354 $dirFixup->AddFixup(length($dirBuff) + 8, $dataTag);
2024             }
2025             }
2026             } else {
2027 2949         5420 $offsetVal = $$newValuePt; # save value in offset if 4 bytes or less
2028             # must pad value with zeros if less than 4 bytes
2029 2949 100       9554 $newSize < 4 and $offsetVal .= "\0" x (4 - $newSize);
2030             }
2031             # write the directory entry
2032 5396         15578 $dirBuff .= Set16u($newID) . Set16u($newFormat) .
2033             Set32u($newCount) . $offsetVal;
2034             # update flag to keep track of mandatory tags
2035 5396         18947 while (defined $allMandatory) {
2036 374 100       1450 if (defined $$mandatory{$newID}) {
2037             # values must correspond to mandatory values
2038 186   66     1055 my $form = $$newInfo{Format} || $newFormName;
2039 186         882 my $mandVal = WriteValue($$mandatory{$newID}, $form, $newCount);
2040 186 100 66     1234 if (defined $mandVal and $mandVal eq $$newValuePt) {
2041 177         356 ++$allMandatory; # count mandatory tags
2042 177         579 last;
2043             }
2044             }
2045 197         434 undef $deleteAll;
2046 197         754 undef $allMandatory;
2047             }
2048             }
2049 383 100       1414 if (%validateInfo) {
2050 80         582 ValidateImageData($et, \%validateInfo, $dirName, 1);
2051 80         371 undef %validateInfo;
2052             }
2053 383 50       1307 if ($ignoreCount) {
2054 0 0       0 my $y = $ignoreCount > 1 ? 'ies' : 'y';
2055 0 0       0 my $verb = $$dirInfo{FixBase} ? 'Ignored' : 'Removed';
2056 0         0 $et->Warn("$verb $ignoreCount invalid entr$y from $name", 1);
2057             }
2058 383 50       1207 if ($fixCount) {
2059 0 0       0 my $s = $fixCount > 1 ? 's' : '';
2060 0         0 $et->Warn("Fixed invalid count$s for $fixCount $name tag$s", 1);
2061             }
2062             #..............................................................................
2063             # write directory counts and nextIFD pointer and add value data to end of IFD
2064             #
2065             # determine now if there is or will be another IFD after this one
2066 383         749 my $nextIfdOffset;
2067 383 100       1264 if ($dirEnd + 4 <= $dataLen) {
2068 292         1072 $nextIfdOffset = Get32u($dataPt, $dirEnd);
2069             } else {
2070 91         240 $nextIfdOffset = 0;
2071             }
2072             my $isNextIFD = ($$dirInfo{Multi} and ($nextIfdOffset or
2073             # account for the case where we will create the next IFD
2074             # (IFD1 only, but not in TIFF-format images)
2075             ($dirName eq 'IFD0' and $$et{ADD_DIRS}{'IFD1'} and
2076 383   100     3051 $$et{FILE_TYPE} ne 'TIFF')));
2077             # calculate number of entries in new directory
2078 383         1135 my $newEntries = length($dirBuff) / 12;
2079             # delete entire directory if we deleted a tag and only mandatory tags remain or we
2080             # attempted to create a directory with only mandatory tags and there is no nextIFD
2081 383 100 100     1715 if ($allMandatory and not $isNextIFD and ($newEntries < $numEntries or $numEntries == 0)) {
      100        
      100        
2082 14         36 $newEntries = 0;
2083 14         34 $dirBuff = '';
2084 14         36 $valBuff = '';
2085 14         70 undef $dirFixup; # no fixups in this directory
2086 14 100       61 ++$deleteAll if defined $deleteAll;
2087 14 50       55 $verbose > 1 and print $out " - $allMandatory mandatory tag(s)\n";
2088 14         46 $$et{CHANGED} -= $addMandatory; # didn't change these after all
2089             }
2090 383 100 100     1668 if ($ifd and not $newEntries) {
2091 1 50       7 $verbose and print $out " Deleting IFD1\n";
2092 1         14 last; # don't write IFD1 if empty
2093             }
2094             # apply one-time fixup for entry-based offsets
2095 382 100       1262 if ($entryBasedFixup) {
2096 1         3 $$entryBasedFixup{Shift} = length($dirBuff) + 4;
2097 1         6 $entryBasedFixup->ApplyFixup(\$dirBuff);
2098 1         9 undef $entryBasedFixup;
2099             }
2100             # initialize next IFD pointer to zero
2101 382         1180 my $nextIFD = Set32u(0);
2102             # some cameras use a different amount of padding after the makernote IFD
2103 382 100 100     3803 if ($dirName eq 'MakerNotes' and $$dirInfo{Parent} =~ /^(ExifIFD|IFD0)$/) {
2104 56         371 my ($rel, $pad) = Image::ExifTool::MakerNotes::GetMakerNoteOffset($et);
2105 56 100 100     655 $nextIFD = "\0" x $pad if defined $pad and ($pad==0 or ($pad>4 and $pad<=32));
      66        
2106             }
2107             # add directory entry count to start of IFD and next IFD pointer to end
2108 382         1124 $newData .= Set16u($newEntries) . $dirBuff . $nextIFD;
2109             # get position of value data in newData
2110 382         922 my $valPos = length($newData);
2111             # go back now and set next IFD pointer if this isn't the first IFD
2112 382 100       1164 if ($nextIfdPos) {
2113             # set offset to next IFD
2114 47         229 Set32u($newStart, \$newData, $nextIfdPos);
2115 47         333 $fixup->AddFixup($nextIfdPos,'NextIFD'); # add fixup for this offset in newData
2116             }
2117             # remember position of 'next IFD' pointer so we can set it next time around
2118 382 100       1314 $nextIfdPos = length($nextIFD) ? $valPos - length($nextIFD) : undef;
2119             # add value data after IFD
2120 382         1693 $newData .= $valBuff;
2121             #
2122             # add any subdirectories, adding fixup information
2123             #
2124 382 100       1238 if (@subdirs) {
2125 122         267 my $subdir;
2126 122         329 foreach $subdir (@subdirs) {
2127 139         305 my $len = length($newData); # position of subdirectory in data
2128 139         391 my $subdirFixup = $$subdir{Fixup};
2129 139 50       444 if ($subdirFixup) {
2130 139         354 $$subdirFixup{Start} += $len;
2131 139         674 $fixup->AddFixup($subdirFixup);
2132             }
2133 139         415 my $imageData = $$subdir{ImageData};
2134 139         300 my $blockSize = 0;
2135             # must also update start position for ImageData fixups
2136 139 100       448 if (ref $imageData) {
2137 4         8 my $blockInfo;
2138 4         10 foreach $blockInfo (@$imageData) {
2139 4         12 my ($pos, $size, $pad, $entry, $subFix) = @$blockInfo;
2140 4 50       11 if ($subFix) {
2141 4         24 $$subFix{Start} += $len;
2142             # save expected image data offset for calculating shift later
2143 4         7 $$subFix{BlockLen} = length(${$$subdir{DataPt}}) + $blockSize;
  4         11  
2144             }
2145 4         11 $blockSize += $size + $pad;
2146             }
2147             }
2148 139         249 $newData .= ${$$subdir{DataPt}}; # add subdirectory to our data
  139         1152  
2149 139         293 undef ${$$subdir{DataPt}}; # free memory now
  139         439  
2150             # set the pointer
2151 139         394 my $offset = $$subdir{Offset};
2152             # if offset is in valBuff, it was added to the end of dirBuff
2153             # (plus 4 bytes for nextIFD pointer)
2154 139 100       486 $offset += length($dirBuff) + 4 if $$subdir{Where} eq 'valBuff';
2155 139         340 $offset += $newStart + 2; # get offset in newData
2156             # check to be sure we got the right offset
2157 139 50       512 unless (Get32u(\$newData, $offset) == 0xfeedf00d) {
2158 0         0 $et->Error("Internal error while rewriting $name");
2159 0         0 return undef;
2160             }
2161             # set the offset to the subdirectory data
2162 139         578 Set32u($len, \$newData, $offset);
2163 139         514 $fixup->AddFixup($offset); # add fixup for this offset in newData
2164             }
2165             }
2166             # add fixup for all offsets in directory according to value data position
2167             # (which is at the end of this directory)
2168 382 100       1366 if ($dirFixup) {
2169 369         1167 $$dirFixup{Start} = $newStart + 2;
2170 369         1008 $$dirFixup{Shift} = $valPos - $$dirFixup{Start};
2171 369         1789 $fixup->AddFixup($dirFixup);
2172             }
2173             # add valueData fixups, adjusting for position of value data
2174 382         753 my $valFixup;
2175 382         1117 foreach $valFixup (@valFixups) {
2176 44         125 $$valFixup{Start} += $valPos;
2177 44         145 $fixup->AddFixup($valFixup);
2178             }
2179             # stop if no next IFD pointer
2180 382 100       5314 last unless $isNextIFD; # stop unless scanning for multiple IFD's
2181 49 100       205 if ($nextIfdOffset) {
2182             # continue with next IFD
2183 42         118 $dirStart = $nextIfdOffset - $dataPos;
2184             } else {
2185             # create IFD1 if necessary
2186 7 50       30 $verbose and print $out " Creating IFD1\n";
2187 7         22 my $ifd1 = "\0" x 2; # empty IFD1 data (zero entry count)
2188 7         26 $dataPt = \$ifd1;
2189 7         14 $dirStart = 0;
2190 7         24 $dirLen = $dataLen = 2;
2191             }
2192             # increment IFD name
2193 49 50       637 my $ifdNum = $dirName =~ s/(\d+)$// ? $1 : 0;
2194 49         215 $dirName .= $ifdNum + 1;
2195 49         2224 $name =~ s/\d+$//;
2196 49         1318 $name .= $ifdNum + 1;
2197 49         272 $$et{DIR_NAME} = $$et{PATH}[-1] = $dirName;
2198 49 100       331 next unless $nextIfdOffset;
2199              
2200             # guard against writing the same directory twice
2201 42         112 my $addr = $nextIfdOffset + $base;
2202 42 50       304 if ($$et{PROCESSED}{$addr}) {
2203 0         0 $et->Error("$name pointer references previous $$et{PROCESSED}{$addr} directory", 1);
2204 0         0 last;
2205             }
2206 42         177 $$et{PROCESSED}{$addr} = $name;
2207              
2208 42 50 33     225 if ($dirName eq 'SubIFD1' and not ValidateIFD($dirInfo, $dirStart)) {
2209 0 0       0 if ($$et{TIFF_TYPE} eq 'TIFF') {
    0          
2210 0         0 $et->Error('Ignored bad IFD linked from SubIFD', 1);
2211             } elsif ($verbose) {
2212 0         0 $et->Warn('Ignored bad IFD linked from SubIFD');
2213             }
2214 0         0 last; # don't write bad IFD
2215             }
2216 42 100       200 if ($$et{DEL_GROUP}{$dirName}) {
2217 1 50       6 $verbose and print $out " Deleting $dirName\n";
2218 1 50       7 $raf and $et->Error("Deleting $dirName also deletes subsequent" .
2219             " IFD's and possibly image data", 1);
2220 1         4 ++$$et{CHANGED};
2221 1 50 33     8 if ($$et{DEL_GROUP}{$dirName} == 2 and
2222             $$et{ADD_DIRS}{$dirName})
2223             {
2224 0         0 my $emptyIFD = "\0" x 2; # start with empty IFD
2225 0         0 $dataPt = \$emptyIFD;
2226 0         0 $dirStart = 0;
2227 0         0 $dirLen = $dataLen = 2;
2228             } else {
2229 1         19 last; # don't write this IFD (or any subsequent IFD)
2230             }
2231             } else {
2232 41 50       725 $verbose and print $out " Rewriting $name\n";
2233             }
2234             }
2235             #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2236              
2237             # do our fixups now so we can more easily calculate offsets below
2238 335         2156 $fixup->ApplyFixup(\$newData);
2239             # write Sony HiddenData now if this is an ARW file
2240 335 0 33     1814 if ($$et{HiddenData} and not $$dirInfo{Fixup} and $$et{FILE_TYPE} eq 'TIFF') {
      33        
2241 0         0 $fixup->SetMarkerPointers(\$newData, 'HiddenData', length($newData));
2242 0         0 my $hbuf;
2243 0         0 my $hd = $$et{HiddenData};
2244 0 0 0     0 if ($raf->Seek($$hd{Offset}, 0) and $raf->Read($hbuf, $$hd{Size}) == $$hd{Size} and
      0        
2245             $hbuf =~ /^\x55\x26\x11\x05\0/)
2246             {
2247 0         0 $newData .= $hbuf;
2248             } else {
2249 0         0 $et->Error('Error copying hidden data', 1);
2250             }
2251             }
2252             #
2253             # determine total block size for deferred data
2254             #
2255 335         1018 my $numBlocks = scalar @imageData; # save this so we scan only existing blocks later
2256 335         1999 my $blockSize = 0; # total size of blocks to copy later
2257 335         642 my $blockInfo;
2258 335         908 foreach $blockInfo (@imageData) {
2259 4         15 my ($pos, $size, $pad) = @$blockInfo;
2260 4         12 $blockSize += $size + $pad;
2261             }
2262             #
2263             # copy over image data for IFD's, starting with the last IFD first
2264             #
2265 335 100       1084 if (@offsetInfo) {
2266 60         175 my $ttwLen; # length of MRW TTW segment
2267             my @writeLater; # write image data last
2268 60         341 for ($ifd=$#offsetInfo; $ifd>=-1; --$ifd) {
2269             # build list of offsets to process
2270 162         344 my @offsetList;
2271 162 100       416 if ($ifd >= 0) {
2272 102   50     481 $dirName = $$dirInfo{DirName} || 'unknown';
2273 102 100       382 if ($ifd) {
2274 42         356 $dirName =~ s/\d+$//;
2275 42         143 $dirName .= $ifd;
2276             }
2277 102 100       431 my $offsetInfo = $offsetInfo[$ifd] or next;
2278 70 50 66     372 if ($$offsetInfo{0x111} and $$offsetInfo{0x144}) {
2279             # SubIFD may contain double-referenced data as both strips and tiles
2280             # for Sony ARW files when SonyRawFileType is "Lossless Compressed RAW 2"
2281 0 0 0     0 if ($dirName eq 'SubIFD' and $$et{TIFF_TYPE} eq 'ARW' and
      0        
      0        
      0        
2282             $$offsetInfo{0x117} and $$offsetInfo{0x145} and
2283             $$offsetInfo{0x111}[2]==1) # (must be a single strip or the tile offsets could get out of sync)
2284             {
2285             # check the start offsets to see if they are the same
2286 0 0       0 if ($$offsetInfo{0x111}[3][0] == $$offsetInfo{0x144}[3][0]) {
2287             # some Sony ARW images contain double-referenced raw data stored as both strips
2288             # and tiles. Copy the data using only the strip tags, but store the TileOffets
2289             # information for updating later (see PanasonicRaw:PatchRawDataOffset for a
2290             # description of offsetInfo elements)
2291 0         0 $$offsetInfo{0x111}[5] = $$offsetInfo{0x144}; # hack to save TileOffsets
2292             # delete tile information from offsetInfo because we will copy as strips
2293 0         0 delete $$offsetInfo{0x144};
2294 0         0 delete $$offsetInfo{0x145};
2295             }
2296             } else {
2297 0         0 $et->Error("TIFF $dirName contains both strip and tile data");
2298             }
2299             }
2300             # patch Panasonic RAW/RW2 StripOffsets/StripByteCounts if necessary
2301 70         171 my $stripOffsets = $$offsetInfo{0x111};
2302 70         179 my $rawDataOffset = $$offsetInfo{0x118};
2303 70 50 100     626 if ($stripOffsets and $$stripOffsets[0]{PanasonicHack} or
      33        
      66        
2304             $rawDataOffset and $$rawDataOffset[0]{PanasonicHack})
2305             {
2306 1         13 require Image::ExifTool::PanasonicRaw;
2307 1         10 my $err = Image::ExifTool::PanasonicRaw::PatchRawDataOffset($offsetInfo, $raf, $ifd);
2308 1 50       6 $err and $et->Error($err);
2309             }
2310 70         136 my $tagID;
2311             # loop through all tags in reverse numerical order so we save thumbnail
2312             # data before main image data if both exist in the same IFD
2313 70         551 foreach $tagID (reverse sort { $a <=> $b } keys %$offsetInfo) {
  70         411  
2314 140         331 my $tagInfo = $$offsetInfo{$tagID}[0];
2315 140 100       486 next unless $$tagInfo{IsOffset}; # handle byte counts with offsets
2316 70         255 my $sizeInfo = $$offsetInfo{$$tagInfo{OffsetPair}};
2317 70 50       266 $sizeInfo or $et->Error("No size tag for $dirName:$$tagInfo{Name}"), next;
2318 70         176 my $dataTag = $$tagInfo{DataTag};
2319             # write TIFF image data (strips or tiles) later if requested
2320 70 100 100     866 if ($raf and defined $$origDirInfo{ImageData} and
      66        
      100        
      66        
      66        
2321             ($tagID == 0x111 or $tagID == 0x144 or
2322             # also defer writing of other big data such as JpgFromRaw in NEF
2323             ($$sizeInfo[3][0] and
2324             # (calculate approximate combined size of all blocks)
2325             $$sizeInfo[3][0] * scalar(@{$$sizeInfo[3]}) > 1000000)) and
2326             # but don't defer writing if replacing with new value
2327             (not defined $dataTag or not defined $offsetData{$dataTag}))
2328             {
2329 24         132 push @writeLater, [ $$offsetInfo{$tagID}, $sizeInfo ];
2330             } else {
2331 46         234 push @offsetList, [ $$offsetInfo{$tagID}, $sizeInfo ];
2332             }
2333             }
2334             } else {
2335 60 100       248 last unless @writeLater;
2336             # finally, copy all deferred data
2337 17         51 @offsetList = @writeLater;
2338             }
2339 87         184 my $offsetPair;
2340 87         280 foreach $offsetPair (@offsetList) {
2341 70         145 my ($tagInfo, $offsets, $count, $oldOffset) = @{$$offsetPair[0]};
  70         321  
2342 70         179 my ($cntInfo, $byteCounts, $count2, $oldSize, $format) = @{$$offsetPair[1]};
  70         247  
2343             # must be the same number of offset and byte count values
2344 70 50       255 unless ($count == $count2) {
2345 0         0 $et->Error("Offsets/ByteCounts disagree on count for $$tagInfo{Name}");
2346 0         0 return undef;
2347             }
2348 70         275 my $formatStr = $formatName[$format];
2349             # follow pointer to value data if necessary
2350 70 50       390 $count > 1 and $offsets = Get32u(\$newData, $offsets);
2351 70         202 my $n = $count * $formatSize[$format];
2352 70 50       247 $n > 4 and $byteCounts = Get32u(\$newData, $byteCounts);
2353 70 50 33     568 if ($byteCounts < 0 or $byteCounts + $n > length($newData)) {
2354 0         0 $et->Error("Error reading $$tagInfo{Name} byte counts");
2355 0         0 return undef;
2356             }
2357             # get offset base and data pos (abnormal for some preview images)
2358 70         171 my ($dbase, $dpos, $wrongBase, $subIfdDataFixup);
2359 70 100       293 if ($$tagInfo{IsOffset} eq '2') {
2360 2         5 $dbase = $firstBase;
2361 2         7 $dpos = $dataPos + $base - $firstBase;
2362             } else {
2363 68         153 $dbase = $base;
2364 68         144 $dpos = $dataPos;
2365             }
2366             # use different base if necessary for some offsets (Minolta A200)
2367 70 50       260 if ($$tagInfo{WrongBase}) {
2368 0         0 my $self = $et;
2369             #### eval WrongBase ($self)
2370 0   0     0 $wrongBase = eval $$tagInfo{WrongBase} || 0;
2371 0         0 $dbase += $wrongBase;
2372 0         0 $dpos -= $wrongBase;
2373             } else {
2374 70         153 $wrongBase = 0;
2375             }
2376 70         313 my $oldOrder = GetByteOrder();
2377 70         202 my $dataTag = $$tagInfo{DataTag};
2378             # use different byte order for values of this offset pair if required (Minolta A200)
2379 70 50       268 SetByteOrder($$tagInfo{ByteOrder}) if $$tagInfo{ByteOrder};
2380             # transfer the data referenced by all offsets of this tag
2381 70         281 for ($n=0; $n<$count; ++$n) {
2382 70         190 my ($oldEnd, $size);
2383 70 100 66     512 if (@$oldOffset and @$oldSize) {
2384             # calculate end offset of this block
2385 68         182 $oldEnd = $$oldOffset[$n] + $$oldSize[$n];
2386             # update TIFF_END as if we read this data from file
2387 68         363 UpdateTiffEnd($et, $oldEnd + $dbase);
2388             }
2389 70         205 my $offsetPos = $offsets + $n * 4;
2390 70         201 my $byteCountPos = $byteCounts + $n * $formatSize[$format];
2391 70 100       290 if ($$tagInfo{PanasonicHack}) {
2392             # use actual raw data length (may be different than StripByteCounts!)
2393 1         4 $size = $$oldSize[$n];
2394             } else {
2395             # use size of new data
2396 69         333 $size = ReadValue(\$newData, $byteCountPos, $formatStr, 1, 4);
2397             }
2398 70         218 my $offset = $$oldOffset[$n];
2399 70 100       224 if (defined $offset) {
    50          
2400 68         185 $offset -= $dpos;
2401             } elsif ($size != 0xfeedfeed) {
2402 0         0 $et->Error('Internal error (no offset)');
2403 0         0 return undef;
2404             }
2405 70         182 my $newOffset = length($newData) - $wrongBase;
2406 70         159 my $buff;
2407             # look for 'feed' code to use our new data
2408 70 100 66     665 if ($size == 0xfeedfeed) {
    100 66        
    100 66        
    50 33        
    100 33        
    50 33        
    50          
2409 4 50       18 unless (defined $dataTag) {
2410 0         0 $et->Error("No DataTag defined for $$tagInfo{Name}");
2411 0         0 return undef;
2412             }
2413 4 50       21 unless (defined $offsetData{$dataTag}) {
2414 0         0 $et->Error("Internal error (no $dataTag)");
2415 0         0 return undef;
2416             }
2417 4 50       16 if ($count > 1) {
2418 0         0 $et->Error("Can't modify $$tagInfo{Name} with count $count");
2419 0         0 return undef;
2420             }
2421 4         12 $buff = $offsetData{$dataTag};
2422 4 50       18 if ($formatSize[$format] != 4) {
2423 0         0 $et->Error("$$cntInfo{Name} is not int32");
2424 0         0 return undef;
2425             }
2426             # set the data size
2427 4         10 $size = length($buff);
2428 4         13 Set32u($size, \$newData, $byteCountPos);
2429             } elsif ($ifd < 0) {
2430             # hack for fixed-offset data (Panasonic GH6)
2431 24 50       95 if ($$offsetPair[0][6]) {
2432 0 0       0 if ($count > 1) {
2433 0         0 $et->Error("Can't handle fixed offsets with count > 1");
2434             } else {
2435 0         0 my $fixedOffset = Get32u(\$newData, $offsets);
2436 0         0 my $padToFixedOffset = $fixedOffset - ($newOffset + $dpos);
2437             # account for blocks that come before this (Pansonic DC-S1RM2, forum17319)
2438 0         0 $padToFixedOffset -= $$_[1] + $$_[2] foreach @imageData;
2439 0 0       0 if ($padToFixedOffset < 0) {
2440 0         0 $et->Error('Metadata too large to fit before fixed-offset image data');
2441             } else {
2442             # add necessary padding before raw data
2443 0         0 push @imageData, [$offset+$dbase+$dpos, 0, $padToFixedOffset];
2444 0         0 $newOffset += $padToFixedOffset;
2445 0         0 $et->Warn("Adding $padToFixedOffset bytes of padding before fixed-offset image data", 1);
2446             }
2447             }
2448             }
2449             # pad if necessary (but don't pad contiguous image blocks)
2450 24         89 my $pad = 0;
2451 24 0 33     126 ++$pad if ($blockSize + $size) & 0x01 and ($n+1 >= $count or
      66        
2452             not $oldEnd or $oldEnd != $$oldOffset[$n+1]);
2453             # preserve original image padding if specified
2454 24 0 66     130 if ($$origDirInfo{PreserveImagePadding} and $n+1 < $count and
      33        
      33        
2455             $oldEnd and $$oldOffset[$n+1] > $oldEnd)
2456             {
2457 0         0 $pad = $$oldOffset[$n+1] - $oldEnd;
2458             }
2459             # copy data later
2460 24         94 push @imageData, [$offset+$dbase+$dpos, $size, $pad];
2461 24         52 $newOffset += $blockSize; # data comes after other deferred data
2462             # create fixup for SubIFD ImageData
2463 24 100 66     127 if ($imageDataFlag eq 'SubIFD' and not $subIfdDataFixup) {
2464 4         36 $subIfdDataFixup = Image::ExifTool::Fixup->new;
2465 4         18 $imageData[-1][4] = $subIfdDataFixup;
2466             }
2467 24         54 $size += $pad; # account for pad byte if necessary
2468             # return ImageData list
2469 24         96 $$origDirInfo{ImageData} = \@imageData;
2470             } elsif ($offset >= 0 and $offset+$size <= $dataLen) {
2471             # take data from old dir data buffer
2472 37         233 $buff = substr($$dataPt, $offset, $size);
2473             } elsif ($$et{TIFF_TYPE} eq 'MRW') {
2474             # TTW segment must be an even 4 bytes long, so pad now if necessary
2475 0         0 my $n = length $newData;
2476 0 0       0 $buff = ($n & 0x03) ? "\0" x (4 - ($n & 0x03)) : '';
2477 0         0 $size = length($buff);
2478             # data exists after MRW TTW segment
2479 0 0       0 $ttwLen = length($newData) + $size unless defined $ttwLen;
2480 0         0 $newOffset = $offset + $dpos + $ttwLen - $dataLen;
2481             } elsif ($raf and $raf->Seek($offset+$dbase+$dpos,0) and
2482             $raf->Read($buff,$size) == $size)
2483             {
2484             # (data was read OK)
2485             # patch incorrect ThumbnailOffset in Sony A100 1.00 ARW images
2486 4 0 33     29 if ($$et{TIFF_TYPE} eq 'ARW' and $$tagInfo{Name} eq 'ThumbnailOffset' and
      33        
      0        
2487             $$et{Model} eq 'DSLR-A100' and $buff !~ /^\xff\xd8\xff/)
2488             {
2489 0         0 my $pos = $offset + $dbase + $dpos;
2490 0         0 my $try;
2491 0 0 0     0 if ($pos < 0x10000 and $raf->Seek($pos+0x10000,0) and
      0        
      0        
2492             $raf->Read($try,$size) == $size and $try =~ /^\xff\xd8\xff/)
2493             {
2494 0         0 $buff = $try;
2495 0         0 $et->Warn('Adjusted incorrect A100 ThumbnailOffset', 1);
2496             } else {
2497 0         0 $et->Error('Invalid ThumbnailImage');
2498             }
2499             }
2500             } elsif ($$tagInfo{Name} eq 'ThumbnailOffset' and $offset>=0 and $offset<$dataLen) {
2501             # Grrr. The Canon 350D writes the thumbnail with an incorrect byte count
2502 0         0 my $diff = $offset + $size - $dataLen;
2503 0         0 $et->Warn("ThumbnailImage runs outside EXIF data by $diff bytes (truncated)",1);
2504             # set the size to the available data
2505 0         0 $size -= $diff;
2506 0 0       0 unless (WriteValue($size, $formatStr, 1, \$newData, $byteCountPos)) {
2507 0         0 warn 'Internal error writing thumbnail size';
2508             }
2509             # get the truncated image
2510 0         0 $buff = substr($$dataPt, $offset, $size);
2511             } elsif ($$tagInfo{Name} eq 'PreviewImageStart' and $$et{FILE_TYPE} eq 'JPEG') {
2512             # try to load the preview image using the specified offset
2513 1         3 undef $buff;
2514 1         4 my $r = $$et{RAF};
2515 1 50 33     13 if ($r and not $raf) {
2516 1         8 my $tell = $r->Tell();
2517             # read and validate
2518 1 50 33     7 undef $buff unless $r->Seek($offset+$base+$dataPos,0) and
      33        
2519             $r->Read($buff,$size) == $size and
2520             $buff =~ /^.\xd8\xff[\xc4\xdb\xe0-\xef]/s;
2521 1 50       5 $r->Seek($tell, 0) or $et->Error('Seek error'), return undef;
2522             }
2523             # set flag if we must load PreviewImage
2524 1 50       6 $buff = 'LOAD_PREVIEW' unless defined $buff;
2525             } else {
2526 0   0     0 my $dataName = $dataTag || $$tagInfo{Name};
2527 0 0       0 return undef if $et->Error("Error reading $dataName data in $name", $inMakerNotes);
2528 0         0 $buff = '';
2529             }
2530 70 100       357 if ($$tagInfo{Name} eq 'PreviewImageStart') {
2531 14 100 66     157 if ($$et{FILE_TYPE} eq 'JPEG' and not $$tagInfo{MakerPreview}) {
    50 33        
2532 8 100       30 if ($size) {
2533             # hold onto the PreviewImage until we can determine if it fits
2534             $$et{PREVIEW_INFO} or $$et{PREVIEW_INFO} = {
2535 5 100       35 Data => $buff,
2536             Fixup => Image::ExifTool::Fixup->new,
2537             };
2538 5 100 66     49 if ($$tagInfo{IsOffset} and $$tagInfo{IsOffset} eq '2') {
2539 1         4 $$et{PREVIEW_INFO}{NoBaseShift} = 1;
2540             }
2541 5 50 33     30 if ($offset >= 0 and $offset+$size <= $dataLen) {
2542             # set flag indicating this preview wasn't in a trailer
2543 5         15 $$et{PREVIEW_INFO}{WasContained} = 1;
2544             }
2545             }
2546 8         22 $buff = '';
2547             } elsif ($$et{TIFF_TYPE} eq 'ARW' and $$et{Model} eq 'DSLR-A100') {
2548             # the A100 double-references the same preview, so ignore the
2549             # second one (the offset and size will be patched later)
2550 0 0       0 next if $$et{A100PreviewLength};
2551 0 0       0 $$et{A100PreviewLength} = length $buff if defined $buff;
2552             }
2553             }
2554             # update offset accordingly and add to end of new data
2555 70         352 Set32u($newOffset, \$newData, $offsetPos);
2556             # add a pointer to fix up this offset value (marked with DataTag name)
2557 70         389 $fixup->AddFixup($offsetPos, $dataTag);
2558             # also add to subIfdDataFixup if necessary
2559 70 100       312 $subIfdDataFixup->AddFixup($offsetPos, $dataTag) if $subIfdDataFixup;
2560             # must also (sometimes) update StripOffsets in Panasonic RW2 images
2561             # and TileOffsets in Sony ARW images
2562 70         203 my $otherPos = $$offsetPair[0][5];
2563 70 50       234 if ($otherPos) {
2564 0 0       0 if ($$tagInfo{PanasonicHack}) {
    0          
2565 0         0 Set32u($newOffset, \$newData, $otherPos);
2566 0         0 $fixup->AddFixup($otherPos, $dataTag);
2567             } elsif (ref $otherPos eq 'ARRAY') {
2568             # the image data was copied as one large strip, and is double-referenced
2569             # as tile data, so all we need to do now is properly update the tile offsets
2570 0         0 my $oldRawDataOffset = $$offsetPair[0][3][0];
2571 0         0 my $count = $$otherPos[2];
2572 0         0 my $i;
2573             # point to offsets in value data if more than one pointer
2574 0 0       0 $$otherPos[1] = Get32u(\$newData, $$otherPos[1]) if $count > 1;
2575 0         0 for ($i=0; $i<$count; ++$i) {
2576 0         0 my $oldTileOffset = $$otherPos[3][$i];
2577 0         0 my $ptrPos = $$otherPos[1] + 4 * $i;
2578 0         0 Set32u($newOffset + $oldTileOffset - $oldRawDataOffset, \$newData, $ptrPos);
2579 0         0 $fixup->AddFixup($ptrPos, $dataTag);
2580 0 0       0 $subIfdDataFixup->AddFixup($ptrPos, $dataTag) if $subIfdDataFixup;
2581             }
2582             }
2583             }
2584 70 100       231 if ($ifd >= 0) {
2585             # buff length must be even (Note: may have changed since $size was set)
2586 46 100       221 $buff .= "\0" if length($buff) & 0x01;
2587 46         302 $newData .= $buff; # add this strip to the data
2588             } else {
2589 24         102 $blockSize += $size; # keep track of total size
2590             }
2591             }
2592 70         266 SetByteOrder($oldOrder);
2593             }
2594             }
2595             # verify that nothing else got written after determining TTW length
2596 60 50 33     336 if (defined $ttwLen and $ttwLen != length($newData)) {
2597 0         0 $et->Error('Internal error writing MRW TTW');
2598             }
2599             }
2600             #
2601             # set offsets and generate fixups for tag values which were too large for memory
2602             #
2603 335         779 $blockSize = 0;
2604 335         859 foreach $blockInfo (@imageData) {
2605 28         106 my ($pos, $size, $pad, $entry, $subFix) = @$blockInfo;
2606 28 50       113 if (defined $entry) {
2607 0         0 my $format = Get16u(\$newData, $entry + 2);
2608 0 0 0     0 if ($format < 1 or $format > 13) {
2609 0         0 $et->Error('Internal error copying huge value');
2610 0         0 last;
2611             } else {
2612             # set count and offset in directory entry
2613 0         0 Set32u($size / $formatSize[$format], \$newData, $entry + 4);
2614 0         0 Set32u(length($newData)+$blockSize, \$newData, $entry + 8);
2615 0         0 $fixup->AddFixup($entry + 8);
2616             # create special fixup for SubIFD data
2617 0 0       0 if ($imageDataFlag eq 'SubIFD') {
2618 0         0 my $subIfdDataFixup = Image::ExifTool::Fixup->new;
2619 0         0 $subIfdDataFixup->AddFixup($entry + 8);
2620             # save fixup in imageData list
2621 0         0 $$blockInfo[4] = $subIfdDataFixup;
2622             }
2623             # must reset entry pointer so we don't use it again in a parent IFD!
2624 0         0 $$blockInfo[3] = undef;
2625             }
2626             }
2627             # apply additional shift required for contained SubIFD image data offsets
2628 28 100 100     171 if ($subFix and defined $$subFix{BlockLen} and $numBlocks > 0) {
      66        
2629             # our offset expects the data at the end of the SubIFD block (BlockLen + Start),
2630             # but it will actually be at length($newData) + $blockSize. So adjust
2631             # accordingly (and subtract an extra Start because this shift is applied later)
2632 4         14 $$subFix{Shift} += length($newData) - $$subFix{BlockLen} - 2 * $$subFix{Start} + $blockSize;
2633 4         17 $subFix->ApplyFixup(\$newData);
2634             }
2635 28         87 $blockSize += $size + $pad;
2636 28         67 --$numBlocks;
2637             }
2638             #
2639             # apply final shift to new data position if this is the top level IFD
2640             #
2641 335 100       1462 unless ($$dirInfo{Fixup}) {
2642 126         443 my $hdrPtr = $$dirInfo{HeaderPtr};
2643 126 100 50     770 my $newDataPos = $hdrPtr ? length $$hdrPtr : $$dirInfo{NewDataPos} || 0;
2644             # adjust CanonVRD offset to point to end of regular TIFF if necessary
2645             # (NOTE: This will be incorrect if multiple trailers exist,
2646             # but it is unlikely that it could ever be correct in this case anyway.
2647             # Also, this doesn't work for JPEG images (but CanonDPP doesn't set
2648             # this when editing JPEG images anyway))
2649 126         1065 $fixup->SetMarkerPointers(\$newData, 'CanonVRD', length($newData) + $blockSize);
2650 126 50       517 if ($newDataPos) {
2651 126         483 $$fixup{Shift} += $newDataPos;
2652 126         545 $fixup->ApplyFixup(\$newData);
2653             }
2654             # save fixup for adjusting Leica trailer and Sony HiddenData offsets if necessary
2655 126 50       764 $$et{LeicaTrailer}{Fixup}->AddFixup($fixup) if $$et{LeicaTrailer};
2656 126 50       526 $$et{HiddenData}{Fixup}->AddFixup($fixup) if $$et{HiddenData};
2657             # save fixup for PreviewImage in JPEG file if necessary
2658 126         373 my $previewInfo = $$et{PREVIEW_INFO};
2659 126 100 66     1278 if ($previewInfo) {
    100          
    50          
2660 5         20 my $pt = \$$previewInfo{Data}; # image data or 'LOAD_PREVIEW' flag
2661             # now that we know the size of the EXIF data, first test to see if our new image fits
2662             # inside the EXIF segment (remember about the TIFF and EXIF headers: 8+6 bytes)
2663 5 50 33     90 if (($$pt ne 'LOAD_PREVIEW' and length($$pt) + length($newData) + 14 <= 0xfffd and
      33        
      33        
2664             not $$previewInfo{IsTrailer}) or
2665             $$previewInfo{IsShort}) # must fit in this segment if using short pointers
2666             {
2667             # It fits! (or must exist in EXIF segment), so fixup the
2668             # PreviewImage pointers and stuff the preview image in here
2669 5         16 my $newPos = length($newData) + $newDataPos;
2670 5   50     31 $newPos += ($$previewInfo{BaseShift} || 0);
2671 5 50       31 if ($$previewInfo{Relative}) {
2672             # calculate our base by looking at how far the pointer got shifted
2673 0   0     0 $newPos -= ($fixup->GetMarkerPointers(\$newData, 'PreviewImage') || 0);
2674             }
2675 5         30 $fixup->SetMarkerPointers(\$newData, 'PreviewImage', $newPos);
2676 5         49 $newData .= $$pt;
2677             # set flag to delete old preview unless it was contained in the EXIF
2678 5 50       29 $$et{DEL_PREVIEW} = 1 unless $$et{PREVIEW_INFO}{WasContained};
2679 5         19 delete $$et{PREVIEW_INFO}; # done with our preview data
2680             } else {
2681             # Doesn't fit, or we still don't know, so save fixup information
2682             # and put the preview at the end of the file
2683 0 0       0 $$previewInfo{Fixup} or $$previewInfo{Fixup} = Image::ExifTool::Fixup->new;
2684 0         0 $$previewInfo{Fixup}->AddFixup($fixup);
2685             }
2686             } elsif (defined $newData and $deleteAll) {
2687 6         22 $newData = ''; # delete both IFD0 and IFD1 since only mandatory tags remain
2688             } elsif ($$et{A100PreviewLength}) {
2689             # save preview image start for patching A100 quirks later
2690 0         0 $$et{A100PreviewStart} = $fixup->GetMarkerPointers(\$newData, 'PreviewImage');
2691             }
2692             # save location of last IFD for use in Canon RAW header
2693 126 100       531 if ($newDataPos == 16) {
2694 6         48 my @ifdPos = $fixup->GetMarkerPointers(\$newData,'NextIFD');
2695 6         27 $$origDirInfo{LastIFD} = pop @ifdPos;
2696             }
2697             # recrypt SR2 SubIFD data if necessary
2698 126         390 my $key = $$et{SR2SubIFDKey};
2699 126 50       603 if ($key) {
2700 0         0 my $start = $fixup->GetMarkerPointers(\$newData, 'SR2SubIFDOffset');
2701 0         0 my $len = $$et{SR2SubIFDLength};
2702             # (must subtract 8 for size of TIFF header)
2703 0 0 0     0 if ($start and $start - 8 + $len <= length $newData) {
2704 0         0 require Image::ExifTool::Sony;
2705 0         0 Image::ExifTool::Sony::Decrypt(\$newData, $start - 8, $len, $key);
2706             }
2707             }
2708             }
2709             # return empty string if no entries in directory
2710             # (could be up to 10 bytes and still be empty)
2711 335 100 66     2036 $newData = '' if defined $newData and length($newData) < 12;
2712              
2713             # set changed if ForceWrite tag was set to "EXIF"
2714 335 50 66     2783 ++$$et{CHANGED} if defined $newData and length $newData and $$et{FORCE_WRITE}{EXIF};
      66        
2715              
2716 335         4713 return $newData; # return our directory data
2717             }
2718              
2719             1; # end
2720              
2721             __END__