File Coverage

blib/lib/Image/ExifTool/WriteExif.pl
Criterion Covered Total %
statement 1008 1417 71.1
branch 579 976 59.3
condition 398 766 51.9
subroutine 11 16 68.7
pod 0 13 0.0
total 1996 3188 62.6


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