Debian Codegraph @

core/libs/dngwriter/extra/dng_sdk/dng_negative.cpp

raw
1 /*****************************************************************************/
2 // Copyright 2006-2021 Adobe Systems Incorporated
3 // All Rights Reserved.
4 //
5 // NOTICE: Adobe permits you to use, modify, and distribute this file in
6 // accordance with the terms of the Adobe license agreement accompanying it.
7 /*****************************************************************************/
8
9 #include "dng_negative.h"
10
11 #include "dng_1d_table.h"
12 #include "dng_abort_sniffer.h"
13 #include "dng_area_task.h"
14 #include "dng_assertions.h"
15 #include "dng_big_table.h"
16 #include "dng_bottlenecks.h"
17 #include "dng_camera_profile.h"
18 #include "dng_color_space.h"
19 #include "dng_color_spec.h"
20 #include "dng_exceptions.h"
21 #include "dng_file_stream.h"
22 #include "dng_gain_map.h"
23 #include "dng_globals.h"
24 #include "dng_host.h"
25 #include "dng_image.h"
26 #include "dng_image_writer.h"
27 #include "dng_info.h"
28 #include "dng_jpeg_image.h"
29 #include "dng_jxl.h"
30 #include "dng_linearization_info.h"
31 #include "dng_memory.h"
32 #include "dng_memory_stream.h"
33 #include "dng_misc_opcodes.h"
34 #include "dng_mosaic_info.h"
35 #include "dng_preview.h"
36 #include "dng_read_image.h"
37 #include "dng_resample.h"
38 #include "dng_safe_arithmetic.h"
39 #include "dng_sdk_limits.h"
40 #include "dng_tag_codes.h"
41 #include "dng_tag_values.h"
42 #include "dng_tile_iterator.h"
43 #include "dng_uncopyable.h"
44 #include "dng_utils.h"
45
46 #if qDNGUseXMP
47 #include "dng_xmp.h"
48 #endif
49
50 /*****************************************************************************/
51
52 void dng_semantic_mask::CalcMaskSubArea (dng_point &origin,
53 dng_rect &wholeImageArea) const
54 {
55
56 origin.v = (int32) fMaskSubArea [0]; // top
57 origin.h = (int32) fMaskSubArea [1]; // left
58
59 wholeImageArea.t = (int32) 0;
60 wholeImageArea.l = (int32) 0;
61 wholeImageArea.b = (int32) fMaskSubArea [3]; // height
62 wholeImageArea.r = (int32) fMaskSubArea [2]; // width
63
64 }
65
66 /*****************************************************************************/
67
68 bool dng_semantic_mask::IsMaskSubAreaValid () const
69 {
70
71 // Can't do full check without mask itself.
72
73 if (!fMask)
74 {
75 return false;
76 }
77
78 dng_point origin;
79
80 dng_rect wholeImageArea;
81
82 CalcMaskSubArea (origin, wholeImageArea);
83
84 const dng_point maskSize = fMask->Bounds ().Size ();
85
86 dng_rect crop;
87
88 crop.t = origin.v;
89 crop.l = origin.h;
90 crop.b = origin.v + maskSize.v;
91 crop.r = origin.h + maskSize.h;
92
93 if ((crop & wholeImageArea) != crop)
94 {
95 return false;
96 }
97
98 return true;
99
100 }
101
102 /*****************************************************************************/
103
104 dng_noise_profile::dng_noise_profile ()
105
106 : fNoiseFunctions ()
107
108 {
109
110 }
111
112 /*****************************************************************************/
113
114 dng_noise_profile::dng_noise_profile (const dng_std_vector<dng_noise_function> &functions)
115
116 : fNoiseFunctions (functions)
117
118 {
119
120 }
121
122 /*****************************************************************************/
123
124 bool dng_noise_profile::IsValid () const
125 {
126
127 if (NumFunctions () == 0 || NumFunctions () > kMaxColorPlanes)
128 {
129 return false;
130 }
131
132 for (uint32 plane = 0; plane < NumFunctions (); plane++)
133 {
134
135 if (!NoiseFunction (plane).IsValid ())
136 {
137 return false;
138 }
139
140 }
141
142 return true;
143
144 }
145
146 /*****************************************************************************/
147
148 bool dng_noise_profile::IsValidForNegative (const dng_negative &negative) const
149 {
150
151 if (!(NumFunctions () == 1 || NumFunctions () == negative.ColorChannels ()))
152 {
153 return false;
154 }
155
156 return IsValid ();
157
158 }
159
160 /*****************************************************************************/
161
162 const dng_noise_function & dng_noise_profile::NoiseFunction (uint32 plane) const
163 {
164
165 if (NumFunctions () == 1)
166 {
167 return fNoiseFunctions.front ();
168 }
169
170 DNG_REQUIRE (plane < NumFunctions (),
171 "Bad plane index argument for NoiseFunction ().");
172
173 return fNoiseFunctions [plane];
174
175 }
176
177 /*****************************************************************************/
178
179 uint32 dng_noise_profile::NumFunctions () const
180 {
181 return (uint32) fNoiseFunctions.size ();
182 }
183
184 /*****************************************************************************/
185
186 bool dng_noise_profile::operator== (const dng_noise_profile &profile) const
187 {
188
189 if (IsValid ())
190 {
191
192 if (!profile.IsValid ())
193 {
194 return false;
195 }
196
197 if (NumFunctions () != profile.NumFunctions ())
198 {
199 return false;
200 }
201
202 for (uint32 plane = 0; plane < NumFunctions (); plane++)
203 {
204
205 if (NoiseFunction (plane).Scale () != profile.NoiseFunction (plane).Scale () ||
206 NoiseFunction (plane).Offset () != profile.NoiseFunction (plane).Offset ())
207 {
208 return false;
209 }
210
211 }
212
213 return true;
214
215 }
216
217 else
218 return !profile.IsValid ();
219
220 }
221
222 /*****************************************************************************/
223
224 dng_metadata::dng_metadata (dng_host &host)
225
226 : fHasBaseOrientation (false)
227 , fBaseOrientation ()
228 , fIsMakerNoteSafe (false)
229 , fMakerNote ()
230 , fExif (host.Make_dng_exif ())
231 , fOriginalExif ()
232 , fIPTCBlock ()
233 , fIPTCOffset (kDNGStreamInvalidOffset)
234
235 #if qDNGUseXMP
236 , fXMP (host.Make_dng_xmp ())
237 #endif
238
239 , fEmbeddedXMPDigest ()
240 , fXMPinSidecar (false)
241 , fXMPisNewer (false)
242 , fSourceMIME ()
243 , fBigTableDictionary ()
244 , fBigTableIndex ()
245
246 {
247 }
248
249 /*****************************************************************************/
250
251 dng_metadata::~dng_metadata ()
252 {
253 }
254
255 /******************************************************************************/
256
257 template< class T >
258 T * CloneAutoPtr (const AutoPtr< T > &ptr)
259 {
260
261 return ptr.Get () ? ptr->Clone () : NULL;
262
263 }
264
265 /******************************************************************************/
266
267 template< class T, typename U >
268 T * CloneAutoPtr (const AutoPtr< T > &ptr, U &u)
269 {
270
271 return ptr.Get () ? ptr->Clone (u) : NULL;
272
273 }
274
275 /******************************************************************************/
276
277 dng_metadata::dng_metadata (const dng_metadata &rhs,
278 dng_memory_allocator &allocator)
279
280 : fHasBaseOrientation (rhs.fHasBaseOrientation)
281 , fBaseOrientation (rhs.fBaseOrientation)
282 , fIsMakerNoteSafe (rhs.fIsMakerNoteSafe)
283 , fMakerNote (CloneAutoPtr (rhs.fMakerNote, allocator))
284 , fExif (CloneAutoPtr (rhs.fExif))
285 , fOriginalExif (CloneAutoPtr (rhs.fOriginalExif))
286 , fIPTCBlock (CloneAutoPtr (rhs.fIPTCBlock, allocator))
287 , fIPTCOffset (rhs.fIPTCOffset)
288
289 #if qDNGUseXMP
290 , fXMP (CloneAutoPtr (rhs.fXMP))
291 #endif
292
293 , fEmbeddedXMPDigest (rhs.fEmbeddedXMPDigest)
294 , fXMPinSidecar (rhs.fXMPinSidecar)
295 , fXMPisNewer (rhs.fXMPisNewer)
296 , fSourceMIME (rhs.fSourceMIME)
297 , fBigTableDictionary (rhs.fBigTableDictionary)
298 , fBigTableIndex (rhs.fBigTableIndex)
299 , fBigTableGroupIndex (rhs.fBigTableGroupIndex)
300 , fImageSequenceInfo (rhs.fImageSequenceInfo)
301 , fImageStats (rhs.fImageStats)
302
303 {
304
305 }
306
307 /******************************************************************************/
308
309 dng_metadata * dng_metadata::Clone (dng_memory_allocator &allocator) const
310 {
311
312 return new dng_metadata (*this, allocator);
313
314 }
315
316 /******************************************************************************/
317
318 void dng_metadata::SetBaseOrientation (const dng_orientation &orientation)
319 {
320
321 fHasBaseOrientation = true;
322
323 fBaseOrientation = orientation;
324
325 }
326
327 /******************************************************************************/
328
329 void dng_metadata::ApplyOrientation (const dng_orientation &orientation)
330 {
331
332 fBaseOrientation += orientation;
333
334 #if qDNGUseXMP
335 fXMP->SetOrientation (fBaseOrientation);
336 #endif
337
338 }
339
340 /*****************************************************************************/
341
342 void dng_metadata::ResetExif (dng_exif * newExif)
343 {
344
345 fExif.Reset (newExif);
346
347 }
348
349 /******************************************************************************/
350
351 dng_memory_block * dng_metadata::BuildExifBlock (dng_memory_allocator &allocator,
352 const dng_resolution *resolution,
353 bool includeIPTC,
354 const dng_jpeg_preview *thumbnail,
355 const uint32 numLeadingZeroBytes) const
356 {
357
358 dng_memory_stream stream (allocator);
359
360 {
361
362 // Create the main IFD
363
364 dng_tiff_directory mainIFD;
365
366 // Optionally include the resolution tags.
367
368 dng_resolution res;
369
370 if (resolution)
371 {
372 res = *resolution;
373 }
374
375 tag_urational tagXResolution (tcXResolution, res.fXResolution);
376 tag_urational tagYResolution (tcYResolution, res.fYResolution);
377
378 tag_uint16 tagResolutionUnit (tcResolutionUnit, res.fResolutionUnit);
379
380 if (resolution)
381 {
382 mainIFD.Add (&tagXResolution );
383 mainIFD.Add (&tagYResolution );
384 mainIFD.Add (&tagResolutionUnit);
385 }
386
387 // Optionally include IPTC block.
388
389 tag_iptc tagIPTC (IPTCData (),
390 IPTCLength ());
391
392 if (includeIPTC && tagIPTC.Count ())
393 {
394 mainIFD.Add (&tagIPTC);
395 }
396
397 // Exif tags.
398
399 exif_tag_set exifSet (mainIFD,
400 *GetExif (),
401 IsMakerNoteSafe (),
402 MakerNoteData (),
403 MakerNoteLength (),
404 false);
405
406 // Figure out the Exif IFD offset.
407
408 uint32 exifOffset = 8 + mainIFD.Size ();
409
410 exifSet.Locate (exifOffset);
411
412 // Thumbnail IFD (if any).
413
414 dng_tiff_directory thumbIFD;
415
416 tag_uint16 thumbCompression (tcCompression, ccOldJPEG);
417
418 tag_urational thumbXResolution (tcXResolution, dng_urational (72, 1));
419 tag_urational thumbYResolution (tcYResolution, dng_urational (72, 1));
420
421 tag_uint16 thumbResolutionUnit (tcResolutionUnit, ruInch);
422
423 tag_uint32 thumbDataOffset (tcJPEGInterchangeFormat , 0);
424 tag_uint32 thumbDataLength (tcJPEGInterchangeFormatLength, 0);
425
426 if (thumbnail)
427 {
428
429 thumbIFD.Add (&thumbCompression);
430
431 thumbIFD.Add (&thumbXResolution);
432 thumbIFD.Add (&thumbYResolution);
433 thumbIFD.Add (&thumbResolutionUnit);
434
435 thumbIFD.Add (&thumbDataOffset);
436 thumbIFD.Add (&thumbDataLength);
437
438 thumbDataLength.Set (thumbnail->CompressedData ().LogicalSize ());
439
440 uint32 thumbOffset = exifOffset + exifSet.Size ();
441
442 mainIFD.SetChained (thumbOffset);
443
444 thumbDataOffset.Set (thumbOffset + thumbIFD.Size ());
445
446 }
447
448 // Don't write anything unless the main IFD has some tags.
449
450 if (mainIFD.Size () != 0)
451 {
452
453 // Write TIFF Header.
454
455 stream.SetWritePosition (0);
456
457 stream.Put_uint16 (stream.BigEndian () ? byteOrderMM : byteOrderII);
458
459 stream.Put_uint16 (42);
460
461 stream.Put_uint32 (8);
462
463 // Write the IFDs.
464
465 mainIFD.Put (stream);
466
467 exifSet.Put (stream);
468
469 if (thumbnail)
470 {
471
472 thumbIFD.Put (stream);
473
474 stream.Put (thumbnail->CompressedData ().Buffer (),
475 thumbnail->CompressedData ().LogicalSize ());
476
477 }
478
479 // Trim the file to this length.
480
481 stream.Flush ();
482
483 stream.SetLength (stream.Position ());
484
485 }
486
487 }
488
489 return stream.AsMemoryBlock (allocator,
490 numLeadingZeroBytes);
491
492 }
493
494 /******************************************************************************/
495
496 void dng_metadata::SetIPTC (AutoPtr<dng_memory_block> &block, uint64 offset)
497 {
498
499 fIPTCBlock.Reset (block.Release ());
500
501 fIPTCOffset = offset;
502
503 }
504
505 /******************************************************************************/
506
507 void dng_metadata::SetIPTC (AutoPtr<dng_memory_block> &block)
508 {
509
510 SetIPTC (block, kDNGStreamInvalidOffset);
511
512 }
513
514 /******************************************************************************/
515
516 void dng_metadata::ClearIPTC ()
517 {
518
519 fIPTCBlock.Reset ();
520
521 fIPTCOffset = kDNGStreamInvalidOffset;
522
523 }
524
525 /*****************************************************************************/
526
527 const void * dng_metadata::IPTCData () const
528 {
529
530 if (fIPTCBlock.Get ())
531 {
532
533 return fIPTCBlock->Buffer ();
534
535 }
536
537 return NULL;
538
539 }
540
541 /*****************************************************************************/
542
543 uint32 dng_metadata::IPTCLength () const
544 {
545
546 if (fIPTCBlock.Get ())
547 {
548
549 return fIPTCBlock->LogicalSize ();
550
551 }
552
553 return 0;
554
555 }
556
557 /*****************************************************************************/
558
559 uint64 dng_metadata::IPTCOffset () const
560 {
561
562 if (fIPTCBlock.Get ())
563 {
564
565 return fIPTCOffset;
566
567 }
568
569 return kDNGStreamInvalidOffset;
570
571 }
572
573 /*****************************************************************************/
574
575 dng_fingerprint dng_metadata::IPTCDigest (bool includePadding) const
576 {
577
578 if (IPTCLength ())
579 {
580
581 dng_md5_printer printer;
582
583 const uint8 *data = (const uint8 *) IPTCData ();
584
585 uint32 count = IPTCLength ();
586
587 // Because of some stupid ways of storing the IPTC data, the IPTC
588 // data might be padded with up to three zeros. The official Adobe
589 // logic is to include these zeros in the digest. However, older
590 // versions of the Camera Raw code did not include the padding zeros
591 // in the digest, so we support both methods and allow either to
592 // match.
593
594 if (!includePadding)
595 {
596
597 uint32 removed = 0;
598
599 while ((removed < 3) && (count > 0) && (data [count - 1] == 0))
600 {
601 removed++;
602 count--;
603 }
604
605 }
606
607 printer.Process (data, count);
608
609 return printer.Result ();
610
611 }
612
613 return dng_fingerprint ();
614
615 }
616
617 /******************************************************************************/
618
619 #if qDNGUseXMP
620
621 /******************************************************************************/
622
623 void dng_metadata::RebuildIPTC (dng_memory_allocator &allocator,
624 bool padForTIFF)
625 {
626
627 ClearIPTC ();
628
629 fXMP->RebuildIPTC (*this, allocator, padForTIFF);
630
631 dng_fingerprint digest = IPTCDigest ();
632
633 fXMP->SetIPTCDigest (digest);
634
635 }
636
637 /*****************************************************************************/
638
639 void dng_metadata::ResetXMP (dng_xmp * newXMP)
640 {
641
642 fXMP.Reset (newXMP);
643
644 }
645
646 /*****************************************************************************/
647
648 void dng_metadata::ResetXMPSidecarNewer (dng_xmp * newXMP,
649 bool inSidecar,
650 bool isNewer )
651 {
652
653 fXMP.Reset (newXMP);
654
655 fXMPinSidecar = inSidecar;
656
657 fXMPisNewer = isNewer;
658
659 }
660
661 /*****************************************************************************/
662
663 bool dng_metadata::SetXMP (dng_host &host,
664 const void *buffer,
665 uint32 count,
666 bool xmpInSidecar,
667 bool xmpIsNewer)
668 {
669
670 bool result = false;
671
672 try
673 {
674
675 AutoPtr<dng_xmp> tempXMP (host.Make_dng_xmp ());
676
677 dng_big_table_dictionary dictionary = BigTableDictionary ();
678
679 DualParseXMP (host,
680 *tempXMP,
681 dictionary,
682 buffer,
683 count);
684
685 ResetXMPSidecarNewer (tempXMP.Release (), xmpInSidecar, xmpIsNewer);
686
687 SetBigTableDictionary (dictionary);
688
689 result = true;
690
691 }
692
693 catch (dng_exception &except)
694 {
695
696 // Don't ignore transient errors.
697
698 if (host.IsTransientError (except.ErrorCode ()))
699 {
700
701 throw;
702
703 }
704
705 // Eat other parsing errors.
706
707 }
708
709 catch (...)
710 {
711
712 // Eat unknown parsing exceptions.
713
714 }
715
716 return result;
717
718 }
719
720 /*****************************************************************************/
721
722 void dng_metadata::SetEmbeddedXMP (dng_host &host,
723 const void *buffer,
724 uint32 count)
725 {
726
727 if (SetXMP (host, buffer, count))
728 {
729
730 dng_md5_printer printer;
731
732 printer.Process (buffer, count);
733
734 fEmbeddedXMPDigest = printer.Result ();
735
736 // Remove any sidecar specific tags from embedded XMP.
737
738 if (fXMP.Get ())
739 {
740
741 fXMP->Remove (XMP_NS_PHOTOSHOP, "SidecarForExtension");
742 fXMP->Remove (XMP_NS_PHOTOSHOP, "EmbeddedXMPDigest");
743
744 }
745
746 }
747
748 else
749 {
750
751 fEmbeddedXMPDigest.Clear ();
752
753 }
754
755 }
756
757 /*****************************************************************************/
758
759 #endif // qDNGUseXMP
760
761 /*****************************************************************************/
762
763 void dng_metadata::SynchronizeMetadata ()
764 {
765
766 DNG_REQUIRE (fExif.Get (),
767 "Expected valid fExif field in "
768 "dng_metadata::SynchronizeMetadata");
769
770 if (!fOriginalExif.Get ())
771 {
772
773 fOriginalExif.Reset (fExif->Clone ());
774
775 }
776
777 #if qDNGUseXMP
778
779 fXMP->ValidateMetadata ();
780
781 fXMP->IngestIPTC (*this, fXMPisNewer);
782
783 fXMP->SyncExif (*fExif.Get ());
784
785 fXMP->SyncOrientation (*this, fXMPinSidecar);
786
787 #endif
788
789 }
790
791 /*****************************************************************************/
792
793 void dng_metadata::UpdateDateTime (const dng_date_time_info &dt)
794 {
795
796 fExif->UpdateDateTime (dt);
797
798 #if qDNGUseXMP
799 fXMP->UpdateDateTime (dt);
800 #endif
801
802 }
803
804 /*****************************************************************************/
805
806 void dng_metadata::UpdateDateTimeToNow ()
807 {
808
809 dng_date_time_info dt;
810
811 CurrentDateTimeAndZone (dt);
812
813 UpdateDateTime (dt);
814
815 #if qDNGUseXMP
816 fXMP->UpdateMetadataDate (dt);
817 #endif
818
819 }
820
821 /*****************************************************************************/
822
823 void dng_metadata::UpdateMetadataDateTimeToNow ()
824 {
825
826 dng_date_time_info dt;
827
828 CurrentDateTimeAndZone (dt);
829
830 #if qDNGUseXMP
831 fXMP->UpdateMetadataDate (dt);
832 #endif
833
834 }
835
836 /*****************************************************************************/
837
838 dng_negative::dng_negative (dng_host &host)
839
840 : fAllocator (host.Allocator ())
841
842 , fModelName ()
843 , fLocalName ()
844 , fDefaultCropSizeH ()
845 , fDefaultCropSizeV ()
846 , fDefaultCropOriginH (0, 1)
847 , fDefaultCropOriginV (0, 1)
848 , fRawDefaultCropSizeH ()
849 , fRawDefaultCropSizeV ()
850 , fRawDefaultCropOriginH ()
851 , fRawDefaultCropOriginV ()
852 , fDefaultUserCropT (0, 1)
853 , fDefaultUserCropL (0, 1)
854 , fDefaultUserCropB (1, 1)
855 , fDefaultUserCropR (1, 1)
856 , fDefaultScaleH (1, 1)
857 , fDefaultScaleV (1, 1)
858 , fRawDefaultScaleH ()
859 , fRawDefaultScaleV ()
860 , fBestQualityScale (1, 1)
861 , fRawBestQualityScale ()
862 , fOriginalDefaultFinalSize ()
863 , fOriginalBestQualityFinalSize ()
864 , fOriginalDefaultCropSizeH ()
865 , fOriginalDefaultCropSizeV ()
866 , fRawToFullScaleH (1.0)
867 , fRawToFullScaleV (1.0)
868 , fBaselineNoise (100, 100)
869 , fNoiseReductionApplied (0, 0)
870 , fRawNoiseReductionApplied (0, 0)
871 , fNoiseProfile ()
872 , fRawNoiseProfile ()
873 , fBaselineExposure ( 0, 100)
874 , fBaselineSharpness (100, 100)
875 , fRawBaselineSharpness (0, 0)
876 , fChromaBlurRadius ()
877 , fAntiAliasStrength (100, 100)
878 , fLinearResponseLimit (100, 100)
879 , fShadowScale (1, 1)
880 , fColorimetricReference (crSceneReferred)
881 , fFloatingPoint (false)
882 , fColorChannels (0)
883 , fAnalogBalance ()
884 , fCameraNeutral ()
885 , fCameraWhiteXY ()
886 , fCameraCalibration1 ()
887 , fCameraCalibration2 ()
888 , fCameraCalibration3 ()
889 , fCameraCalibrationSignature ()
890 , fCameraProfile ()
891 , fAsShotProfileName ()
892 , fRawImageDigest ()
893 , fNewRawImageDigest ()
894 , fRawDataUniqueID ()
895 , fOriginalRawFileName ()
896 , fHasOriginalRawFileData (false)
897 , fOriginalRawFileData ()
898 , fOriginalRawFileDigest ()
899 , fDNGPrivateData ()
900 , fMetadata (host)
901 , fLinearizationInfo ()
902 , fMosaicInfo ()
903 , fOpcodeList1 (1)
904 , fOpcodeList2 (2)
905 , fOpcodeList3 (3)
906 , fStage1Image ()
907 , fStage2Image ()
908 , fStage3Image ()
909 , fStage3Gain (1.0)
910 , fStage3BlackLevel (0)
911 , fIsPreview (false)
912 , fIsDamaged (false)
913 , fRawImageStage (rawImageStageNone)
914 , fRawImage ()
915 , fRawImageBlackLevel (0)
916 , fRawFloatBitDepth (0)
917 , fTransparencyMask ()
918 , fRawTransparencyMask ()
919 , fRawTransparencyMaskBitDepth (0)
920 , fUnflattenedStage3Image ()
921 , fHasDepthMap (false)
922 , fDepthMap ()
923 , fRawDepthMap ()
924 , fDepthFormat (depthFormatUnknown)
925 , fDepthNear (0, 0)
926 , fDepthFar (0, 0)
927 , fDepthUnits (depthUnitsUnknown)
928 , fDepthMeasureType (depthMeasureUnknown)
929 , fEnhanceParams ()
930
931 {
932
933 }
934
935 /*****************************************************************************/
936
937 dng_negative::~dng_negative ()
938 {
939
940 // Delete any camera profiles owned by this negative.
941
942 ClearProfiles ();
943
944 }
945
946 /******************************************************************************/
947
948 void dng_negative::Initialize ()
949 {
950
951 }
952
953 /******************************************************************************/
954
955 dng_negative * dng_negative::Make (dng_host &host)
956 {
957
958 AutoPtr<dng_negative> result (new dng_negative (host));
959
960 if (!result.Get ())
961 {
962 ThrowMemoryFull ();
963 }
964
965 result->Initialize ();
966
967 return result.Release ();
968
969 }
970
971 /******************************************************************************/
972
973 dng_metadata * dng_negative::CloneInternalMetadata () const
974 {
975
976 return InternalMetadata ().Clone (Allocator ());
977
978 }
979
980 /******************************************************************************/
981
982 dng_orientation dng_negative::ComputeOrientation (const dng_metadata &metadata) const
983 {
984
985 return metadata.BaseOrientation ();
986
987 }
988
989 /******************************************************************************/
990
991 void dng_negative::SetAnalogBalance (const dng_vector &b)
992 {
993
994 real64 minEntry = b.MinEntry ();
995
996 if (b.NotEmpty () && minEntry > 0.0)
997 {
998
999 fAnalogBalance = b;
1000
1001 fAnalogBalance.Scale (1.0 / minEntry);
1002
1003 fAnalogBalance.Round (1000000.0);
1004
1005 }
1006
1007 else
1008 {
1009
1010 fAnalogBalance.Clear ();
1011
1012 }
1013
1014 }
1015
1016 /*****************************************************************************/
1017
1018 real64 dng_negative::AnalogBalance (uint32 channel) const
1019 {
1020
1021 DNG_ASSERT (channel < ColorChannels (), "Channel out of bounds");
1022
1023 if (channel < fAnalogBalance.Count ())
1024 {
1025
1026 return fAnalogBalance [channel];
1027
1028 }
1029
1030 return 1.0;
1031
1032 }
1033
1034 /*****************************************************************************/
1035
1036 dng_urational dng_negative::AnalogBalanceR (uint32 channel) const
1037 {
1038
1039 dng_urational result;
1040
1041 result.Set_real64 (AnalogBalance (channel), 1000000);
1042
1043 return result;
1044
1045 }
1046
1047 /******************************************************************************/
1048
1049 void dng_negative::SetCameraNeutral (const dng_vector &n)
1050 {
1051
1052 real64 maxEntry = n.MaxEntry ();
1053
1054 if (n.NotEmpty () && maxEntry > 0.0)
1055 {
1056
1057 fCameraNeutral = n;
1058
1059 fCameraNeutral.Scale (1.0 / maxEntry);
1060
1061 fCameraNeutral.Round (1000000.0);
1062
1063 }
1064
1065 else
1066 {
1067
1068 fCameraNeutral.Clear ();
1069
1070 }
1071
1072 }
1073
1074 /*****************************************************************************/
1075
1076 dng_urational dng_negative::CameraNeutralR (uint32 channel) const
1077 {
1078
1079 dng_urational result;
1080
1081 result.Set_real64 (CameraNeutral () [channel], 1000000);
1082
1083 return result;
1084
1085 }
1086
1087 /******************************************************************************/
1088
1089 void dng_negative::SetCameraWhiteXY (const dng_xy_coord &coord)
1090 {
1091
1092 if (coord.IsValid ())
1093 {
1094
1095 fCameraWhiteXY.x = Round_int32 (coord.x * 1000000.0) / 1000000.0;
1096 fCameraWhiteXY.y = Round_int32 (coord.y * 1000000.0) / 1000000.0;
1097
1098 }
1099
1100 else
1101 {
1102
1103 fCameraWhiteXY.Clear ();
1104
1105 }
1106
1107 }
1108
1109 /*****************************************************************************/
1110
1111 const dng_xy_coord & dng_negative::CameraWhiteXY () const
1112 {
1113
1114 DNG_ASSERT (HasCameraWhiteXY (), "Using undefined CameraWhiteXY");
1115
1116 return fCameraWhiteXY;
1117
1118 }
1119
1120 /*****************************************************************************/
1121
1122 void dng_negative::GetCameraWhiteXY (dng_urational &x,
1123 dng_urational &y) const
1124 {
1125
1126 dng_xy_coord coord = CameraWhiteXY ();
1127
1128 x.Set_real64 (coord.x, 1000000);
1129 y.Set_real64 (coord.y, 1000000);
1130
1131 }
1132
1133 /*****************************************************************************/
1134
1135 void dng_negative::SetCameraCalibration1 (const dng_matrix &m)
1136 {
1137
1138 fCameraCalibration1 = m;
1139
1140 fCameraCalibration1.Round (10000);
1141
1142 }
1143
1144 /******************************************************************************/
1145
1146 void dng_negative::SetCameraCalibration2 (const dng_matrix &m)
1147 {
1148
1149 fCameraCalibration2 = m;
1150
1151 fCameraCalibration2.Round (10000);
1152
1153 }
1154
1155 /******************************************************************************/
1156
1157 void dng_negative::SetCameraCalibration3 (const dng_matrix &m)
1158 {
1159
1160 fCameraCalibration3 = m;
1161
1162 fCameraCalibration3.Round (10000);
1163
1164 }
1165
1166 /******************************************************************************/
1167
1168 void dng_negative::AddProfile (AutoPtr<dng_camera_profile> &profile)
1169 {
1170
1171 // Make sure we have a profile to add.
1172
1173 if (!profile.Get ())
1174 {
1175
1176 return;
1177
1178 }
1179
1180 // We must have some profile name. Use "embedded" if nothing else.
1181
1182 if (profile->Name ().IsEmpty ())
1183 {
1184
1185 profile->SetName (kProfileName_Embedded);
1186
1187 }
1188
1189 // Special case support for reading older DNG files which did not store
1190 // the profile name in the main IFD profile.
1191
1192 if (fCameraProfile.size ())
1193 {
1194
1195 // See the first profile has a default "embedded" name, and has
1196 // the same data as the profile we are adding.
1197
1198 if (fCameraProfile [0]->NameIsEmbedded () &&
1199 fCameraProfile [0]->EqualData (*profile.Get ()))
1200 {
1201
1202 // If the profile we are deleting was read from DNG
1203 // then the new profile should be marked as such also.
1204
1205 if (fCameraProfile [0]->WasReadFromDNG ())
1206 {
1207
1208 profile->SetWasReadFromDNG ();
1209
1210 }
1211
1212 // If the profile we are deleting wasn't read from disk then the new
1213 // profile should be marked as such also.
1214
1215 if (!fCameraProfile [0]->WasReadFromDisk ())
1216 {
1217
1218 profile->SetWasReadFromDisk (false);
1219
1220 }
1221
1222 // Delete the profile with default name.
1223
1224 delete fCameraProfile [0];
1225
1226 fCameraProfile [0] = NULL;
1227
1228 fCameraProfile.erase (fCameraProfile.begin ());
1229
1230 }
1231
1232 }
1233
1234 // Duplicate detection logic. We give a preference to last added profile
1235 // so the profiles end up in a more consistent order no matter what profiles
1236 // happen to be embedded in the DNG.
1237
1238 for (uint32 index = 0; index < (uint32) fCameraProfile.size (); index++)
1239 {
1240
1241 // Instead of checking for matching fingerprints, we check that the two
1242 // profiles have the same color and have the same name. This allows two
1243 // profiles that are identical except for copyright string and embed policy
1244 // to be considered duplicates.
1245
1246 const bool equalColorAndSameName = (fCameraProfile [index]->EqualData (*profile.Get ()) &&
1247 fCameraProfile [index]->Name () == profile->Name ());
1248
1249 if (equalColorAndSameName)
1250 {
1251
1252 // If the profile we are deleting was read from DNG
1253 // then the new profile should be marked as such also.
1254
1255 if (fCameraProfile [index]->WasReadFromDNG ())
1256 {
1257
1258 profile->SetWasReadFromDNG ();
1259
1260 }
1261
1262 // If the profile we are deleting wasn't read from disk then the new
1263 // profile should be marked as such also.
1264
1265 if (!fCameraProfile [index]->WasReadFromDisk ())
1266 {
1267
1268 profile->SetWasReadFromDisk (false);
1269
1270 }
1271
1272 // Delete the duplicate profile.
1273
1274 delete fCameraProfile [index];
1275
1276 fCameraProfile [index] = NULL;
1277
1278 fCameraProfile.erase (fCameraProfile.begin () + index);
1279
1280 break;
1281
1282 }
1283
1284 }
1285
1286 // Now add to profile list.
1287
1288 fCameraProfile.push_back (NULL);
1289
1290 fCameraProfile [fCameraProfile.size () - 1] = profile.Release ();
1291
1292 }
1293
1294 /******************************************************************************/
1295
1296 void dng_negative::ClearProfiles ()
1297 {
1298
1299 // Delete any camera profiles owned by this negative.
1300
1301 for (uint32 index = 0; index < (uint32) fCameraProfile.size (); index++)
1302 {
1303
1304 if (fCameraProfile [index])
1305 {
1306
1307 delete fCameraProfile [index];
1308
1309 fCameraProfile [index] = NULL;
1310
1311 }
1312
1313 }
1314
1315 // Now empty list.
1316
1317 fCameraProfile.clear ();
1318
1319 }
1320
1321 /******************************************************************************/
1322
1323 uint32 dng_negative::ProfileCount () const
1324 {
1325
1326 return (uint32) fCameraProfile.size ();
1327
1328 }
1329
1330 /******************************************************************************/
1331
1332 const dng_camera_profile & dng_negative::ProfileByIndex (uint32 index) const
1333 {
1334
1335 DNG_ASSERT (index < ProfileCount (),
1336 "Invalid index for ProfileByIndex");
1337
1338 return *fCameraProfile [index];
1339
1340 }
1341
1342 /*****************************************************************************/
1343
1344 void dng_negative::GetProfileMetadataList (dng_profile_metadata_list &list) const
1345 {
1346
1347 list.clear ();
1348
1349 list.reserve (ProfileCount ());
1350
1351 for (uint32 index = 0; index < ProfileCount (); index++)
1352 {
1353
1354 list.push_back (dng_camera_profile_metadata (ProfileByIndex (index),
1355 index));
1356
1357 }
1358
1359 }
1360
1361 /*****************************************************************************/
1362
1363 bool dng_negative::GetProfileByMetadata
1364 (const dng_camera_profile_metadata &metadata,
1365 dng_camera_profile &foundProfile) const
1366 {
1367
1368 if (metadata.fIndex >= 0)
1369 {
1370
1371 foundProfile = ProfileByIndex (metadata.fIndex);
1372
1373 return true;
1374
1375 }
1376
1377 return false;
1378
1379 }
1380
1381 /*****************************************************************************/
1382
1383 bool dng_negative::GetProfileByIDFromList (const dng_profile_metadata_list &list,
1384 const dng_camera_profile_id &id,
1385 dng_camera_profile &foundProfile,
1386 bool useDefaultIfNoMatch,
1387 const dng_camera_profile_group_selector *groupSelector) const
1388 {
1389
1390 // How many profiles in list?
1391
1392 uint32 profileCount = (uint32) list.size ();
1393
1394 if (profileCount == 0)
1395 {
1396 return false;
1397 }
1398
1399 // If this is a profile group ID, match group names and pick from that list.
1400
1401 if (HasProfileGroupPrefix (id.Name ()))
1402 {
1403
1404 dng_string groupName = StripProfileGroupPrefix (id.Name ());
1405
1406 dng_camera_profile_group_selector selector;
1407
1408 if (groupSelector)
1409 {
1410 selector = *groupSelector;
1411 }
1412
1413 for (uint32 pass = 1; pass <= 2; pass++)
1414 {
1415
1416 for (uint32 index = 0; index < profileCount; index++)
1417 {
1418
1419 if (list [index] . fGroupName == groupName)
1420 {
1421
1422 if (pass == 1 && (selector.fHDR != list [index] . fHDR))
1423 {
1424 continue;
1425 }
1426
1427 if (GetProfileByMetadata (list [index],
1428 foundProfile))
1429 {
1430 return true;
1431 }
1432
1433 }
1434
1435 }
1436
1437 }
1438
1439 }
1440
1441 // If we have both a profile name and fingerprint, try matching both.
1442
1443 if (id.Name ().NotEmpty () && id.Fingerprint ().IsValid ())
1444 {
1445
1446 for (uint32 index = 0; index < profileCount; index++)
1447 {
1448
1449 const dng_camera_profile_id &profileID (list [index] . fProfileID);
1450
1451 if (id == profileID)
1452 {
1453
1454 if (GetProfileByMetadata (list [index],
1455 foundProfile))
1456 {
1457 return true;
1458 }
1459
1460 }
1461
1462 }
1463
1464 }
1465
1466 // If we have a name, try matching that.
1467
1468 if (id.Name ().NotEmpty ())
1469 {
1470
1471 // Try case sensitive match first, then ignore case.
1472
1473 for (uint32 pass = 1; pass <= 2; pass++)
1474 {
1475
1476 bool case_sensitive = (pass == 1);
1477
1478 for (uint32 index = 0; index < profileCount; index++)
1479 {
1480
1481 const dng_camera_profile_id &profileID (list [index] . fProfileID);
1482
1483 if (id.Name ().Matches (profileID.Name ().Get (), case_sensitive))
1484 {
1485
1486 if (GetProfileByMetadata (list [index],
1487 foundProfile))
1488 {
1489 return true;
1490 }
1491
1492 }
1493
1494 }
1495
1496 }
1497
1498 }
1499
1500 // If we have a valid fingerprint, try matching that. Since the fingerprint
1501 // includes the profile name, we only do this if the name is null.
1502
1503 else if (id.Fingerprint ().IsValid ())
1504 {
1505
1506 for (uint32 index = 0; index < profileCount; index++)
1507 {
1508
1509 const dng_camera_profile_id &profileID (list [index] . fProfileID);
1510
1511 if (id.Fingerprint () == profileID.Fingerprint ())
1512 {
1513
1514 if (GetProfileByMetadata (list [index],
1515 foundProfile))
1516 {
1517 return true;
1518 }
1519
1520 }
1521
1522 }
1523
1524 }
1525
1526 // Try "upgrading" (or downgrading if required) profile name versions.
1527
1528 if (id.Name ().NotEmpty ())
1529 {
1530
1531 dng_string baseName;
1532 int32 version;
1533
1534 SplitCameraProfileName (id.Name (),
1535 baseName,
1536 version);
1537
1538 int32 bestIndex = -1;
1539 int32 bestVersion = 0;
1540
1541 for (uint32 index = 0; index < profileCount; index++)
1542 {
1543
1544 const dng_camera_profile_id &profileID (list [index] . fProfileID);
1545
1546 if (profileID.Name ().StartsWith (baseName.Get ()))
1547 {
1548
1549 dng_string testBaseName;
1550 int32 testVersion;
1551
1552 SplitCameraProfileName (profileID.Name (),
1553 testBaseName,
1554 testVersion);
1555
1556 if (testBaseName.Matches (baseName.Get ()))
1557 {
1558
1559 if (bestIndex == -1 || testVersion > bestVersion)
1560 {
1561
1562 bestIndex = index;
1563 bestVersion = testVersion;
1564
1565 }
1566
1567 }
1568
1569 }
1570
1571 }
1572
1573 if (bestIndex != -1)
1574 {
1575
1576 if (GetProfileByMetadata (list [bestIndex],
1577 foundProfile))
1578 {
1579 return true;
1580 }
1581
1582 }
1583
1584 }
1585
1586 // Did not find a match any way. See if we should return a default value.
1587
1588 if (useDefaultIfNoMatch)
1589 {
1590
1591 if (GetProfileByMetadata (list [0],
1592 foundProfile))
1593 {
1594 return true;
1595 }
1596
1597 }
1598
1599 // Found nothing.
1600
1601 return false;
1602
1603 }
1604
1605 /*****************************************************************************/
1606
1607 bool dng_negative::GetProfileToEmbedFromList (const dng_profile_metadata_list &list,
1608 const dng_metadata & /* metadata */,
1609 dng_camera_profile &foundProfile) const
1610 {
1611
1612 // How many profiles in list?
1613
1614 uint32 profileCount = (uint32) list.size ();
1615
1616 if (profileCount == 0)
1617 {
1618 return false;
1619 }
1620
1621 // First try to look for the first profile that was already in the DNG
1622 // when we read it.
1623
1624 {
1625
1626 for (uint32 index = 0; index < profileCount; index++)
1627 {
1628
1629 if (list [index] . fWasReadFromDNG)
1630 {
1631
1632 if (GetProfileByMetadata (list [index],
1633 foundProfile))
1634 {
1635 return true;
1636 }
1637
1638 }
1639
1640 }
1641
1642 }
1643
1644 // Next we look for the first profile that is legal to embed.
1645
1646 {
1647
1648 for (uint32 index = 0; index < profileCount; index++)
1649 {
1650
1651 if (list [index] . fIsLegalToEmbed)
1652 {
1653
1654 if (GetProfileByMetadata (list [index],
1655 foundProfile))
1656 {
1657 return true;
1658 }
1659
1660 }
1661
1662 }
1663
1664 }
1665
1666 // Else just return the first profile.
1667
1668 return GetProfileByMetadata (list [0],
1669 foundProfile);
1670
1671 }
1672
1673 /*****************************************************************************/
1674
1675 bool dng_negative::GetProfileByID (const dng_camera_profile_id &id,
1676 dng_camera_profile &foundProfile,
1677 bool useDefaultIfNoMatch,
1678 const dng_camera_profile_group_selector *groupSelector) const
1679 {
1680
1681 // Monochrome negatives don't have profiles.
1682
1683 if (IsMonochrome ())
1684 {
1685 return false;
1686 }
1687
1688 // Get list of profile metadata.
1689
1690 dng_profile_metadata_list list;
1691
1692 GetProfileMetadataList (list);
1693
1694 // Search the list.
1695
1696 return GetProfileByIDFromList (list,
1697 id,
1698 foundProfile,
1699 useDefaultIfNoMatch,
1700 groupSelector);
1701
1702 }
1703
1704 /*****************************************************************************/
1705
1706 bool dng_negative::GetProfileToEmbed (const dng_metadata &metadata,
1707 dng_camera_profile &foundProfile) const
1708 {
1709
1710 // Monochrome negatives don't have profiles.
1711
1712 if (IsMonochrome ())
1713 {
1714 return false;
1715 }
1716
1717 // Get list of profile metadata.
1718
1719 dng_profile_metadata_list list;
1720
1721 GetProfileMetadataList (list);
1722
1723 // Search the list.
1724
1725 return GetProfileToEmbedFromList (list,
1726 metadata,
1727 foundProfile);
1728
1729 }
1730
1731 /*****************************************************************************/
1732
1733 dng_color_spec * dng_negative::MakeColorSpec (const dng_camera_profile_id &id,
1734 bool allowStubbed) const
1735 {
1736
1737 dng_camera_profile profile;
1738
1739 bool haveProfile = GetProfileByID (id, profile);
1740
1741 dng_color_spec *spec = new dng_color_spec (*this,
1742 haveProfile ? &profile : NULL,
1743 allowStubbed);
1744
1745 if (!spec)
1746 {
1747 ThrowMemoryFull ();
1748 }
1749
1750 return spec;
1751
1752 }
1753
1754 /*****************************************************************************/
1755
1756 dng_fingerprint dng_negative::FindImageDigest (dng_host &host,
1757 const dng_image &image)
1758 {
1759
1760 dng_md5_printer printer;
1761
1762 dng_pixel_buffer buffer (image.Bounds (),
1763 0,
1764 image.Planes (),
1765 image.PixelType (),
1766 pcInterleaved,
1767 NULL);
1768
1769 // Sometimes we expand 8-bit data to 16-bit data while reading or
1770 // writing, so always compute the digest of 8-bit data as 16-bits.
1771
1772 if (buffer.fPixelType == ttByte)
1773 {
1774 buffer.fPixelType = ttShort;
1775 buffer.fPixelSize = 2;
1776 }
1777
1778 const uint32 kBufferRows = 16;
1779
1780 uint32 bufferBytes = 0;
1781
1782 if (!SafeUint32Mult (kBufferRows, buffer.fRowStep, &bufferBytes) ||
1783 !SafeUint32Mult (bufferBytes, buffer.fPixelSize, &bufferBytes))
1784 {
1785
1786 ThrowOverflow ("Arithmetic overflow computing buffer size.");
1787
1788 }
1789
1790 AutoPtr<dng_memory_block> bufferData (host.Allocate (bufferBytes));
1791
1792 buffer.fData = bufferData->Buffer ();
1793
1794 dng_rect area;
1795
1796 dng_tile_iterator iter (dng_point (kBufferRows,
1797 image.Width ()),
1798 image.Bounds ());
1799
1800 while (iter.GetOneTile (area))
1801 {
1802
1803 host.SniffForAbort ();
1804
1805 buffer.fArea = area;
1806
1807 image.Get (buffer);
1808
1809 uint32 count = buffer.fArea.H () *
1810 buffer.fRowStep *
1811 buffer.fPixelSize;
1812
1813 #if qDNGBigEndian
1814
1815 // We need to use the same byte order to compute
1816 // the digest, no matter the native order. Little-endian
1817 // is more common now, so use that.
1818
1819 switch (buffer.fPixelSize)
1820 {
1821
1822 case 1:
1823 break;
1824
1825 case 2:
1826 {
1827 DoSwapBytes16 ((uint16 *) buffer.fData, count >> 1);
1828 break;
1829 }
1830
1831 case 4:
1832 {
1833 DoSwapBytes32 ((uint32 *) buffer.fData, count >> 2);
1834 break;
1835 }
1836
1837 default:
1838 {
1839 DNG_REPORT ("Unexpected pixel size");
1840 break;
1841 }
1842
1843 }
1844
1845 #endif
1846
1847 printer.Process (buffer.fData,
1848 count);
1849
1850 }
1851
1852 return printer.Result ();
1853
1854 }
1855
1856 /*****************************************************************************/
1857
1858 void dng_negative::FindRawImageDigest (dng_host &host) const
1859 {
1860
1861 if (fRawImageDigest.IsNull ())
1862 {
1863
1864 // Since we are adding the floating point and transparency support
1865 // in DNG 1.4, and there are no legacy floating point or transparent
1866 // DNGs, switch to using the more MP friendly algorithm to compute
1867 // the digest for these images.
1868
1869 if (RawImage ().PixelType () == ttFloat || RawTransparencyMask ())
1870 {
1871
1872 FindNewRawImageDigest (host);
1873
1874 fRawImageDigest = fNewRawImageDigest;
1875
1876 }
1877
1878 else
1879 {
1880
1881 #if qDNGValidate
1882
1883 dng_timer timeScope ("FindRawImageDigest time");
1884
1885 #endif
1886
1887 fRawImageDigest = FindImageDigest (host, RawImage ());
1888
1889 }
1890
1891 }
1892
1893 }
1894
1895 /*****************************************************************************/
1896
1897 class dng_find_new_raw_image_digest_task : public dng_area_task
1898 {
1899
1900 private:
1901
1902 enum
1903 {
1904 kTileSize = 256
1905 };
1906
1907 const dng_image &fImage;
1908
1909 uint32 fPixelType;
1910 uint32 fPixelSize;
1911
1912 uint32 fTilesAcross;
1913 uint32 fTilesDown;
1914
1915 uint32 fTileCount;
1916
1917 AutoArray<dng_fingerprint> fTileHash;
1918
1919 AutoPtr<dng_memory_block> fBufferData [kMaxMPThreads];
1920
1921 public:
1922
1923 dng_find_new_raw_image_digest_task (const dng_image &image,
1924 uint32 pixelType)
1925
1926 : dng_area_task ("dng_find_new_raw_image_digest_task")
1927
1928 , fImage (image)
1929 , fPixelType (pixelType)
1930 , fPixelSize (TagTypeSize (pixelType))
1931 , fTilesAcross (0)
1932 , fTilesDown (0)
1933 , fTileCount (0)
1934 , fTileHash ()
1935
1936 {
1937
1938 fMinTaskArea = 1;
1939
1940 fUnitCell = dng_point (Min_int32 (kTileSize, fImage.Bounds ().H ()),
1941 Min_int32 (kTileSize, fImage.Bounds ().W ()));
1942
1943 fMaxTileSize = fUnitCell;
1944
1945 }
1946
1947 virtual void Start (uint32 threadCount,
1948 const dng_rect & /* dstArea */,
1949 const dng_point &tileSize,
1950 dng_memory_allocator *allocator,
1951 dng_abort_sniffer * /* sniffer */)
1952 {
1953
1954 if (tileSize != fUnitCell)
1955 {
1956 ThrowProgramError ();
1957 }
1958
1959 fTilesAcross = (fImage.Bounds ().W () + fUnitCell.h - 1) / fUnitCell.h;
1960 fTilesDown = (fImage.Bounds ().H () + fUnitCell.v - 1) / fUnitCell.v;
1961
1962 fTileCount = fTilesAcross * fTilesDown;
1963
1964 fTileHash.Reset (fTileCount);
1965
1966 const uint32 bufferSize =
1967 ComputeBufferSize (fPixelType,
1968 tileSize,
1969 fImage.Planes (),
1970 padNone);
1971
1972 for (uint32 index = 0; index < threadCount; index++)
1973 {
1974
1975 fBufferData [index].Reset (allocator->Allocate (bufferSize));
1976
1977 }
1978
1979 }
1980
1981 virtual void Process (uint32 threadIndex,
1982 const dng_rect &tile,
1983 dng_abort_sniffer * /* sniffer */)
1984 {
1985
1986 int32 colIndex = (tile.l - fImage.Bounds ().l) / fUnitCell.h;
1987 int32 rowIndex = (tile.t - fImage.Bounds ().t) / fUnitCell.v;
1988
1989 DNG_ASSERT (tile.l == fImage.Bounds ().l + colIndex * fUnitCell.h &&
1990 tile.t == fImage.Bounds ().t + rowIndex * fUnitCell.v,
1991 "Bad tile origin");
1992
1993 uint32 tileIndex = rowIndex * fTilesAcross + colIndex;
1994
1995 dng_pixel_buffer buffer (tile,
1996 0,
1997 fImage.Planes (),
1998 fPixelType,
1999 pcPlanar,
2000 fBufferData [threadIndex]->Buffer ());
2001
2002 fImage.Get (buffer);
2003
2004 uint32 count = buffer.fPlaneStep *
2005 buffer.fPlanes *
2006 buffer.fPixelSize;
2007
2008 #if qDNGBigEndian
2009
2010 // We need to use the same byte order to compute
2011 // the digest, no matter the native order. Little-endian
2012 // is more common now, so use that.
2013
2014 switch (buffer.fPixelSize)
2015 {
2016
2017 case 1:
2018 break;
2019
2020 case 2:
2021 {
2022 DoSwapBytes16 ((uint16 *) buffer.fData, count >> 1);
2023 break;
2024 }
2025
2026 case 4:
2027 {
2028 DoSwapBytes32 ((uint32 *) buffer.fData, count >> 2);
2029 break;
2030 }
2031
2032 default:
2033 {
2034 DNG_REPORT ("Unexpected pixel size");
2035 break;
2036 }
2037
2038 }
2039
2040 #endif
2041
2042 dng_md5_printer printer;
2043
2044 printer.Process (buffer.fData, count);
2045
2046 fTileHash [tileIndex] = printer.Result ();
2047
2048 }
2049
2050 dng_fingerprint Result ()
2051 {
2052
2053 dng_md5_printer printer;
2054
2055 for (uint32 tileIndex = 0; tileIndex < fTileCount; tileIndex++)
2056 {
2057
2058 printer.Process (fTileHash [tileIndex] . data, 16);
2059
2060 }
2061
2062 return printer.Result ();
2063
2064 }
2065
2066 };
2067
2068 /*****************************************************************************/
2069
2070 dng_fingerprint dng_negative::FindFastImageDigest (dng_host &host,
2071 const dng_image &image,
2072 uint32 pixelType)
2073 {
2074
2075 dng_find_new_raw_image_digest_task task (image, pixelType);
2076
2077 host.PerformAreaTask (task, image.Bounds ());
2078
2079 return task.Result ();
2080
2081 }
2082
2083 /*****************************************************************************/
2084
2085 void dng_negative::FindNewRawImageDigest (dng_host &host) const
2086 {
2087
2088 if (fNewRawImageDigest.IsNull ())
2089 {
2090
2091 #if qDNGValidate
2092
2093 dng_timer timeScope ("FindNewRawImageDigest time");
2094
2095 #endif
2096
2097 // Find fast digest of the raw image.
2098
2099 {
2100
2101 const dng_image &rawImage = RawImage ();
2102
2103 // Find pixel type that will be saved in the file. When saving DNGs, we convert
2104 // some 16-bit data to 8-bit data, so we need to do the matching logic here.
2105
2106 uint32 rawPixelType = rawImage.PixelType ();
2107
2108 if (rawPixelType == ttShort)
2109 {
2110
2111 // See if we are using a linearization table with <= 256 entries, in which
2112 // case the useful data will all fit within 8-bits.
2113
2114 const dng_linearization_info *rangeInfo = GetLinearizationInfo ();
2115
2116 if (rangeInfo)
2117 {
2118
2119 if (rangeInfo->fLinearizationTable.Get ())
2120 {
2121
2122 uint32 entries = rangeInfo->fLinearizationTable->LogicalSize () >> 1;
2123
2124 if (entries <= 256)
2125 {
2126
2127 rawPixelType = ttByte;
2128
2129 }
2130
2131 }
2132
2133 }
2134
2135 }
2136
2137 // Find the fast digest on the raw image.
2138
2139 fNewRawImageDigest = FindFastImageDigest (host, rawImage, rawPixelType);
2140
2141 }
2142
2143 // If there is a transparency mask, we need to include that in the
2144 // digest also.
2145
2146 if (RawTransparencyMask () != NULL)
2147 {
2148
2149 // Find the fast digest on the raw mask.
2150
2151 dng_fingerprint maskDigest;
2152
2153 {
2154
2155 dng_find_new_raw_image_digest_task task (*RawTransparencyMask (),
2156 RawTransparencyMask ()->PixelType ());
2157
2158 host.PerformAreaTask (task, RawTransparencyMask ()->Bounds ());
2159
2160 maskDigest = task.Result ();
2161
2162 }
2163
2164 // Combine the two digests into a single digest.
2165
2166 dng_md5_printer printer;
2167
2168 printer.Process (fNewRawImageDigest.data, 16);
2169
2170 printer.Process (maskDigest.data, 16);
2171
2172 fNewRawImageDigest = printer.Result ();
2173
2174 }
2175
2176 }
2177
2178 }
2179
2180 /*****************************************************************************/
2181
2182 void dng_negative::ValidateRawImageDigest (dng_host &host)
2183 {
2184
2185 if (Stage1Image () && !IsPreview () && (fRawImageDigest .IsValid () ||
2186 fNewRawImageDigest.IsValid ()))
2187 {
2188
2189 bool isNewDigest = fNewRawImageDigest.IsValid ();
2190
2191 dng_fingerprint &rawDigest = isNewDigest ? fNewRawImageDigest
2192 : fRawImageDigest;
2193
2194 if (RawLossyCompressedImageDigest ().IsValid () ||
2195 RawLossyCompressedImage ())
2196 {
2197
2198 FindRawLossyCompressedImageDigest (host);
2199
2200 if (rawDigest != RawLossyCompressedImageDigest ())
2201 {
2202
2203 #if qDNGValidate
2204
2205 ReportError ("NewRawImageDigest does not match Lossy Compressed image");
2206
2207 #endif
2208
2209 SetIsDamaged (true);
2210
2211 }
2212
2213 }
2214
2215 else if (fTransparencyMaskWasLossyCompressed)
2216 {
2217
2218 // We currently don't have a defined way of computing digest
2219 // that safely round trips in this case (lossless main image
2220 // and lossy transparancy mask).
2221
2222 }
2223
2224 // Else we can compare the stored digest to the image in memory.
2225
2226 else
2227 {
2228
2229 dng_fingerprint oldDigest = rawDigest;
2230
2231 try
2232 {
2233
2234 rawDigest.Clear ();
2235
2236 if (isNewDigest)
2237 {
2238
2239 FindNewRawImageDigest (host);
2240
2241 }
2242
2243 else
2244 {
2245
2246 FindRawImageDigest (host);
2247
2248 }
2249
2250 }
2251
2252 catch (...)
2253 {
2254
2255 rawDigest = oldDigest;
2256
2257 throw;
2258
2259 }
2260
2261 if (oldDigest != rawDigest)
2262 {
2263
2264 #if qDNGValidate
2265
2266 if (isNewDigest)
2267 {
2268 ReportError ("NewRawImageDigest does not match raw image");
2269 }
2270 else
2271 {
2272 ReportError ("RawImageDigest does not match raw image");
2273 }
2274
2275 SetIsDamaged (true);
2276
2277 #else
2278
2279 if (!isNewDigest)
2280 {
2281
2282 // Note that Lightroom 1.4 Windows had a bug that corrupts the
2283 // first four bytes of the RawImageDigest tag. So if the last
2284 // twelve bytes match, this is very likely the result of the
2285 // bug, and not an actual corrupt file. So don't report this
2286 // to the user--just fix it.
2287
2288 {
2289
2290 bool matchLast12 = true;
2291
2292 for (uint32 j = 4; j < 16; j++)
2293 {
2294 matchLast12 = matchLast12 && (oldDigest.data [j] == fRawImageDigest.data [j]);
2295 }
2296
2297 if (matchLast12)
2298 {
2299 return;
2300 }
2301
2302 }
2303
2304 // Sometimes Lightroom 1.4 would corrupt more than the first four
2305 // bytes, but for all those files that I have seen so far the
2306 // resulting first four bytes are 0x08 0x00 0x00 0x00.
2307
2308 if (oldDigest.data [0] == 0x08 &&
2309 oldDigest.data [1] == 0x00 &&
2310 oldDigest.data [2] == 0x00 &&
2311 oldDigest.data [3] == 0x00)
2312 {
2313 return;
2314 }
2315
2316 }
2317
2318 SetIsDamaged (true);
2319
2320 #endif
2321
2322 }
2323
2324 }
2325
2326 }
2327
2328 }
2329
2330 /*****************************************************************************/
2331
2332 dng_fingerprint dng_negative::RawDataUniqueID () const
2333 {
2334
2335 dng_lock_std_mutex lock (fRawDataUniqueIDMutex);
2336
2337 if (fRawDataUniqueID.IsValid () && fEnhanceParams.NotEmpty ())
2338 {
2339
2340 dng_md5_printer printer;
2341
2342 printer.Process (fRawDataUniqueID.data, 16);
2343
2344 printer.Process (fEnhanceParams.Get (),
2345 fEnhanceParams.Length ());
2346
2347 return printer.Result ();
2348
2349 }
2350
2351 return fRawDataUniqueID;
2352
2353 }
2354
2355 /*****************************************************************************/
2356
2357 // If the raw data unique ID is missing, compute one based on a MD5 hash of
2358 // the raw image hash and the model name, plus other commonly changed
2359 // data that can affect rendering.
2360
2361 void dng_negative::FindRawDataUniqueID (dng_host &host) const
2362 {
2363
2364 if (RawDataUniqueID ().IsNull ())
2365 {
2366
2367 dng_md5_printer_stream printer;
2368
2369 // If we have a raw lossy image, it is much faster to use its digest as
2370 // part of the unique ID since the data size is much smaller. We
2371 // cannot use it if there a transparency mask, since that is not
2372 // included in the RawLossyCompressedImageDigest.
2373
2374 if (RawLossyCompressedImage () && !RawTransparencyMask ())
2375 {
2376
2377 FindRawLossyCompressedImageDigest (host);
2378
2379 printer.Put (fRawLossyCompressedImageDigest.data,
2380 uint32 (sizeof (fRawLossyCompressedImageDigest.data)));
2381
2382 }
2383
2384 // Include the new raw image digest in the unique ID.
2385
2386 else
2387 {
2388
2389 FindNewRawImageDigest (host);
2390
2391 printer.Put (fNewRawImageDigest.data, 16);
2392
2393 }
2394
2395 // Include model name.
2396
2397 printer.Put (ModelName ().Get (),
2398 ModelName ().Length ());
2399
2400 // Include default crop area, since DNG Recover Edges can modify
2401 // these values and they affect rendering.
2402
2403 printer.Put_uint32 (fDefaultCropSizeH.n);
2404 printer.Put_uint32 (fDefaultCropSizeH.d);
2405
2406 printer.Put_uint32 (fDefaultCropSizeV.n);
2407 printer.Put_uint32 (fDefaultCropSizeV.d);
2408
2409 printer.Put_uint32 (fDefaultCropOriginH.n);
2410 printer.Put_uint32 (fDefaultCropOriginH.d);
2411
2412 printer.Put_uint32 (fDefaultCropOriginV.n);
2413 printer.Put_uint32 (fDefaultCropOriginV.d);
2414
2415 // Include default user crop.
2416
2417 printer.Put_uint32 (fDefaultUserCropT.n);
2418 printer.Put_uint32 (fDefaultUserCropT.d);
2419
2420 printer.Put_uint32 (fDefaultUserCropL.n);
2421 printer.Put_uint32 (fDefaultUserCropL.d);
2422
2423 printer.Put_uint32 (fDefaultUserCropB.n);
2424 printer.Put_uint32 (fDefaultUserCropB.d);
2425
2426 printer.Put_uint32 (fDefaultUserCropR.n);
2427 printer.Put_uint32 (fDefaultUserCropR.d);
2428
2429 // Include opcode lists, since lens correction utilities can modify
2430 // these values and they affect rendering.
2431
2432 fOpcodeList1.FingerprintToStream (printer);
2433 fOpcodeList2.FingerprintToStream (printer);
2434 fOpcodeList3.FingerprintToStream (printer);
2435
2436 dng_lock_std_mutex lock (fRawDataUniqueIDMutex);
2437
2438 fRawDataUniqueID = printer.Result ();
2439
2440 }
2441
2442 }
2443
2444 /******************************************************************************/
2445
2446 // Forces recomputation of RawDataUniqueID, useful to call
2447 // after modifying the opcode lists, etc.
2448
2449 void dng_negative::RecomputeRawDataUniqueID (dng_host &host)
2450 {
2451
2452 fRawDataUniqueID.Clear ();
2453
2454 FindRawDataUniqueID (host);
2455
2456 }
2457
2458 /******************************************************************************/
2459
2460 void dng_negative::FindOriginalRawFileDigest () const
2461 {
2462
2463 if (fOriginalRawFileDigest.IsNull () && fOriginalRawFileData.Get ())
2464 {
2465
2466 dng_md5_printer printer;
2467
2468 printer.Process (fOriginalRawFileData->Buffer (),
2469 fOriginalRawFileData->LogicalSize ());
2470
2471 fOriginalRawFileDigest = printer.Result ();
2472
2473 }
2474
2475 }
2476
2477 /*****************************************************************************/
2478
2479 void dng_negative::ValidateOriginalRawFileDigest ()
2480 {
2481
2482 if (fOriginalRawFileDigest.IsValid () && fOriginalRawFileData.Get ())
2483 {
2484
2485 dng_fingerprint oldDigest = fOriginalRawFileDigest;
2486
2487 try
2488 {
2489
2490 fOriginalRawFileDigest.Clear ();
2491
2492 FindOriginalRawFileDigest ();
2493
2494 }
2495
2496 catch (...)
2497 {
2498
2499 fOriginalRawFileDigest = oldDigest;
2500
2501 throw;
2502
2503 }
2504
2505 if (oldDigest != fOriginalRawFileDigest)
2506 {
2507
2508 #if qDNGValidate
2509
2510 ReportError ("OriginalRawFileDigest does not match OriginalRawFileData");
2511
2512 #else
2513
2514 SetIsDamaged (true);
2515
2516 #endif
2517
2518 // Don't "repair" the original image data digest. Once it is
2519 // bad, it stays bad. The user cannot tell by looking at the image
2520 // whether the damage is acceptable and can be ignored in the
2521 // future.
2522
2523 fOriginalRawFileDigest = oldDigest;
2524
2525 }
2526
2527 }
2528
2529 }
2530
2531 /******************************************************************************/
2532
2533 dng_rect dng_negative::DefaultCropArea () const
2534 {
2535
2536 // First compute the area using simple rounding.
2537
2538 dng_rect result;
2539
2540 result.l = Round_int32 (fDefaultCropOriginH.As_real64 () * fRawToFullScaleH);
2541 result.t = Round_int32 (fDefaultCropOriginV.As_real64 () * fRawToFullScaleV);
2542
2543 result.r = result.l + Round_int32 (fDefaultCropSizeH.As_real64 () * fRawToFullScaleH);
2544 result.b = result.t + Round_int32 (fDefaultCropSizeV.As_real64 () * fRawToFullScaleV);
2545
2546 // Sometimes the simple rounding causes the resulting default crop
2547 // area to slide off the scaled image area. So we force this not
2548 // to happen. We only do this if the image is not stubbed.
2549
2550 const dng_image *image = Stage3Image ();
2551
2552 if (image)
2553 {
2554
2555 dng_point imageSize = image->Size ();
2556
2557 if (result.r > imageSize.h)
2558 {
2559 result.l -= result.r - imageSize.h;
2560 result.r = imageSize.h;
2561 }
2562
2563 if (result.b > imageSize.v)
2564 {
2565 result.t -= result.b - imageSize.v;
2566 result.b = imageSize.v;
2567 }
2568
2569 }
2570
2571 return result;
2572
2573 }
2574
2575 /*****************************************************************************/
2576
2577 real64 dng_negative::TotalBaselineExposure (const dng_camera_profile_id &profileID) const
2578 {
2579
2580 real64 total = BaselineExposure ();
2581
2582 dng_camera_profile profile;
2583
2584 if (GetProfileByID (profileID, profile))
2585 {
2586
2587 real64 offset = profile.BaselineExposureOffset ().As_real64 ();
2588
2589 total += offset;
2590
2591 }
2592
2593 return total;
2594
2595 }
2596
2597 /******************************************************************************/
2598
2599 void dng_negative::SetShadowScale (const dng_urational &scale)
2600 {
2601
2602 if (scale.d > 0)
2603 {
2604
2605 real64 s = scale.As_real64 ();
2606
2607 if (s > 0.0 && s <= 1.0)
2608 {
2609
2610 fShadowScale = scale;
2611
2612 }
2613
2614 }
2615
2616 }
2617
2618 /******************************************************************************/
2619
2620 void dng_negative::SetActiveArea (const dng_rect &area)
2621 {
2622
2623 NeedLinearizationInfo ();
2624
2625 dng_linearization_info &info = *fLinearizationInfo.Get ();
2626
2627 info.fActiveArea = area;
2628
2629 }
2630
2631 /******************************************************************************/
2632
2633 void dng_negative::SetMaskedAreas (uint32 count,
2634 const dng_rect *area)
2635 {
2636
2637 DNG_ASSERT (count <= kMaxMaskedAreas, "Too many masked areas");
2638
2639 NeedLinearizationInfo ();
2640
2641 dng_linearization_info &info = *fLinearizationInfo.Get ();
2642
2643 info.fMaskedAreaCount = Min_uint32 (count, kMaxMaskedAreas);
2644
2645 for (uint32 index = 0; index < info.fMaskedAreaCount; index++)
2646 {
2647
2648 info.fMaskedArea [index] = area [index];
2649
2650 }
2651
2652 }
2653
2654 /*****************************************************************************/
2655
2656 void dng_negative::SetLinearization (AutoPtr<dng_memory_block> &curve)
2657 {
2658
2659 NeedLinearizationInfo ();
2660
2661 dng_linearization_info &info = *fLinearizationInfo.Get ();
2662
2663 info.fLinearizationTable.Reset (curve.Release ());
2664
2665 }
2666
2667 /*****************************************************************************/
2668
2669 void dng_negative::SetBlackLevel (real64 black,
2670 int32 plane)
2671 {
2672
2673 NeedLinearizationInfo ();
2674
2675 dng_linearization_info &info = *fLinearizationInfo.Get ();
2676
2677 info.fBlackLevelRepeatRows = 1;
2678 info.fBlackLevelRepeatCols = 1;
2679
2680 if (plane < 0)
2681 {
2682
2683 for (uint32 j = 0; j < kMaxColorPlanes; j++)
2684 {
2685
2686 info.fBlackLevel [0] [0] [j] = black;
2687
2688 }
2689
2690 }
2691
2692 else
2693 {
2694
2695 info.fBlackLevel [0] [0] [plane] = black;
2696
2697 }
2698
2699 info.RoundBlacks ();
2700
2701 }
2702
2703 /*****************************************************************************/
2704
2705 void dng_negative::SetQuadBlacks (real64 black0,
2706 real64 black1,
2707 real64 black2,
2708 real64 black3,
2709 int32 plane)
2710 {
2711
2712 NeedLinearizationInfo ();
2713
2714 dng_linearization_info &info = *fLinearizationInfo.Get ();
2715
2716 info.fBlackLevelRepeatRows = 2;
2717 info.fBlackLevelRepeatCols = 2;
2718
2719 if (plane < 0)
2720 {
2721
2722 for (uint32 j = 0; j < kMaxColorPlanes; j++)
2723 {
2724
2725 info.fBlackLevel [0] [0] [j] = black0;
2726 info.fBlackLevel [0] [1] [j] = black1;
2727 info.fBlackLevel [1] [0] [j] = black2;
2728 info.fBlackLevel [1] [1] [j] = black3;
2729
2730 }
2731
2732 }
2733
2734 else
2735 {
2736
2737 info.fBlackLevel [0] [0] [plane] = black0;
2738 info.fBlackLevel [0] [1] [plane] = black1;
2739 info.fBlackLevel [1] [0] [plane] = black2;
2740 info.fBlackLevel [1] [1] [plane] = black3;
2741
2742 }
2743
2744 info.RoundBlacks ();
2745
2746 }
2747
2748 /*****************************************************************************/
2749
2750 void dng_negative::Set6x6Blacks (real64 blacks6x6 [36],
2751 int32 plane)
2752 {
2753
2754 NeedLinearizationInfo ();
2755
2756 dng_linearization_info &info = *fLinearizationInfo.Get ();
2757
2758 info.fBlackLevelRepeatRows = 6;
2759 info.fBlackLevelRepeatCols = 6;
2760
2761 if (plane < 0)
2762 {
2763
2764 // Apply the black levels to each image plane up to kMaxColorPlanes.
2765
2766 for (uint32 p = 0; p < kMaxColorPlanes; p++)
2767 {
2768
2769 uint32 m = 0;
2770
2771 for (uint32 r = 0; r < info.fBlackLevelRepeatRows; r++)
2772 for (uint32 c = 0; c < info.fBlackLevelRepeatCols; c++)
2773 {
2774
2775 info.fBlackLevel [r] [c] [p] = blacks6x6 [m];
2776
2777 m++;
2778
2779 }
2780 }
2781 }
2782
2783 else
2784 {
2785
2786 uint32 m = 0;
2787
2788 // Apply the black levels to a single plane.
2789
2790 for (uint32 r = 0; r < info.fBlackLevelRepeatRows; r++)
2791 for (uint32 c = 0; c < info.fBlackLevelRepeatCols; c++)
2792 {
2793
2794 info.fBlackLevel [r] [c] [plane] = blacks6x6 [m];
2795
2796 m++;
2797
2798 }
2799
2800 }
2801
2802 info.RoundBlacks ();
2803
2804 }
2805
2806 /*****************************************************************************/
2807
2808 void dng_negative::SetRowBlacks (const real64 *blacks,
2809 uint32 count)
2810 {
2811
2812 if (count)
2813 {
2814
2815 NeedLinearizationInfo ();
2816
2817 dng_linearization_info &info = *fLinearizationInfo.Get ();
2818
2819 dng_safe_uint32 byteCount =
2820 dng_safe_uint32 (count) * (uint32) sizeof (real64);
2821
2822 info.fBlackDeltaV.Reset (Allocator ().Allocate (byteCount.Get ()));
2823
2824 DoCopyBytes (blacks,
2825 info.fBlackDeltaV->Buffer (),
2826 byteCount.Get ());
2827
2828 info.RoundBlacks ();
2829
2830 }
2831
2832 else if (fLinearizationInfo.Get ())
2833 {
2834
2835 dng_linearization_info &info = *fLinearizationInfo.Get ();
2836
2837 info.fBlackDeltaV.Reset ();
2838
2839 }
2840
2841 }
2842
2843 /*****************************************************************************/
2844
2845 void dng_negative::SetColumnBlacks (const real64 *blacks,
2846 uint32 count)
2847 {
2848
2849 if (count)
2850 {
2851
2852 NeedLinearizationInfo ();
2853
2854 dng_linearization_info &info = *fLinearizationInfo.Get ();
2855
2856 dng_safe_uint32 byteCount =
2857 dng_safe_uint32 (count) * (uint32) sizeof (real64);
2858
2859 info.fBlackDeltaH.Reset (Allocator ().Allocate (byteCount.Get ()));
2860
2861 DoCopyBytes (blacks,
2862 info.fBlackDeltaH->Buffer (),
2863 byteCount.Get ());
2864
2865 info.RoundBlacks ();
2866
2867 }
2868
2869 else if (fLinearizationInfo.Get ())
2870 {
2871
2872 dng_linearization_info &info = *fLinearizationInfo.Get ();
2873
2874 info.fBlackDeltaH.Reset ();
2875
2876 }
2877
2878 }
2879
2880 /*****************************************************************************/
2881
2882 uint32 dng_negative::WhiteLevel (uint32 plane) const
2883 {
2884
2885 if (fLinearizationInfo.Get ())
2886 {
2887
2888 const dng_linearization_info &info = *fLinearizationInfo.Get ();
2889
2890 return Round_uint32 (info.fWhiteLevel [plane]);
2891
2892 }
2893
2894 if (RawImage ().PixelType () == ttFloat)
2895 {
2896
2897 return 1;
2898
2899 }
2900
2901 return 0x0FFFF;
2902
2903 }
2904
2905 /*****************************************************************************/
2906
2907 void dng_negative::SetWhiteLevel (uint32 white,
2908 int32 plane)
2909 {
2910
2911 NeedLinearizationInfo ();
2912
2913 dng_linearization_info &info = *fLinearizationInfo.Get ();
2914
2915 if (plane < 0)
2916 {
2917
2918 for (uint32 j = 0; j < kMaxColorPlanes; j++)
2919 {
2920
2921 info.fWhiteLevel [j] = (real64) white;
2922
2923 }
2924
2925 }
2926
2927 else
2928 {
2929
2930 info.fWhiteLevel [plane] = (real64) white;
2931
2932 }
2933
2934 }
2935
2936 /******************************************************************************/
2937
2938 void dng_negative::SetColorKeys (ColorKeyCode color0,
2939 ColorKeyCode color1,
2940 ColorKeyCode color2,
2941 ColorKeyCode color3)
2942 {
2943
2944 NeedMosaicInfo ();
2945
2946 dng_mosaic_info &info = *fMosaicInfo.Get ();
2947
2948 info.fCFAPlaneColor [0] = color0;
2949 info.fCFAPlaneColor [1] = color1;
2950 info.fCFAPlaneColor [2] = color2;
2951 info.fCFAPlaneColor [3] = color3;
2952
2953 }
2954
2955 /******************************************************************************/
2956
2957 void dng_negative::SetBayerMosaic (uint32 phase)
2958 {
2959
2960 NeedMosaicInfo ();
2961
2962 dng_mosaic_info &info = *fMosaicInfo.Get ();
2963
2964 ColorKeyCode color0 = (ColorKeyCode) info.fCFAPlaneColor [0];
2965 ColorKeyCode color1 = (ColorKeyCode) info.fCFAPlaneColor [1];
2966 ColorKeyCode color2 = (ColorKeyCode) info.fCFAPlaneColor [2];
2967
2968 info.fCFAPatternSize = dng_point (2, 2);
2969
2970 switch (phase)
2971 {
2972
2973 case 0:
2974 {
2975 info.fCFAPattern [0] [0] = color1;
2976 info.fCFAPattern [0] [1] = color0;
2977 info.fCFAPattern [1] [0] = color2;
2978 info.fCFAPattern [1] [1] = color1;
2979 break;
2980 }
2981
2982 case 1:
2983 {
2984 info.fCFAPattern [0] [0] = color0;
2985 info.fCFAPattern [0] [1] = color1;
2986 info.fCFAPattern [1] [0] = color1;
2987 info.fCFAPattern [1] [1] = color2;
2988 break;
2989 }
2990
2991 case 2:
2992 {
2993 info.fCFAPattern [0] [0] = color2;
2994 info.fCFAPattern [0] [1] = color1;
2995 info.fCFAPattern [1] [0] = color1;
2996 info.fCFAPattern [1] [1] = color0;
2997 break;
2998 }
2999
3000 case 3:
3001 {
3002 info.fCFAPattern [0] [0] = color1;
3003 info.fCFAPattern [0] [1] = color2;
3004 info.fCFAPattern [1] [0] = color0;
3005 info.fCFAPattern [1] [1] = color1;
3006 break;
3007 }
3008
3009 }
3010
3011 info.fColorPlanes = 3;
3012
3013 info.fCFALayout = 1;
3014
3015 }
3016
3017 /******************************************************************************/
3018
3019 void dng_negative::SetFujiMosaic (uint32 phase)
3020 {
3021
3022 NeedMosaicInfo ();
3023
3024 dng_mosaic_info &info = *fMosaicInfo.Get ();
3025
3026 ColorKeyCode color0 = (ColorKeyCode) info.fCFAPlaneColor [0];
3027 ColorKeyCode color1 = (ColorKeyCode) info.fCFAPlaneColor [1];
3028 ColorKeyCode color2 = (ColorKeyCode) info.fCFAPlaneColor [2];
3029
3030 info.fCFAPatternSize = dng_point (2, 4);
3031
3032 switch (phase)
3033 {
3034
3035 case 0:
3036 {
3037 info.fCFAPattern [0] [0] = color0;
3038 info.fCFAPattern [0] [1] = color1;
3039 info.fCFAPattern [0] [2] = color2;
3040 info.fCFAPattern [0] [3] = color1;
3041 info.fCFAPattern [1] [0] = color2;
3042 info.fCFAPattern [1] [1] = color1;
3043 info.fCFAPattern [1] [2] = color0;
3044 info.fCFAPattern [1] [3] = color1;
3045 break;
3046 }
3047
3048 case 1:
3049 {
3050 info.fCFAPattern [0] [0] = color2;
3051 info.fCFAPattern [0] [1] = color1;
3052 info.fCFAPattern [0] [2] = color0;
3053 info.fCFAPattern [0] [3] = color1;
3054 info.fCFAPattern [1] [0] = color0;
3055 info.fCFAPattern [1] [1] = color1;
3056 info.fCFAPattern [1] [2] = color2;
3057 info.fCFAPattern [1] [3] = color1;
3058 break;
3059 }
3060
3061 }
3062
3063 info.fColorPlanes = 3;
3064
3065 info.fCFALayout = 2;
3066
3067 }
3068
3069 /*****************************************************************************/
3070
3071 void dng_negative::SetFujiMosaic6x6 (uint32 phase)
3072 {
3073
3074 NeedMosaicInfo ();
3075
3076 dng_mosaic_info &info = *fMosaicInfo.Get ();
3077
3078 ColorKeyCode color0 = (ColorKeyCode) info.fCFAPlaneColor [0];
3079 ColorKeyCode color1 = (ColorKeyCode) info.fCFAPlaneColor [1];
3080 ColorKeyCode color2 = (ColorKeyCode) info.fCFAPlaneColor [2];
3081
3082 const uint32 patSize = 6;
3083
3084 info.fCFAPatternSize = dng_point (patSize, patSize);
3085
3086 info.fCFAPattern [0] [0] = color1;
3087 info.fCFAPattern [0] [1] = color2;
3088 info.fCFAPattern [0] [2] = color1;
3089 info.fCFAPattern [0] [3] = color1;
3090 info.fCFAPattern [0] [4] = color0;
3091 info.fCFAPattern [0] [5] = color1;
3092
3093 info.fCFAPattern [1] [0] = color0;
3094 info.fCFAPattern [1] [1] = color1;
3095 info.fCFAPattern [1] [2] = color0;
3096 info.fCFAPattern [1] [3] = color2;
3097 info.fCFAPattern [1] [4] = color1;
3098 info.fCFAPattern [1] [5] = color2;
3099
3100 info.fCFAPattern [2] [0] = color1;
3101 info.fCFAPattern [2] [1] = color2;
3102 info.fCFAPattern [2] [2] = color1;
3103 info.fCFAPattern [2] [3] = color1;
3104 info.fCFAPattern [2] [4] = color0;
3105 info.fCFAPattern [2] [5] = color1;
3106
3107 info.fCFAPattern [3] [0] = color1;
3108 info.fCFAPattern [3] [1] = color0;
3109 info.fCFAPattern [3] [2] = color1;
3110 info.fCFAPattern [3] [3] = color1;
3111 info.fCFAPattern [3] [4] = color2;
3112 info.fCFAPattern [3] [5] = color1;
3113
3114 info.fCFAPattern [4] [0] = color2;
3115 info.fCFAPattern [4] [1] = color1;
3116 info.fCFAPattern [4] [2] = color2;
3117 info.fCFAPattern [4] [3] = color0;
3118 info.fCFAPattern [4] [4] = color1;
3119 info.fCFAPattern [4] [5] = color0;
3120
3121 info.fCFAPattern [5] [0] = color1;
3122 info.fCFAPattern [5] [1] = color0;
3123 info.fCFAPattern [5] [2] = color1;
3124 info.fCFAPattern [5] [3] = color1;
3125 info.fCFAPattern [5] [4] = color2;
3126 info.fCFAPattern [5] [5] = color1;
3127
3128 DNG_REQUIRE (phase < patSize * patSize,
3129 "Bad phase in SetFujiMosaic6x6.");
3130
3131 if (phase > 0)
3132 {
3133
3134 dng_mosaic_info temp = info;
3135
3136 uint32 phaseRow = phase / patSize;
3137
3138 uint32 phaseCol = phase - (phaseRow * patSize);
3139
3140 for (uint32 dstRow = 0; dstRow < patSize; dstRow++)
3141 {
3142
3143 uint32 srcRow = (dstRow + phaseRow) % patSize;
3144
3145 for (uint32 dstCol = 0; dstCol < patSize; dstCol++)
3146 {
3147
3148 uint32 srcCol = (dstCol + phaseCol) % patSize;
3149
3150 temp.fCFAPattern [dstRow] [dstCol] = info.fCFAPattern [srcRow] [srcCol];
3151
3152 }
3153
3154 }
3155
3156 info = temp;
3157
3158 }
3159
3160 info.fColorPlanes = 3;
3161
3162 info.fCFALayout = 1;
3163
3164 }
3165
3166 /******************************************************************************/
3167
3168 void dng_negative::SetQuadMosaic (uint32 pattern)
3169 {
3170
3171 // The pattern of the four colors is assumed to be repeat at least every two
3172 // columns and eight rows. The pattern is encoded as a 32-bit integer,
3173 // with every two bits encoding a color, in scan order for two columns and
3174 // eight rows (lsb is first). The usual color coding is:
3175 //
3176 // 0 = Green
3177 // 1 = Magenta
3178 // 2 = Cyan
3179 // 3 = Yellow
3180 //
3181 // Examples:
3182 //
3183 // PowerShot 600 uses 0xe1e4e1e4:
3184 //
3185 // 0 1 2 3 4 5
3186 // 0 G M G M G M
3187 // 1 C Y C Y C Y
3188 // 2 M G M G M G
3189 // 3 C Y C Y C Y
3190 //
3191 // PowerShot A5 uses 0x1e4e1e4e:
3192 //
3193 // 0 1 2 3 4 5
3194 // 0 C Y C Y C Y
3195 // 1 G M G M G M
3196 // 2 C Y C Y C Y
3197 // 3 M G M G M G
3198 //
3199 // PowerShot A50 uses 0x1b4e4b1e:
3200 //
3201 // 0 1 2 3 4 5
3202 // 0 C Y C Y C Y
3203 // 1 M G M G M G
3204 // 2 Y C Y C Y C
3205 // 3 G M G M G M
3206 // 4 C Y C Y C Y
3207 // 5 G M G M G M
3208 // 6 Y C Y C Y C
3209 // 7 M G M G M G
3210 //
3211 // PowerShot Pro70 uses 0x1e4b4e1b:
3212 //
3213 // 0 1 2 3 4 5
3214 // 0 Y C Y C Y C
3215 // 1 M G M G M G
3216 // 2 C Y C Y C Y
3217 // 3 G M G M G M
3218 // 4 Y C Y C Y C
3219 // 5 G M G M G M
3220 // 6 C Y C Y C Y
3221 // 7 M G M G M G
3222 //
3223 // PowerShots Pro90 and G1 use 0xb4b4b4b4:
3224 //
3225 // 0 1 2 3 4 5
3226 // 0 G M G M G M
3227 // 1 Y C Y C Y C
3228
3229 NeedMosaicInfo ();
3230
3231 dng_mosaic_info &info = *fMosaicInfo.Get ();
3232
3233 if (((pattern >> 16) & 0x0FFFF) != (pattern & 0x0FFFF))
3234 {
3235 info.fCFAPatternSize = dng_point (8, 2);
3236 }
3237
3238 else if (((pattern >> 8) & 0x0FF) != (pattern & 0x0FF))
3239 {
3240 info.fCFAPatternSize = dng_point (4, 2);
3241 }
3242
3243 else
3244 {
3245 info.fCFAPatternSize = dng_point (2, 2);
3246 }
3247
3248 for (int32 row = 0; row < info.fCFAPatternSize.v; row++)
3249 {
3250
3251 for (int32 col = 0; col < info.fCFAPatternSize.h; col++)
3252 {
3253
3254 uint32 index = (pattern >> ((((row << 1) & 14) + (col & 1)) << 1)) & 3;
3255
3256 info.fCFAPattern [row] [col] = info.fCFAPlaneColor [index];
3257
3258 }
3259
3260 }
3261
3262 info.fColorPlanes = 4;
3263
3264 info.fCFALayout = 1;
3265
3266 }
3267
3268 /******************************************************************************/
3269
3270 void dng_negative::SetGreenSplit (uint32 split)
3271 {
3272
3273 NeedMosaicInfo ();
3274
3275 dng_mosaic_info &info = *fMosaicInfo.Get ();
3276
3277 info.fBayerGreenSplit = split;
3278
3279 }
3280
3281 /*****************************************************************************/
3282
3283 void dng_negative::Parse (dng_host &host,
3284 dng_stream &stream,
3285 dng_info &info)
3286 {
3287
3288 // Shared info.
3289
3290 dng_shared &shared = *(info.fShared.Get ());
3291
3292 // Find IFD holding the main raw information.
3293
3294 dng_ifd &rawIFD = *info.fIFD [info.fMainIndex];
3295
3296 // Model name.
3297
3298 SetModelName (shared.fUniqueCameraModel.Get ());
3299
3300 // Localized model name.
3301
3302 SetLocalName (shared.fLocalizedCameraModel.Get ());
3303
3304 // Base orientation.
3305
3306 {
3307
3308 uint32 orientation = info.fIFD [0]->fOrientation;
3309
3310 if (orientation >= 1 && orientation <= 8)
3311 {
3312
3313 SetBaseOrientation (dng_orientation::TIFFtoDNG (orientation));
3314
3315 }
3316
3317 }
3318
3319 // Default crop rectangle.
3320
3321 SetDefaultCropSize (rawIFD.fDefaultCropSizeH,
3322 rawIFD.fDefaultCropSizeV);
3323
3324 SetDefaultCropOrigin (rawIFD.fDefaultCropOriginH,
3325 rawIFD.fDefaultCropOriginV);
3326
3327 // Default user crop rectangle.
3328
3329 SetDefaultUserCrop (rawIFD.fDefaultUserCropT,
3330 rawIFD.fDefaultUserCropL,
3331 rawIFD.fDefaultUserCropB,
3332 rawIFD.fDefaultUserCropR);
3333
3334 // Default scale.
3335
3336 SetDefaultScale (rawIFD.fDefaultScaleH,
3337 rawIFD.fDefaultScaleV);
3338
3339 // Best quality scale.
3340
3341 SetBestQualityScale (rawIFD.fBestQualityScale);
3342
3343 // Baseline noise.
3344
3345 SetBaselineNoise (shared.fBaselineNoise.As_real64 ());
3346
3347 // NoiseReductionApplied.
3348
3349 // Kludge: DNG spec says that NoiseReductionApplied tag should be in the
3350 // Raw IFD, not main IFD. However, our original DNG SDK implementation
3351 // read/wrote this tag from/to the main IFD. We now support reading the
3352 // NoiseReductionApplied tag from both locations, but prefer the raw IFD
3353 // (correct location).
3354
3355 if (rawIFD.fNoiseReductionApplied.IsValid ())
3356 {
3357
3358 SetNoiseReductionApplied (rawIFD.fNoiseReductionApplied);
3359
3360 }
3361
3362 else
3363 {
3364
3365 const dng_ifd &ifd0 = *info.fIFD [0];
3366
3367 SetNoiseReductionApplied (ifd0.fNoiseReductionApplied);
3368
3369 }
3370
3371 // NoiseProfile.
3372
3373 // Kludge: DNG spec says that NoiseProfile tag should be in the Raw IFD,
3374 // not main IFD. However, our original DNG SDK implementation read/wrote
3375 // this tag from/to the main IFD. We now support reading the NoiseProfile
3376 // tag from both locations, but prefer the raw IFD (correct location).
3377
3378 if (rawIFD.fNoiseProfile.IsValid ())
3379 {
3380
3381 SetNoiseProfile (rawIFD.fNoiseProfile);
3382
3383 }
3384
3385 else
3386 {
3387
3388 const dng_ifd &ifd0 = *info.fIFD [0];
3389
3390 SetNoiseProfile (ifd0.fNoiseProfile);
3391
3392 }
3393
3394 // Baseline exposure.
3395
3396 SetBaselineExposure (shared.fBaselineExposure.As_real64 ());
3397
3398 // Baseline sharpness.
3399
3400 SetBaselineSharpness (shared.fBaselineSharpness.As_real64 ());
3401
3402 // Chroma blur radius.
3403
3404 SetChromaBlurRadius (rawIFD.fChromaBlurRadius);
3405
3406 // Anti-alias filter strength.
3407
3408 SetAntiAliasStrength (rawIFD.fAntiAliasStrength);
3409
3410 // Linear response limit.
3411
3412 SetLinearResponseLimit (shared.fLinearResponseLimit.As_real64 ());
3413
3414 // Shadow scale.
3415
3416 SetShadowScale (shared.fShadowScale);
3417
3418 // Colorimetric reference.
3419
3420 SetColorimetricReference (shared.fColorimetricReference);
3421
3422 // Floating point flag.
3423
3424 SetFloatingPoint (rawIFD.fSampleFormat [0] == sfFloatingPoint);
3425
3426 // Color channels.
3427
3428 SetColorChannels (shared.fCameraProfile.fColorPlanes);
3429
3430 // Analog balance.
3431
3432 if (shared.fAnalogBalance.NotEmpty ())
3433 {
3434
3435 SetAnalogBalance (shared.fAnalogBalance);
3436
3437 }
3438
3439 // Camera calibration matrices
3440
3441 if (shared.fCameraCalibration1.NotEmpty ())
3442 {
3443
3444 SetCameraCalibration1 (shared.fCameraCalibration1);
3445
3446 }
3447
3448 if (shared.fCameraCalibration2.NotEmpty ())
3449 {
3450
3451 SetCameraCalibration2 (shared.fCameraCalibration2);
3452
3453 }
3454
3455 if (shared.fCameraCalibration3.NotEmpty ())
3456 {
3457
3458 SetCameraCalibration3 (shared.fCameraCalibration3);
3459
3460 }
3461
3462 if (shared.fCameraCalibration1.NotEmpty () ||
3463 shared.fCameraCalibration2.NotEmpty () ||
3464 shared.fCameraCalibration3.NotEmpty ())
3465 {
3466
3467 SetCameraCalibrationSignature (shared.fCameraCalibrationSignature.Get ());
3468
3469 }
3470
3471 // ProfileGainTableMap and ProfileGainTableMap2.
3472
3473 {
3474
3475 // ProfileGainTableMap2 usage is IFD 0 and supercedes
3476 // ProfileGainTablMap (whose usage is Raw IFD).
3477
3478 const dng_ifd &ifd0 = *info.fIFD [0];
3479
3480 if (ifd0.fProfileGainTableMap)
3481 {
3482
3483 SetProfileGainTableMap (ifd0.fProfileGainTableMap);
3484
3485 // Also mirror to main camera profile.
3486
3487 shared.fCameraProfile.fProfileGainTableMap =
3488 ifd0.fProfileGainTableMap;
3489
3490 }
3491
3492 else
3493 SetProfileGainTableMap (rawIFD.fProfileGainTableMap);
3494
3495 }
3496
3497 // Embedded camera profiles.
3498
3499 if (shared.fCameraProfile.fColorPlanes > 1)
3500 {
3501
3502 if (qDNGValidate || host.NeedsMeta () || host.NeedsImage ())
3503 {
3504
3505 // Add profile from main IFD.
3506
3507 {
3508
3509 AutoPtr<dng_camera_profile> profile (new dng_camera_profile ());
3510
3511 dng_camera_profile_info &profileInfo = shared.fCameraProfile;
3512
3513 profile->Parse (stream, profileInfo);
3514
3515 // The main embedded profile must be valid.
3516
3517 if (!profile->IsValid (shared.fCameraProfile.fColorPlanes))
3518 {
3519
3520 ThrowBadFormat ();
3521
3522 }
3523
3524 profile->SetWasReadFromDNG ();
3525
3526 AddProfile (profile);
3527
3528 }
3529
3530 // Extra profiles.
3531
3532 for (uint32 index = 0; index < (uint32) shared.fExtraCameraProfiles.size (); index++)
3533 {
3534
3535 try
3536 {
3537
3538 AutoPtr<dng_camera_profile> profile (new dng_camera_profile ());
3539
3540 dng_camera_profile_info &profileInfo = shared.fExtraCameraProfiles [index];
3541
3542 profile->Parse (stream, profileInfo);
3543
3544 if (!profile->IsValid (shared.fCameraProfile.fColorPlanes))
3545 {
3546
3547 ThrowBadFormat ();
3548
3549 }
3550
3551 profile->SetWasReadFromDNG ();
3552
3553 AddProfile (profile);
3554
3555 }
3556
3557 catch (dng_exception &except)
3558 {
3559
3560 // Don't ignore transient errors.
3561
3562 if (host.IsTransientError (except.ErrorCode ()))
3563 {
3564
3565 throw;
3566
3567 }
3568
3569 // Eat other parsing errors.
3570
3571 #if qDNGValidate
3572
3573 ReportWarning ("Unable to parse extra profile");
3574
3575 #endif
3576
3577 }
3578
3579 }
3580
3581 }
3582
3583 // As shot profile name.
3584
3585 if (shared.fAsShotProfileName.NotEmpty ())
3586 {
3587
3588 SetAsShotProfileName (shared.fAsShotProfileName.Get ());
3589
3590 }
3591
3592 }
3593
3594 // Raw image data digest.
3595
3596 if (shared.fRawImageDigest.IsValid ())
3597 {
3598
3599 SetRawImageDigest (shared.fRawImageDigest);
3600
3601 }
3602
3603 // New raw image data digest.
3604
3605 if (shared.fNewRawImageDigest.IsValid ())
3606 {
3607
3608 SetNewRawImageDigest (shared.fNewRawImageDigest);
3609
3610 }
3611
3612 // Raw data unique ID.
3613
3614 if (shared.fRawDataUniqueID.IsValid ())
3615 {
3616
3617 SetRawDataUniqueID (shared.fRawDataUniqueID);
3618
3619 }
3620
3621 // Original raw file name.
3622
3623 if (shared.fOriginalRawFileName.NotEmpty ())
3624 {
3625
3626 SetOriginalRawFileName (shared.fOriginalRawFileName.Get ());
3627
3628 }
3629
3630 // Original raw file data.
3631
3632 if (shared.fOriginalRawFileDataCount)
3633 {
3634
3635 SetHasOriginalRawFileData (true);
3636
3637 if (host.KeepOriginalFile ())
3638 {
3639
3640 uint32 count = shared.fOriginalRawFileDataCount;
3641
3642 AutoPtr<dng_memory_block> block (host.Allocate (count));
3643
3644 stream.SetReadPosition (shared.fOriginalRawFileDataOffset);
3645
3646 stream.Get (block->Buffer (), count);
3647
3648 SetOriginalRawFileData (block);
3649
3650 SetOriginalRawFileDigest (shared.fOriginalRawFileDigest);
3651
3652 ValidateOriginalRawFileDigest ();
3653
3654 }
3655
3656 }
3657
3658 // DNG private data.
3659
3660 if (shared.fDNGPrivateDataCount && (host.SaveDNGVersion () != dngVersion_None))
3661 {
3662
3663 uint32 length = shared.fDNGPrivateDataCount;
3664
3665 AutoPtr<dng_memory_block> block (host.Allocate (length));
3666
3667 stream.SetReadPosition (shared.fDNGPrivateDataOffset);
3668
3669 stream.Get (block->Buffer (), length);
3670
3671 SetPrivateData (block);
3672
3673 }
3674
3675 // Hand off EXIF metadata to negative.
3676
3677 ResetExif (info.fExif.Release ());
3678
3679 // Parse linearization info.
3680
3681 NeedLinearizationInfo ();
3682
3683 fLinearizationInfo.Get ()->Parse (host,
3684 stream,
3685 info);
3686
3687 // Parse mosaic info.
3688
3689 if (rawIFD.fPhotometricInterpretation == piCFA)
3690 {
3691
3692 NeedMosaicInfo ();
3693
3694 fMosaicInfo.Get ()->Parse (host,
3695 stream,
3696 info);
3697
3698 }
3699
3700 // Fill in original sizes.
3701
3702 if (shared.fOriginalDefaultFinalSize.h > 0 &&
3703 shared.fOriginalDefaultFinalSize.v > 0)
3704 {
3705
3706 SetOriginalDefaultFinalSize (shared.fOriginalDefaultFinalSize);
3707
3708 SetOriginalBestQualityFinalSize (shared.fOriginalDefaultFinalSize);
3709
3710 SetOriginalDefaultCropSize (dng_urational (shared.fOriginalDefaultFinalSize.h, 1),
3711 dng_urational (shared.fOriginalDefaultFinalSize.v, 1));
3712
3713 }
3714
3715 if (shared.fOriginalBestQualityFinalSize.h > 0 &&
3716 shared.fOriginalBestQualityFinalSize.v > 0)
3717 {
3718
3719 SetOriginalBestQualityFinalSize (shared.fOriginalBestQualityFinalSize);
3720
3721 }
3722
3723 if (shared.fOriginalDefaultCropSizeH.As_real64 () >= 1.0 &&
3724 shared.fOriginalDefaultCropSizeV.As_real64 () >= 1.0)
3725 {
3726
3727 SetOriginalDefaultCropSize (shared.fOriginalDefaultCropSizeH,
3728 shared.fOriginalDefaultCropSizeV);
3729
3730 }
3731
3732 if (shared.fDepthFormat != depthFormatUnknown)
3733 {
3734
3735 SetDepthFormat (shared.fDepthFormat);
3736
3737 }
3738
3739 if (shared.fDepthNear != dng_urational (0, 0))
3740 {
3741
3742 SetDepthNear (shared.fDepthNear);
3743
3744 }
3745
3746 if (shared.fDepthFar != dng_urational (0, 0))
3747 {
3748
3749 SetDepthFar (shared.fDepthFar);
3750
3751 }
3752
3753 if (shared.fDepthUnits != depthUnitsUnknown)
3754 {
3755
3756 SetDepthUnits (shared.fDepthUnits);
3757
3758 }
3759
3760 if (shared.fDepthMeasureType != depthMeasureUnknown)
3761 {
3762
3763 SetDepthMeasureType (shared.fDepthMeasureType);
3764
3765 }
3766
3767 // Prefer some values from the enhanced IFD, if present and we
3768 // are not ignoring it.
3769
3770 if (info.fEnhancedIndex != -1 && !host.IgnoreEnhanced ())
3771 {
3772
3773 dng_ifd &enhancedIFD = *info.fIFD [info.fEnhancedIndex];
3774
3775 // Remember the enhance parameters.
3776
3777 SetEnhanceParams (enhancedIFD.fEnhanceParams);
3778
3779 // Note: Call the various SetRaw... routines even if there are no
3780 // corresponding tags in the enhanced IFD. This way, the tag values are
3781 // correctly associated with the raw (original, non-enhanced) data and not
3782 // with the enhanced IFD. This distinction matters when converting a DNG
3783 // to a derived DNG.
3784
3785 // Baseline sharpness.
3786
3787 SetRawBaselineSharpness ();
3788
3789 if (enhancedIFD.fBaselineSharpness.IsValid ())
3790 {
3791
3792 SetBaselineSharpness (enhancedIFD.fBaselineSharpness.As_real64 ());
3793
3794 }
3795
3796 // Noise reduction applied.
3797
3798 SetRawNoiseReductionApplied ();
3799
3800 if (enhancedIFD.fNoiseReductionApplied.IsValid ())
3801 {
3802
3803 SetNoiseReductionApplied (enhancedIFD.fNoiseReductionApplied);
3804
3805 }
3806
3807 // Noise profile.
3808
3809 SetRawNoiseProfile ();
3810
3811 if (enhancedIFD.fNoiseProfile.IsValidForNegative (*this))
3812 {
3813
3814 SetNoiseProfile (enhancedIFD.fNoiseProfile);
3815
3816 }
3817
3818 // Default scale.
3819
3820 SetRawDefaultScale ();
3821
3822 if (enhancedIFD.fDefaultScaleH.IsValid () &&
3823 enhancedIFD.fDefaultScaleV.IsValid ())
3824 {
3825
3826 SetDefaultScale (enhancedIFD.fDefaultScaleH,
3827 enhancedIFD.fDefaultScaleV);
3828
3829 }
3830
3831 // Best quality scale.
3832
3833 SetRawBestQualityScale ();
3834
3835 if (enhancedIFD.fBestQualityScale.IsValid ())
3836 {
3837
3838 fBestQualityScale = enhancedIFD.fBestQualityScale;
3839
3840 }
3841
3842 // Default crop.
3843
3844 SetRawDefaultCrop ();
3845
3846 if (enhancedIFD.fDefaultCropSizeH.IsValid () &&
3847 enhancedIFD.fDefaultCropSizeV.IsValid ())
3848 {
3849
3850 fDefaultCropSizeH = enhancedIFD.fDefaultCropSizeH;
3851 fDefaultCropSizeV = enhancedIFD.fDefaultCropSizeV;
3852
3853 if (enhancedIFD.fDefaultCropOriginH.IsValid ())
3854 {
3855 fDefaultCropOriginH = enhancedIFD.fDefaultCropOriginH;
3856 }
3857 else
3858 {
3859 fDefaultCropOriginH = dng_urational (0, 1);
3860 }
3861
3862 if (enhancedIFD.fDefaultCropOriginV.IsValid ())
3863 {
3864 fDefaultCropOriginV = enhancedIFD.fDefaultCropOriginV;
3865 }
3866 else
3867 {
3868 fDefaultCropOriginV = dng_urational (0, 1);
3869 }
3870
3871 }
3872
3873 }
3874
3875 // Image Stats.
3876
3877 if (rawIFD.fImageStats.IsValidForPlaneCount (ColorChannels ()) &&
3878 (rawIFD.fImageStats.TagCount () > 0))
3879 {
3880
3881 fMetadata.SetImageStats (rawIFD.fImageStats);
3882
3883 }
3884
3885 }
3886
3887 /*****************************************************************************/
3888
3889 void dng_negative::ClearOriginalSizes ()
3890 {
3891
3892 fOriginalDefaultFinalSize = dng_point ();
3893
3894 fOriginalBestQualityFinalSize = dng_point ();
3895
3896 fOriginalDefaultCropSizeH.Clear ();
3897 fOriginalDefaultCropSizeV.Clear ();
3898
3899 }
3900
3901 /*****************************************************************************/
3902
3903 void dng_negative::SetDefaultOriginalSizes ()
3904 {
3905
3906 // Fill in original sizes if we don't have them already.
3907
3908 if (OriginalDefaultFinalSize () == dng_point ())
3909 {
3910
3911 SetOriginalDefaultFinalSize (dng_point (DefaultFinalHeight (),
3912 DefaultFinalWidth ()));
3913
3914 }
3915
3916 if (OriginalBestQualityFinalSize () == dng_point ())
3917 {
3918
3919 SetOriginalBestQualityFinalSize (dng_point (BestQualityFinalHeight (),
3920 BestQualityFinalWidth ()));
3921
3922 }
3923
3924 if (OriginalDefaultCropSizeH ().NotValid () ||
3925 OriginalDefaultCropSizeV ().NotValid ())
3926 {
3927
3928 SetOriginalDefaultCropSize (DefaultCropSizeH (),
3929 DefaultCropSizeV ());
3930
3931 }
3932
3933 }
3934
3935 /*****************************************************************************/
3936
3937 void dng_negative::SetOriginalSizes (const dng_point &size)
3938 {
3939
3940 SetOriginalDefaultFinalSize (size);
3941
3942 SetOriginalBestQualityFinalSize (size);
3943
3944 SetOriginalDefaultCropSize (dng_urational (size.h, 1),
3945 dng_urational (size.v, 1));
3946
3947 }
3948
3949 /*****************************************************************************/
3950
3951 void dng_negative::PostParse (dng_host &host,
3952 dng_stream &stream,
3953 dng_info &info)
3954 {
3955
3956 // Shared info.
3957
3958 dng_shared &shared = *(info.fShared.Get ());
3959
3960 if (host.NeedsMeta ())
3961 {
3962
3963 // Fill in original sizes if we don't have them already.
3964
3965 SetDefaultOriginalSizes ();
3966
3967 // MakerNote.
3968
3969 if (shared.fMakerNoteCount)
3970 {
3971
3972 // See if we know if the MakerNote is safe or not.
3973
3974 SetMakerNoteSafety (shared.fMakerNoteSafety == 1);
3975
3976 // If the MakerNote is safe, preserve it as a MakerNote.
3977
3978 if (IsMakerNoteSafe ())
3979 {
3980
3981 AutoPtr<dng_memory_block> block (host.Allocate (shared.fMakerNoteCount));
3982
3983 stream.SetReadPosition (shared.fMakerNoteOffset + info.fTIFFBlockOriginalOffset -
3984 info.fTIFFBlockOffset);
3985
3986 stream.Get (block->Buffer (), shared.fMakerNoteCount);
3987
3988 SetMakerNote (block);
3989
3990 }
3991
3992 }
3993
3994 // IPTC metadata.
3995
3996 if (shared.fIPTC_NAA_Count)
3997 {
3998
3999 AutoPtr<dng_memory_block> block (host.Allocate (shared.fIPTC_NAA_Count));
4000
4001 stream.SetReadPosition (shared.fIPTC_NAA_Offset);
4002
4003 uint64 iptcOffset = stream.PositionInOriginalFile();
4004
4005 stream.Get (block->Buffer (),
4006 block->LogicalSize ());
4007
4008 SetIPTC (block, iptcOffset);
4009
4010 }
4011
4012 // XMP metadata.
4013
4014 #if qDNGUseXMP
4015
4016 if (shared.fXMPCount)
4017 {
4018
4019 AutoPtr<dng_memory_block> block (host.Allocate (shared.fXMPCount));
4020
4021 stream.SetReadPosition (shared.fXMPOffset);
4022
4023 stream.Get (block->Buffer (),
4024 block->LogicalSize ());
4025
4026 Metadata ().SetEmbeddedXMP (host,
4027 block->Buffer (),
4028 block->LogicalSize ());
4029
4030 #if qDNGValidate
4031
4032 if (!Metadata ().HaveValidEmbeddedXMP ())
4033 {
4034 ReportError ("The embedded XMP is invalid");
4035 }
4036
4037 #endif
4038
4039 }
4040
4041 #endif // qDNGUseXMP
4042
4043 // Embedded big tables.
4044
4045 if (shared.fBigTableDigests.size ())
4046 {
4047
4048 dng_big_table_index bigTableIndex;
4049
4050 for (uint32 j = 0; j < (uint32) shared.fBigTableDigests.size (); j++)
4051 {
4052
4053 if (!shared.fBigTableDigests [j].IsValid () ||
4054 !shared.fBigTableOffsets [j] ||
4055 !shared.fBigTableByteCounts [j])
4056 {
4057 continue;
4058 }
4059
4060 bigTableIndex.AddEntry (shared.fBigTableDigests [j],
4061 shared.fBigTableByteCounts [j],
4062 shared.fBigTableOffsets [j]);
4063
4064 }
4065
4066 if (!bigTableIndex.IsEmpty ())
4067 {
4068
4069 Metadata ().SetBigTableIndex (bigTableIndex);
4070
4071 }
4072
4073 // Big table group index.
4074
4075 if (!shared.fBigTableGroupIndex.empty ())
4076 {
4077
4078 dng_big_table_group_index index;
4079
4080 for (const auto &group : shared.fBigTableGroupIndex)
4081 {
4082
4083 if (group.first .IsValid () &&
4084 group.second.IsValid ())
4085 {
4086
4087 index.AddEntry (group.first,
4088 group.second);
4089
4090 }
4091
4092 }
4093
4094 if (!index.IsEmpty ())
4095 {
4096
4097 Metadata ().SetBigTableGroupIndex (index);
4098
4099 }
4100
4101 }
4102
4103 }
4104
4105 // Color info.
4106
4107 if (!IsMonochrome ())
4108 {
4109
4110 // If the ColorimetricReference is the ICC profile PCS,
4111 // then the data must be already be white balanced to the
4112 // ICC profile PCS white point.
4113
4114 if (IsOutputReferred ())
4115 {
4116
4117 ClearCameraNeutral ();
4118
4119 SetCameraWhiteXY (PCStoXY ());
4120
4121 }
4122
4123 else
4124 {
4125
4126 // AsShotNeutral.
4127
4128 if (shared.fAsShotNeutral.Count () == ColorChannels ())
4129 {
4130
4131 SetCameraNeutral (shared.fAsShotNeutral);
4132
4133 }
4134
4135 // AsShotWhiteXY.
4136
4137 if (shared.fAsShotWhiteXY.IsValid () && !HasCameraNeutral ())
4138 {
4139
4140 SetCameraWhiteXY (shared.fAsShotWhiteXY);
4141
4142 }
4143
4144 }
4145
4146 } // color info
4147
4148 // Image sequence info.
4149
4150 if (shared.fImageSequenceInfo.IsValid ())
4151 {
4152
4153 fMetadata.SetImageSequenceInfo (shared.fImageSequenceInfo);
4154
4155 }
4156
4157 } // needs meta
4158
4159 }
4160
4161 /*****************************************************************************/
4162
4163 bool dng_negative::SetFourColorBayer ()
4164 {
4165
4166 if (ColorChannels () != 3)
4167 {
4168 return false;
4169 }
4170
4171 if (!fMosaicInfo.Get ())
4172 {
4173 return false;
4174 }
4175
4176 if (!fMosaicInfo.Get ()->SetFourColorBayer ())
4177 {
4178 return false;
4179 }
4180
4181 SetColorChannels (4);
4182
4183 if (fCameraNeutral.Count () == 3)
4184 {
4185
4186 dng_vector n (4);
4187
4188 n [0] = fCameraNeutral [0];
4189 n [1] = fCameraNeutral [1];
4190 n [2] = fCameraNeutral [2];
4191 n [3] = fCameraNeutral [1];
4192
4193 fCameraNeutral = n;
4194
4195 }
4196
4197 fCameraCalibration1.Clear ();
4198 fCameraCalibration2.Clear ();
4199 fCameraCalibration3.Clear ();
4200
4201 fCameraCalibrationSignature.Clear ();
4202
4203 for (uint32 index = 0; index < (uint32) fCameraProfile.size (); index++)
4204 {
4205
4206 fCameraProfile [index]->SetFourColorBayer ();
4207
4208 }
4209
4210 return true;
4211
4212 }
4213
4214 /*****************************************************************************/
4215
4216 const dng_image & dng_negative::RawImage () const
4217 {
4218
4219 if (fRawImage.Get ())
4220 {
4221 return *fRawImage.Get ();
4222 }
4223
4224 if (fStage1Image.Get ())
4225 {
4226 return *fStage1Image.Get ();
4227 }
4228
4229 if (fUnflattenedStage3Image.Get ())
4230 {
4231 return *fUnflattenedStage3Image.Get ();
4232 }
4233
4234 DNG_REQUIRE (fStage3Image.Get (),
4235 "dng_negative::RawImage with no raw image");
4236
4237 return *fStage3Image.Get ();
4238
4239 }
4240
4241 /*****************************************************************************/
4242
4243 uint16 dng_negative::RawImageBlackLevel () const
4244 {
4245
4246 if (fRawImage.Get ())
4247 {
4248 return fRawImageBlackLevel;
4249 }
4250
4251 if (fStage1Image.Get ())
4252 {
4253 return 0;
4254 }
4255
4256 return fStage3BlackLevel;
4257
4258 }
4259
4260 /*****************************************************************************/
4261
4262 const dng_lossy_compressed_image * dng_negative::RawLossyCompressedImage () const
4263 {
4264
4265 return fRawLossyCompressedImage.Get ();
4266
4267 }
4268
4269 /*****************************************************************************/
4270
4271 void dng_negative::SetRawLossyCompressedImage (AutoPtr<dng_lossy_compressed_image> &image)
4272 {
4273
4274 fRawLossyCompressedImage.Reset (image.Release ());
4275
4276 }
4277
4278 /*****************************************************************************/
4279
4280 void dng_negative::ClearRawLossyCompressedImage ()
4281 {
4282
4283 fRawLossyCompressedImage.Reset ();
4284
4285 }
4286
4287 /*****************************************************************************/
4288
4289 void dng_negative::FindRawLossyCompressedImageDigest (dng_host &host) const
4290 {
4291
4292 if (fRawLossyCompressedImageDigest.IsNull ())
4293 {
4294
4295 if (fRawLossyCompressedImage.Get ())
4296 {
4297
4298 #if qDNGValidate
4299
4300 dng_timer timer ("FindRawLossyCompressedImageDigest");
4301
4302 #endif
4303
4304 fRawLossyCompressedImageDigest = fRawLossyCompressedImage->FindDigest (host);
4305
4306 }
4307
4308 else
4309 {
4310
4311 ThrowProgramError ("No raw lossy compressed image");
4312
4313 }
4314
4315 }
4316
4317 }
4318
4319 /*****************************************************************************/
4320
4321 void dng_negative::ReadOpcodeLists (dng_host &host,
4322 dng_stream &stream,
4323 dng_info &info)
4324 {
4325
4326 dng_ifd &rawIFD = *info.fIFD [info.fMainIndex];
4327
4328 if (rawIFD.fOpcodeList1Count)
4329 {
4330
4331 #if qDNGValidate
4332
4333 if (gVerbose)
4334 {
4335 printf ("\nParsing OpcodeList1: ");
4336 }
4337
4338 #endif
4339
4340 fOpcodeList1.Parse (host,
4341 stream,
4342 rawIFD.fOpcodeList1Count,
4343 rawIFD.fOpcodeList1Offset);
4344
4345 }
4346
4347 if (rawIFD.fOpcodeList2Count)
4348 {
4349
4350 #if qDNGValidate
4351
4352 if (gVerbose)
4353 {
4354 printf ("\nParsing OpcodeList2: ");
4355 }
4356
4357 #endif
4358
4359 fOpcodeList2.Parse (host,
4360 stream,
4361 rawIFD.fOpcodeList2Count,
4362 rawIFD.fOpcodeList2Offset);
4363
4364 }
4365
4366 if (rawIFD.fOpcodeList3Count)
4367 {
4368
4369 #if qDNGValidate
4370
4371 if (gVerbose)
4372 {
4373 printf ("\nParsing OpcodeList3: ");
4374 }
4375
4376 #endif
4377
4378 fOpcodeList3.Parse (host,
4379 stream,
4380 rawIFD.fOpcodeList3Count,
4381 rawIFD.fOpcodeList3Offset);
4382
4383 }
4384
4385 }
4386
4387 /*****************************************************************************/
4388
4389 void dng_negative::ReadStage1Image (dng_host &host,
4390 dng_stream &stream,
4391 dng_info &info)
4392 {
4393
4394 // Allocate image we are reading.
4395
4396 dng_ifd &rawIFD = *info.fIFD [info.fMainIndex];
4397
4398 fStage1Image.Reset (host.Make_dng_image (rawIFD.Bounds (),
4399 rawIFD.fSamplesPerPixel,
4400 rawIFD.PixelType ()));
4401
4402 // See if we should grab the lossy compressed data.
4403
4404 AutoPtr<dng_lossy_compressed_image> lossyImage (KeepLossyCompressedImage (host,
4405 rawIFD));
4406
4407 // See if we need to compute the digest of the compressed JPEG or JPEG XL
4408 // data while reading.
4409
4410 bool needLossyDigest = ((RawImageDigest ().IsValid () ||
4411 NewRawImageDigest ().IsValid ()) &&
4412
4413 ((rawIFD.fCompression == ccLossyJPEG ||
4414 rawIFD.fCompression == ccJXL) &&
4415 (lossyImage.Get () == NULL)));
4416
4417 dng_fingerprint lossyDigest;
4418
4419 // Read the image.
4420
4421 rawIFD.ReadImage (host,
4422 stream,
4423 *fStage1Image.Get (),
4424 lossyImage.Get (),
4425 needLossyDigest ? &lossyDigest : NULL);
4426
4427 // Remember the raw floating point bit depth, if reading from
4428 // a floating point image.
4429
4430 if (fStage1Image->PixelType () == ttFloat)
4431 {
4432
4433 SetRawFloatBitDepth (rawIFD.fBitsPerSample [0]);
4434
4435 }
4436
4437 // Remember the compressed JPEG data if we read it.
4438
4439 if (lossyImage.Get ())
4440 {
4441
4442 SetRawLossyCompressedImage (lossyImage);
4443
4444 }
4445
4446 // Remember the compressed JPEG digest if we computed it.
4447
4448 if (lossyDigest.IsValid ())
4449 {
4450
4451 SetRawLossyCompressedImageDigest (lossyDigest);
4452
4453 }
4454
4455 // We are are reading the main image, we should read the opcode lists
4456 // also.
4457
4458 ReadOpcodeLists (host,
4459 stream,
4460 info);
4461
4462 }
4463
4464 /*****************************************************************************/
4465
4466 void dng_negative::ReadEnhancedImage (dng_host &host,
4467 dng_stream &stream,
4468 dng_info &info)
4469 {
4470
4471 // Should we read the raw image also?
4472
4473 bool needRawImage = host.SaveDNGVersion () != 0 &&
4474 !host.SaveLinearDNG (*this);
4475
4476 // Allocate image we are reading.
4477
4478 dng_ifd &enhancedIFD = *info.fIFD [info.fEnhancedIndex];
4479
4480 fStage3Image.Reset (host.Make_dng_image (enhancedIFD.Bounds (),
4481 enhancedIFD.fSamplesPerPixel,
4482 enhancedIFD.PixelType ()));
4483
4484 // Do we need to keep the lossy compressed data?
4485
4486 if (needRawImage)
4487 {
4488
4489 fEnhancedLossyCompressedImage.Reset (KeepLossyCompressedImage (host,
4490 enhancedIFD));
4491
4492 }
4493
4494 // Read the image.
4495
4496 enhancedIFD.ReadImage (host,
4497 stream,
4498 *fStage3Image.Get (),
4499 fEnhancedLossyCompressedImage.Get ());
4500
4501 // Stage 3 black level.
4502
4503 SetStage3BlackLevel ((uint16) Round_uint32 (enhancedIFD.fBlackLevel [0] [0] [0]));
4504
4505 // If we are saving as a linear DNG, the saved profile should
4506 // match the profile for the stage3 image.
4507
4508 if (host.SaveDNGVersion () != 0 && host.SaveLinearDNG (*this))
4509 {
4510
4511 AdjustProfileForStage3 ();
4512
4513 }
4514
4515 // Read in raw image data if required.
4516
4517 if (needRawImage)
4518 {
4519
4520 ReadStage1Image (host,
4521 stream,
4522 info);
4523
4524 fRawImage.Reset (fStage1Image.Release ());
4525
4526 }
4527
4528 // Else we can discard the information specific to the raw IFD.
4529
4530 else
4531 {
4532
4533 // We at least need to know about lens opcodes, so we read the
4534 // opcodes and then discard them.
4535
4536 ReadOpcodeLists (host,
4537 stream,
4538 info);
4539
4540 ClearLinearizationInfo ();
4541
4542 ClearMosaicInfo ();
4543
4544 fOpcodeList1.Clear ();
4545 fOpcodeList2.Clear ();
4546 fOpcodeList3.Clear ();
4547
4548 fRawImageDigest .Clear ();
4549 fNewRawImageDigest.Clear ();
4550
4551 fRawDefaultCropSizeH.Clear ();
4552 fRawDefaultCropSizeV.Clear ();
4553
4554 fRawDefaultCropOriginH.Clear ();
4555 fRawDefaultCropOriginV.Clear ();
4556
4557 fRawDefaultScaleH.Clear ();
4558 fRawDefaultScaleV.Clear ();
4559
4560 fRawBestQualityScale.Clear ();
4561
4562 fRawBaselineSharpness .Clear ();
4563 fRawNoiseReductionApplied.Clear ();
4564
4565 fRawNoiseProfile = dng_noise_profile ();
4566
4567 if (fRawDataUniqueID.IsValid ())
4568 {
4569 fRawDataUniqueID = RawDataUniqueID ();
4570 }
4571
4572 fEnhanceParams.Clear ();
4573
4574 }
4575
4576 }
4577
4578 /*****************************************************************************/
4579
4580 void dng_negative::SetStage1Image (AutoPtr<dng_image> &image)
4581 {
4582
4583 fStage1Image.Reset (image.Release ());
4584
4585 }
4586
4587 /*****************************************************************************/
4588
4589 void dng_negative::ClearStage1Image ()
4590 {
4591
4592 fStage1Image.Reset ();
4593
4594 }
4595
4596 /*****************************************************************************/
4597
4598 void dng_negative::SetStage2Image (AutoPtr<dng_image> &image)
4599 {
4600
4601 fStage2Image.Reset (image.Release ());
4602
4603 }
4604
4605 /*****************************************************************************/
4606
4607 void dng_negative::SetStage3Image (AutoPtr<dng_image> &image)
4608 {
4609
4610 fStage3Image.Reset (image.Release ());
4611
4612 SetFloatingPoint (fStage3Image.Get () &&
4613 (fStage3Image->PixelType () == ttFloat));
4614
4615 }
4616
4617 /*****************************************************************************/
4618
4619 void dng_negative::DoBuildStage2 (dng_host &host)
4620 {
4621
4622 dng_image &stage1 = *fStage1Image.Get ();
4623
4624 dng_linearization_info &info = *fLinearizationInfo.Get ();
4625
4626 uint32 pixelType = ttShort;
4627
4628 if (stage1.PixelType () == ttLong ||
4629 stage1.PixelType () == ttFloat)
4630 {
4631
4632 pixelType = ttFloat;
4633
4634 }
4635
4636 fStage2Image.Reset (host.Make_dng_image (info.fActiveArea.Size (),
4637 stage1.Planes (),
4638 pixelType));
4639
4640 info.Linearize (host,
4641 *this,
4642 stage1,
4643 *fStage2Image.Get ());
4644
4645 }
4646
4647 /*****************************************************************************/
4648
4649 void dng_negative::DoPostOpcodeList2 (dng_host & /* host */)
4650 {
4651
4652 // Nothing by default.
4653
4654 }
4655
4656 /*****************************************************************************/
4657
4658 bool dng_negative::NeedDefloatStage2 (dng_host &host)
4659 {
4660
4661 if (fStage2Image->PixelType () == ttFloat)
4662 {
4663
4664 if (fRawImageStage >= rawImageStagePostOpcode2 &&
4665 host.SaveDNGVersion () != dngVersion_None &&
4666 host.SaveDNGVersion () < dngVersion_1_4_0_0)
4667 {
4668
4669 return true;
4670
4671 }
4672
4673 }
4674
4675 return false;
4676
4677 }
4678
4679 /*****************************************************************************/
4680
4681 void dng_negative::DefloatStage2 (dng_host & /* host */)
4682 {
4683
4684 ThrowNotYetImplemented ("dng_negative::DefloatStage2");
4685
4686 }
4687
4688 /*****************************************************************************/
4689
4690 void dng_negative::BuildStage2Image (dng_host &host)
4691 {
4692
4693 // If reading the negative to save in DNG format, figure out
4694 // when to grab a copy of the raw data.
4695
4696 if (host.SaveDNGVersion () != dngVersion_None)
4697 {
4698
4699 // Transparency masks are only supported in DNG version 1.4 and
4700 // later. In this case, the flattening of the transparency mask happens
4701 // on the stage3 image.
4702
4703 if (TransparencyMask () && host.SaveDNGVersion () < dngVersion_1_4_0_0)
4704 {
4705 fRawImageStage = rawImageStagePostOpcode3;
4706 }
4707
4708 else if (fOpcodeList3.MinVersion (false) > host.SaveDNGVersion () ||
4709 fOpcodeList3.AlwaysApply ())
4710 {
4711 fRawImageStage = rawImageStagePostOpcode3;
4712 }
4713
4714 // If we are not doing a full resolution read, then always save the DNG
4715 // from the processed stage 3 image.
4716
4717 else if (host.PreferredSize ())
4718 {
4719 fRawImageStage = rawImageStagePostOpcode3;
4720 }
4721
4722 else if (host.SaveLinearDNG (*this))
4723 {
4724
4725 // If the opcode list 3 has optional tags that are beyond the
4726 // the minimum version, and we are saving a linear DNG anyway,
4727 // then go ahead and apply them.
4728
4729 if (fOpcodeList3.MinVersion (true) > host.SaveDNGVersion ())
4730 {
4731 fRawImageStage = rawImageStagePostOpcode3;
4732 }
4733
4734 else
4735 {
4736 fRawImageStage = rawImageStagePreOpcode3;
4737 }
4738
4739 }
4740
4741 else if (fOpcodeList2.MinVersion (false) > host.SaveDNGVersion () ||
4742 fOpcodeList2.AlwaysApply ())
4743 {
4744 fRawImageStage = rawImageStagePostOpcode2;
4745 }
4746
4747 else if (NeedLossyCompressMosaicJXL (host))
4748 {
4749 fRawImageStage = rawImageStagePostOpcode2;
4750 }
4751
4752 else if (fOpcodeList1.MinVersion (false) > host.SaveDNGVersion () ||
4753 fOpcodeList1.AlwaysApply ())
4754 {
4755 fRawImageStage = rawImageStagePostOpcode1;
4756 }
4757
4758 else
4759 {
4760 fRawImageStage = rawImageStagePreOpcode1;
4761 }
4762
4763 // We should not save floating point stage1 images unless the target
4764 // DNG version is high enough to understand floating point images.
4765 // We handle this by converting from floating point to integer if
4766 // required after building stage2 image.
4767
4768 if (fStage1Image->PixelType () == ttFloat)
4769 {
4770
4771 if (fRawImageStage < rawImageStagePostOpcode2)
4772 {
4773
4774 if (host.SaveDNGVersion () < dngVersion_1_4_0_0)
4775 {
4776
4777 fRawImageStage = rawImageStagePostOpcode2;
4778
4779 }
4780
4781 }
4782
4783 }
4784
4785 // If the host is requesting a negative read for fast conversion to
4786 // DNG, then check whether we can actually do a fast interpolation or
4787 // not. For now, keep the logic simple. If the raw image stage is the
4788 // pre-opcode stage 1 image (original), then proceed with trying a
4789 // fast/downsampled interpolation when building the stage 3 image.
4790 // Otherwise, turn off the attempted optimization.
4791
4792 if (host.ForFastSaveToDNG () &&
4793 (fRawImageStage > rawImageStagePreOpcode1))
4794 {
4795
4796 // Disable/revert the optimization attempt, and do a normal
4797 // interpolation when building the stage 3 image.
4798
4799 host.SetForFastSaveToDNG (false, 0);
4800
4801 }
4802
4803 }
4804
4805 // Grab clone of raw image if required.
4806
4807 if (fRawImageStage == rawImageStagePreOpcode1)
4808 {
4809
4810 fRawImage.Reset (fStage1Image->Clone ());
4811
4812 if (fTransparencyMask.Get ())
4813 {
4814 fRawTransparencyMask.Reset (fTransparencyMask->Clone ());
4815 }
4816
4817 if (fDepthMap.Get ())
4818 {
4819 fRawDepthMap.Reset (fDepthMap->Clone ());
4820 }
4821
4822 // If we choose to resize semantic masks to match the stage 3 image,
4823 // then this would be a good time to grab a copy of the semantic masks
4824 // and store them separately.
4825
4826 // ...
4827
4828 }
4829
4830 else
4831 {
4832
4833 // If we are not keeping the most raw image, we need
4834 // to recompute the raw image digest.
4835
4836 ClearRawImageDigest ();
4837
4838 // If we don't grab the unprocessed stage 1 image, then
4839 // the raw lossy compressed image is no longer valid.
4840
4841 ClearRawLossyCompressedImage ();
4842
4843 // Nor is the digest of the raw lossy compressed data.
4844
4845 ClearRawLossyCompressedImageDigest ();
4846
4847 // We also don't know the raw floating point bit depth.
4848
4849 SetRawFloatBitDepth (0);
4850
4851 }
4852
4853 // Process opcode list 1.
4854
4855 host.ApplyOpcodeList (fOpcodeList1, *this, fStage1Image);
4856
4857 // See if we are done with the opcode list 1.
4858
4859 if (fRawImageStage > rawImageStagePreOpcode1)
4860 {
4861
4862 fOpcodeList1.Clear ();
4863
4864 }
4865
4866 // Grab clone of raw image if required.
4867
4868 if (fRawImageStage == rawImageStagePostOpcode1)
4869 {
4870
4871 fRawImage.Reset (fStage1Image->Clone ());
4872
4873 if (fTransparencyMask.Get ())
4874 {
4875 fRawTransparencyMask.Reset (fTransparencyMask->Clone ());
4876 }
4877
4878 if (fDepthMap.Get ())
4879 {
4880 fRawDepthMap.Reset (fDepthMap->Clone ());
4881 }
4882
4883 // If we choose to resize semantic masks to match the stage 3 image,
4884 // then this would be a good time to grab a copy of the semantic masks
4885 // and store them separately.
4886
4887 // ...
4888
4889 }
4890
4891 // Finalize linearization info.
4892
4893 {
4894
4895 NeedLinearizationInfo ();
4896
4897 dng_linearization_info &info = *fLinearizationInfo.Get ();
4898
4899 info.PostParse (host, *this);
4900
4901 }
4902
4903 // Perform the linearization.
4904
4905 DoBuildStage2 (host);
4906
4907 // Delete the stage1 image now that we have computed the stage 2 image.
4908
4909 fStage1Image.Reset ();
4910
4911 // Are we done with the linearization info.
4912
4913 if (fRawImageStage > rawImageStagePostOpcode1)
4914 {
4915
4916 ClearLinearizationInfo ();
4917
4918 }
4919
4920 // Process opcode list 2.
4921
4922 host.ApplyOpcodeList (fOpcodeList2, *this, fStage2Image);
4923
4924 // See if we are done with the opcode list 2.
4925
4926 if (fRawImageStage > rawImageStagePostOpcode1)
4927 {
4928
4929 fOpcodeList2.Clear ();
4930
4931 }
4932
4933 // Hook for any required processing just after opcode list 2.
4934
4935 DoPostOpcodeList2 (host);
4936
4937 // Convert from floating point to integer if required.
4938
4939 if (NeedDefloatStage2 (host))
4940 {
4941
4942 DefloatStage2 (host);
4943
4944 }
4945
4946 // Grab clone of raw image if required.
4947
4948 if (fRawImageStage == rawImageStagePostOpcode2)
4949 {
4950
4951 fRawImage.Reset (fStage2Image->Clone ());
4952
4953 fRawImageBlackLevel = fStage3BlackLevel;
4954
4955 if (fTransparencyMask.Get ())
4956 {
4957 fRawTransparencyMask.Reset (fTransparencyMask->Clone ());
4958 }
4959
4960 if (fDepthMap.Get ())
4961 {
4962 fRawDepthMap.Reset (fDepthMap->Clone ());
4963 }
4964
4965 // If we choose to resize semantic masks to match the stage 3 image,
4966 // then this would be a good time to grab a copy of the semantic masks
4967 // and store them separately.
4968
4969 // ...
4970
4971 }
4972
4973 }
4974
4975 /*****************************************************************************/
4976
4977 void dng_negative::DoInterpolateStage3 (dng_host &host,
4978 int32 srcPlane,
4979 dng_matrix *scaleTransforms)
4980 {
4981
4982 dng_image &stage2 = *fStage2Image.Get ();
4983
4984 dng_mosaic_info &info = *fMosaicInfo.Get ();
4985
4986 dng_point downScale;
4987
4988 const bool fastSaveToDNG = host.ForFastSaveToDNG ();
4989
4990 const uint32 fastSaveSize = host.FastSaveToDNGSize ();
4991
4992 if (fastSaveToDNG && (fastSaveSize > 0))
4993 {
4994
4995 downScale = info.DownScale (host.MinimumSize (),
4996 host.FastSaveToDNGSize (),
4997 host.CropFactor ());
4998
4999 }
5000
5001 else
5002 {
5003
5004 downScale = info.DownScale (host.MinimumSize (),
5005 host.PreferredSize (),
5006 host.CropFactor ());
5007
5008 }
5009
5010 if (downScale != dng_point (1, 1))
5011 {
5012 SetIsPreview (true);
5013 }
5014
5015 dng_point dstSize = info.DstSize (downScale);
5016
5017 fStage3Image.Reset (host.Make_dng_image (dng_rect (dstSize),
5018 info.fColorPlanes,
5019 stage2.PixelType ()));
5020
5021 if (srcPlane < 0 || srcPlane >= (int32) stage2.Planes ())
5022 {
5023 srcPlane = 0;
5024 }
5025
5026 info.Interpolate (host,
5027 *this,
5028 stage2,
5029 *fStage3Image.Get (),
5030 downScale,
5031 srcPlane,
5032 scaleTransforms);
5033
5034 }
5035
5036 /*****************************************************************************/
5037
5038 // Interpolate and merge a multi-channel CFA image.
5039
5040 void dng_negative::DoMergeStage3 (dng_host &host,
5041 dng_matrix *scaleTransforms)
5042 {
5043
5044 // The DNG SDK does not provide multi-channel CFA image merging code.
5045 // It just grabs the first channel and uses that.
5046
5047 DoInterpolateStage3 (host, 0, scaleTransforms);
5048
5049 // Just grabbing the first channel would often result in the very
5050 // bright image using the baseline exposure value.
5051
5052 fStage3Gain = pow (2.0, BaselineExposure ());
5053
5054 }
5055
5056 /*****************************************************************************/
5057
5058 void dng_negative::DoBuildStage3 (dng_host &host,
5059 int32 srcPlane,
5060 dng_matrix *scaleTransforms)
5061 {
5062
5063 // If we don't have a mosaic pattern, then just move the stage 2
5064 // image on to stage 3.
5065
5066 dng_mosaic_info *info = fMosaicInfo.Get ();
5067
5068 if (!info || !info->IsColorFilterArray ())
5069 {
5070
5071 fStage3Image.Reset (fStage2Image.Release ());
5072
5073 }
5074
5075 else
5076 {
5077
5078 // Remember the size of the stage 2 image.
5079
5080 dng_point stage2_size = fStage2Image->Size ();
5081
5082 // Special case multi-channel CFA interpolation.
5083
5084 if ((fStage2Image->Planes () > 1) && (srcPlane < 0))
5085 {
5086
5087 DoMergeStage3 (host,
5088 scaleTransforms);
5089
5090 }
5091
5092 // Else do a single channel interpolation.
5093
5094 else
5095 {
5096
5097 DoInterpolateStage3 (host,
5098 srcPlane,
5099 scaleTransforms);
5100
5101 }
5102
5103 // Calculate the ratio of the stage 3 image size to stage 2 image size.
5104
5105 dng_point stage3_size = fStage3Image->Size ();
5106
5107 fRawToFullScaleH = (real64) stage3_size.h / (real64) stage2_size.h;
5108 fRawToFullScaleV = (real64) stage3_size.v / (real64) stage2_size.v;
5109
5110 }
5111
5112 }
5113
5114 /*****************************************************************************/
5115
5116 void dng_negative::BuildStage3Image (dng_host &host,
5117 int32 srcPlane)
5118 {
5119
5120 // Finalize the mosaic information.
5121
5122 dng_mosaic_info *info = fMosaicInfo.Get ();
5123
5124 if (info)
5125 {
5126
5127 info->PostParse (host, *this);
5128
5129 }
5130
5131 // Do the interpolation as required.
5132
5133 DoBuildStage3 (host, srcPlane, NULL);
5134
5135 // Delete the stage2 image now that we have computed the stage 3 image,
5136 // unless the host wants to preserve it.
5137
5138 if (!host.WantsPreserveStage2 ())
5139 {
5140
5141 fStage2Image.Reset ();
5142
5143 }
5144
5145 // Are we done with the mosaic info?
5146
5147 if (fRawImageStage >= rawImageStagePreOpcode3)
5148 {
5149
5150 // If we're preserving the stage 2 image, also preserve the mosaic
5151 // info.
5152
5153 if (!host.WantsPreserveStage2 ())
5154 {
5155
5156 ClearMosaicInfo ();
5157
5158 }
5159
5160 }
5161
5162 // If we are keeping the raw image, keep the raw default
5163 // crop and scale information.
5164
5165 if (fRawImageStage < rawImageStagePreOpcode3)
5166 {
5167
5168 SetRawDefaultCrop ();
5169 SetRawDefaultScale ();
5170 SetRawBestQualityScale ();
5171
5172 }
5173
5174 // To support saving linear DNG files, to need to account for
5175 // and upscaling during interpolation.
5176
5177 if (fRawToFullScaleH > 1.0)
5178 {
5179
5180 fDefaultCropSizeH .ScaleBy (fRawToFullScaleH);
5181 fDefaultCropOriginH.ScaleBy (fRawToFullScaleH);
5182 fDefaultScaleH .ScaleBy (1.0 / fRawToFullScaleH);
5183
5184 fRawToFullScaleH = 1.0;
5185
5186 }
5187
5188 if (fRawToFullScaleV > 1.0)
5189 {
5190
5191 fDefaultCropSizeV .ScaleBy (fRawToFullScaleV);
5192 fDefaultCropOriginV.ScaleBy (fRawToFullScaleV);
5193 fDefaultScaleV .ScaleBy (1.0 / fRawToFullScaleV);
5194
5195 fRawToFullScaleV = 1.0;
5196
5197 }
5198
5199 // Resample the transparency mask if required.
5200
5201 ResizeTransparencyToMatchStage3 (host);
5202
5203 // Grab clone of raw image if required.
5204
5205 if (fRawImageStage == rawImageStagePreOpcode3)
5206 {
5207
5208 fRawImage.Reset (fStage3Image->Clone ());
5209
5210 fRawImageBlackLevel = fStage3BlackLevel;
5211
5212 if (fTransparencyMask.Get ())
5213 {
5214 fRawTransparencyMask.Reset (fTransparencyMask->Clone ());
5215 }
5216
5217 if (fDepthMap.Get ())
5218 {
5219 fRawDepthMap.Reset (fDepthMap->Clone ());
5220 }
5221
5222 // If we choose to resize semantic masks to match the stage 3 image,
5223 // then this would be a good time to grab a copy of the semantic masks
5224 // and store them separately.
5225
5226 // ...
5227
5228 }
5229
5230 // Process opcode list 3.
5231
5232 host.ApplyOpcodeList (fOpcodeList3, *this, fStage3Image);
5233
5234 // See if we are done with the opcode list 3.
5235
5236 if (fRawImageStage > rawImageStagePreOpcode3)
5237 {
5238
5239 // Currently re-use the same flag for preserving the opcode list.
5240
5241 if (!host.WantsPreserveStage2 ())
5242 {
5243
5244 fOpcodeList3.Clear ();
5245
5246 }
5247
5248 }
5249
5250 // Just in case the opcode list 3 changed the image size, resample the
5251 // transparency mask again if required. This is nearly always going
5252 // to be a fast NOP operation.
5253
5254 ResizeTransparencyToMatchStage3 (host);
5255
5256 // Depth maps are often lower resolution than the main image,
5257 // so make sure we upsample if required.
5258
5259 ResizeDepthToMatchStage3 (host);
5260
5261 // For now, do not resize semantic masks to match stage 3 image.
5262
5263 // Update Floating Point flag.
5264
5265 SetFloatingPoint (fStage3Image->PixelType () == ttFloat);
5266
5267 // Don't need to grab a copy of raw data at this stage since
5268 // it is kept around as the stage 3 image.
5269
5270 }
5271
5272 /******************************************************************************/
5273
5274 class dng_base_proxy_curve
5275 {
5276
5277 public:
5278
5279 virtual ~dng_base_proxy_curve ()
5280 {
5281 }
5282
5283 virtual real64 EvaluateScene (real64 x) const = 0;
5284
5285 virtual real64 EvaluateOutput (real64 x) const = 0;
5286
5287 virtual real64 SceneSlope () const = 0;
5288
5289 virtual real64 OutputSlope () const = 0;
5290
5291 };
5292
5293 /*****************************************************************************/
5294
5295 class dng_jpeg_proxy_curve : public dng_base_proxy_curve
5296 {
5297
5298 // RESEARCH: Instead of using a constant slope, consider using a family of
5299 // slopes ranging from the original one (1/16) to a limit of 1/128,
5300 // depending on the histogram distribution.
5301
5302 private:
5303
5304 static constexpr real64 kSceneProxyCurveSlope = 1.0 / 128.0;
5305
5306 static constexpr real64 kOutputProxyCurveSlope = 1.0 / 16.0;
5307
5308 public:
5309
5310 virtual real64 EvaluateScene (real64 x) const override
5311 {
5312
5313 // The following code evaluates the inverse of:
5314 //
5315 // f (x) = (s * x) + ((1 - s) * x^3)
5316 //
5317 // where s is the slope of the function at the origin (x==0).
5318
5319 static constexpr real64 s = kSceneProxyCurveSlope;
5320
5321 static const real64 k0 = pow (2.0, 1.0 / 3.0);
5322
5323 static constexpr real64 k1 = 108.0 * s * s * s * (1.0 - s) * (1.0 - s) * (1.0 - s);
5324
5325 real64 k2 = (27.0 * x) - (54.0 * s * x) + (27.0 * x * s * s);
5326
5327 real64 k3 = pow (k2 + sqrt (k1 + k2 * k2), 1.0 / 3.0);
5328
5329 real64 y = (k3 / (3.0 * k0 * (1.0 - s))) - (k0 * s / k3);
5330
5331 y = Pin_real64 (0.0, y, 1.0);
5332
5333 #if 0
5334
5335 DNG_ASSERT (Abs_real64 (x - (kSceneProxyCurveSlope * y +
5336 (1.0 - kSceneProxyCurveSlope) * y * y * y)) < 0.0000001,
5337 "SceneProxyCurve round trip error");
5338
5339 #endif
5340
5341 return y;
5342
5343 }
5344
5345 virtual real64 EvaluateOutput (real64 x) const override
5346 {
5347
5348 // DNG_ASSERT (kOutputProxyCurveSlope == 1.0 / 16.0,
5349 // "OutputProxyCurve unexpected slope");
5350
5351 real64 y = (sqrt (960.0 * x + 1.0) - 1.0) / 30.0;
5352
5353 #if 0
5354
5355 DNG_ASSERT (Abs_real64 (x - (kOutputProxyCurveSlope * y +
5356 (1.0 - kOutputProxyCurveSlope) * y * y)) < 0.0000001,
5357 "OutputProxyCurve round trip error");
5358
5359 #endif
5360
5361 return y;
5362
5363 }
5364
5365 virtual real64 SceneSlope () const override
5366 {
5367 return kSceneProxyCurveSlope;
5368 }
5369
5370 virtual real64 OutputSlope () const override
5371 {
5372 return kOutputProxyCurveSlope;
5373 }
5374
5375 };
5376
5377 /*****************************************************************************/
5378
5379 // This curve is intended for integer data, not floating-point data.
5380
5381 class dng_jxl_proxy_curve : public dng_base_proxy_curve
5382 {
5383
5384 #if 1
5385
5386 // Non-linear curve that is similar to what we use for JPEGs. Bigger
5387 // files, but much better shadow response.
5388
5389 private:
5390
5391 static constexpr real64 kSceneProxyCurveSlope = 1.0 / 16.0;
5392
5393 static constexpr real64 kOutputProxyCurveSlope = 1.0 / 16.0;
5394
5395 public:
5396
5397 virtual real64 EvaluateScene (real64 x) const override
5398 {
5399
5400 // The following code evaluates the inverse of:
5401 //
5402 // f (x) = (s * x) + ((1 - s) * x^3)
5403 //
5404 // where s is the slope of the function at the origin (x==0).
5405
5406 static constexpr real64 s = kSceneProxyCurveSlope;
5407
5408 static const real64 k0 = pow (2.0, 1.0 / 3.0);
5409
5410 static constexpr real64 k1 = 108.0 * s * s * s * (1.0 - s) * (1.0 - s) * (1.0 - s);
5411
5412 real64 k2 = (27.0 * x) - (54.0 * s * x) + (27.0 * x * s * s);
5413
5414 real64 k3 = pow (k2 + sqrt (k1 + k2 * k2), 1.0 / 3.0);
5415
5416 real64 y = (k3 / (3.0 * k0 * (1.0 - s))) - (k0 * s / k3);
5417
5418 y = Pin_real64 (0.0, y, 1.0);
5419
5420 #if 0
5421
5422 DNG_ASSERT (Abs_real64 (x - (kSceneProxyCurveSlope * y +
5423 (1.0 - kSceneProxyCurveSlope) * y * y * y)) < 0.0000001,
5424 "SceneProxyCurve round trip error");
5425
5426 #endif
5427
5428 return y;
5429
5430 }
5431
5432 virtual real64 EvaluateOutput (real64 x) const override
5433 {
5434
5435 // DNG_ASSERT (kOutputProxyCurveSlope == 1.0 / 16.0,
5436 // "OutputProxyCurve unexpected slope");
5437
5438 real64 y = (sqrt (960.0 * x + 1.0) - 1.0) / 30.0;
5439
5440 #if 0
5441
5442 DNG_ASSERT (Abs_real64 (x - (kOutputProxyCurveSlope * y +
5443 (1.0 - kOutputProxyCurveSlope) * y * y)) < 0.0000001,
5444 "OutputProxyCurve round trip error");
5445
5446 #endif
5447
5448 return y;
5449
5450 }
5451
5452 virtual real64 SceneSlope () const override
5453 {
5454 return kSceneProxyCurveSlope;
5455 }
5456
5457 virtual real64 OutputSlope () const override
5458 {
5459 return kOutputProxyCurveSlope;
5460 }
5461
5462 #else
5463
5464 // No curve. This causes JPEG XL to overly compress in the shadows.
5465
5466 public:
5467
5468 virtual real64 EvaluateScene (real64 x) const override
5469 {
5470 return x;
5471 }
5472
5473 virtual real64 EvaluateOutput (real64 x) const override
5474 {
5475 return x;
5476 }
5477
5478 virtual real64 SceneSlope () const override
5479 {
5480 return 1.0;
5481 }
5482
5483 virtual real64 OutputSlope () const override
5484 {
5485 return 1.0;
5486 }
5487
5488 #endif // new vs old method
5489
5490 };
5491
5492 /*****************************************************************************/
5493
5494 class dng_gamma_encode_proxy : public dng_1d_function
5495 {
5496
5497 private:
5498
5499 real64 fLower;
5500 real64 fUpper;
5501
5502 bool fIsSceneReferred;
5503
5504 real64 fStage3BlackLevel;
5505
5506 real64 fBlackLevel;
5507
5508 const dng_base_proxy_curve &fBaseCurve;
5509
5510 public:
5511
5512 dng_gamma_encode_proxy (real64 lower,
5513 real64 upper,
5514 bool isSceneReferred,
5515 real64 stage3BlackLevel,
5516 real64 blackLevel,
5517 const dng_base_proxy_curve &baseCurve)
5518
5519 : fLower (lower)
5520 , fUpper (upper)
5521 , fIsSceneReferred (isSceneReferred)
5522 , fStage3BlackLevel (stage3BlackLevel)
5523 , fBlackLevel (blackLevel)
5524 , fBaseCurve (baseCurve)
5525
5526 {
5527
5528 }
5529
5530 virtual real64 Evaluate (real64 x) const
5531 {
5532
5533 real64 y;
5534
5535 if (fIsSceneReferred)
5536 {
5537
5538 if (fLower < fStage3BlackLevel)
5539 {
5540
5541 x = Pin_real64 (-1.0,
5542 (x - fStage3BlackLevel) / (fUpper - fStage3BlackLevel),
5543 1.0);
5544
5545 if (x >= 0.0)
5546 {
5547
5548 y = fBaseCurve.EvaluateScene (x);
5549
5550 }
5551
5552 else
5553 {
5554
5555 y = -fBaseCurve.EvaluateScene (-x);
5556
5557 }
5558
5559 y = Pin_real64 (0.0, y * (1.0 - fBlackLevel) + fBlackLevel, 1.0);
5560
5561 }
5562
5563 else
5564 {
5565
5566 x = Pin_real64 (0.0, (x - fLower) / (fUpper - fLower), 1.0);
5567
5568 y = fBaseCurve.EvaluateScene (x);
5569
5570 }
5571
5572 }
5573
5574 else
5575 {
5576
5577 x = Pin_real64 (0.0, (x - fLower) / (fUpper - fLower), 1.0);
5578
5579 y = fBaseCurve.EvaluateOutput (x);
5580
5581 }
5582
5583 return y;
5584
5585 }
5586
5587 };
5588
5589 /*****************************************************************************/
5590
5591 class dng_encode_proxy_task: public dng_area_task,
5592 private dng_uncopyable
5593 {
5594
5595 private:
5596
5597 const dng_image &fSrcImage;
5598
5599 dng_image &fDstImage;
5600
5601 AutoPtr<dng_memory_block> fTable16 [kMaxColorPlanes];
5602
5603 public:
5604
5605 dng_encode_proxy_task (dng_host &host,
5606 const dng_image &srcImage,
5607 dng_image &dstImage,
5608 const real64 *lower,
5609 const real64 *upper,
5610 bool isSceneReferred,
5611 real64 stage3BlackLevel,
5612 real64 *blackLevel,
5613 real64 whiteLevel,
5614 const dng_base_proxy_curve &baseCurve);
5615
5616 virtual dng_rect RepeatingTile1 () const
5617 {
5618 return fSrcImage.RepeatingTile ();
5619 }
5620
5621 virtual dng_rect RepeatingTile2 () const
5622 {
5623 return fDstImage.RepeatingTile ();
5624 }
5625
5626 virtual void Process (uint32 threadIndex,
5627 const dng_rect &tile,
5628 dng_abort_sniffer *sniffer);
5629
5630 };
5631
5632 /*****************************************************************************/
5633
5634 dng_encode_proxy_task::dng_encode_proxy_task (dng_host &host,
5635 const dng_image &srcImage,
5636 dng_image &dstImage,
5637 const real64 *lower,
5638 const real64 *upper,
5639 bool isSceneReferred,
5640 real64 stage3BlackLevel,
5641 real64 *blackLevel,
5642 real64 whiteLevel,
5643 const dng_base_proxy_curve &baseCurve)
5644
5645 : dng_area_task ("dng_encode_proxy_task")
5646
5647 , fSrcImage (srcImage)
5648 , fDstImage (dstImage)
5649
5650 {
5651
5652 for (uint32 plane = 0; plane < fSrcImage.Planes (); plane++)
5653 {
5654
5655 fTable16 [plane] . Reset (host.Allocate (0x10000 * sizeof (uint16)));
5656
5657 const real64 normBlackLevel = blackLevel [plane] / whiteLevel;
5658
5659 dng_gamma_encode_proxy gamma (lower [plane],
5660 upper [plane],
5661 isSceneReferred,
5662 stage3BlackLevel,
5663 normBlackLevel,
5664 baseCurve);
5665
5666 // Compute fast approximation of encoding table.
5667
5668 dng_1d_table table32;
5669
5670 table32.Initialize (host.Allocator (), gamma);
5671
5672 table32.Expand16 (fTable16 [plane]->Buffer_uint16 ());
5673
5674 // The gamma curve has some fairly high curvature near
5675 // the black point, and the above approximation can actually
5676 // change results. So use exact math near the black point.
5677 // Still very fast, since we are only computing a small
5678 // fraction of the range exactly.
5679
5680 {
5681
5682 const int32 kHighResRadius = 1024;
5683
5684 uint32 zeroPt = Round_uint32 (stage3BlackLevel * 65535.0);
5685
5686 uint32 highResLower = Max_int32 (0 , zeroPt - kHighResRadius);
5687 uint32 highResUpper = Min_int32 (0x10000, zeroPt + kHighResRadius);
5688
5689 for (uint32 j = highResLower; j < highResUpper; j++)
5690 {
5691
5692 real64 x = j * (1.0 / 65535.0);
5693
5694 real64 y = gamma.Evaluate (x);
5695
5696 uint16 z = Pin_uint16 (Round_int32 (y * 65535.0));
5697
5698 fTable16 [plane]->Buffer_uint16 () [j] = z;
5699
5700 }
5701
5702 }
5703
5704 }
5705
5706 }
5707
5708 /*****************************************************************************/
5709
5710 void dng_encode_proxy_task::Process (uint32 /* threadIndex */,
5711 const dng_rect &tile,
5712 dng_abort_sniffer * /* sniffer */)
5713 {
5714
5715 dng_const_tile_buffer srcBuffer (fSrcImage, tile);
5716 dng_dirty_tile_buffer dstBuffer (fDstImage, tile);
5717
5718 int32 sColStep = srcBuffer.fColStep;
5719 int32 dColStep = dstBuffer.fColStep;
5720
5721 if (fDstImage.PixelSize () == 2)
5722 {
5723
5724 // 16-bit path.
5725
5726 for (uint32 plane = 0; plane < fSrcImage.Planes (); plane++)
5727 {
5728
5729 const uint16 *map = fTable16 [plane]->Buffer_uint16 ();
5730
5731 for (int32 row = tile.t; row < tile.b; row++)
5732 {
5733
5734 const uint16 *sPtr = srcBuffer.ConstPixel_uint16 (row, tile.l, plane);
5735
5736 uint16 *dPtr = dstBuffer.DirtyPixel_uint16 (row, tile.l, plane);
5737
5738 for (int32 col = tile.l; col < tile.r; col++)
5739 {
5740
5741 *dPtr = map [*sPtr];
5742
5743 sPtr += sColStep;
5744 dPtr += dColStep;
5745
5746 }
5747
5748 }
5749
5750 }
5751
5752 }
5753
5754 else
5755 {
5756
5757 // 8-bit path.
5758
5759 const uint16 *noise = dng_dither::Get ().NoiseBuffer16 ();
5760
5761 for (uint32 plane = 0; plane < fSrcImage.Planes (); plane++)
5762 {
5763
5764 const uint16 *map = fTable16 [plane]->Buffer_uint16 ();
5765
5766 for (int32 row = tile.t; row < tile.b; row++)
5767 {
5768
5769 const uint16 *sPtr = srcBuffer.ConstPixel_uint16 (row, tile.l, plane);
5770
5771 uint8 *dPtr = dstBuffer.DirtyPixel_uint8 (row, tile.l, plane);
5772
5773 const uint16 *rPtr = &noise [(row & dng_dither::kRNGMask) * dng_dither::kRNGSize];
5774
5775 for (int32 col = tile.l; col < tile.r; col++)
5776 {
5777
5778 // BULLSHIT: "Noise_Planes_Issue"
5779 // For each pixel we are applying the same noise to each plane.
5780 // This does not seem ideal at it will shift all planes equally for each pixel.
5781 // Is this really what we want? Maybe it helps to preseve hue slightly?
5782 // Not sure if this was 100% intentional or not.
5783
5784 uint32 x = *sPtr;
5785
5786 uint32 r = rPtr [col & dng_dither::kRNGMask];
5787
5788 x = map [x];
5789
5790 x = (((x << 8) - x) + r) >> 16;
5791
5792 *dPtr = (uint8) x;
5793
5794 sPtr += sColStep;
5795 dPtr += dColStep;
5796
5797 }
5798
5799 }
5800
5801 }
5802
5803 }
5804
5805 }
5806
5807 /******************************************************************************/
5808
5809 bool dng_negative::SupportsPreservedBlackLevels (dng_host & /* host */)
5810 {
5811
5812 return false;
5813
5814 }
5815
5816 /******************************************************************************/
5817
5818 dng_image * EncodeImageForCompression (dng_host &host,
5819 const dng_image &srcImage,
5820 const dng_rect &activeArea,
5821 const bool isSceneReferred,
5822 const bool use16bit,
5823 const real64 srcBlackLevel,
5824 real64 *dstBlackLevel,
5825 dng_opcode_list &opcodeList)
5826 {
5827
5828 if (srcImage.PixelType () != ttShort)
5829 {
5830 return nullptr;
5831 }
5832
5833 real64 lower [kMaxColorPlanes];
5834 real64 upper [kMaxColorPlanes];
5835
5836 {
5837
5838 const real64 kClipFraction = 0.00001;
5839
5840 uint64 pixels = (uint64) activeArea.H () *
5841 (uint64) activeArea.W ();
5842
5843 uint32 limit = Round_int32 ((real64) pixels * kClipFraction);
5844
5845 AutoPtr<dng_memory_block> histData (host.Allocate (65536 * sizeof (uint32)));
5846
5847 uint32 *hist = histData->Buffer_uint32 ();
5848
5849 for (uint32 plane = 0; plane < srcImage.Planes (); plane++)
5850 {
5851
5852 HistogramArea (host,
5853 srcImage,
5854 activeArea,
5855 hist,
5856 65535,
5857 plane);
5858
5859 uint32 total = 0;
5860
5861 uint32 upperIndex = 65535;
5862
5863 while (total + hist [upperIndex] <= limit && upperIndex > 255)
5864 {
5865
5866 total += hist [upperIndex];
5867
5868 upperIndex--;
5869
5870 }
5871
5872 total = 0;
5873
5874 uint32 lowerIndex = 0;
5875
5876 while (total + hist [lowerIndex] <= limit && lowerIndex < upperIndex - 255)
5877 {
5878
5879 total += hist [lowerIndex];
5880
5881 lowerIndex++;
5882
5883 }
5884
5885 lower [plane] = lowerIndex / 65535.0;
5886 upper [plane] = upperIndex / 65535.0;
5887
5888 }
5889
5890 }
5891
5892 AutoPtr<dng_base_proxy_curve> baseCurve;
5893
5894 if (use16bit)
5895 baseCurve.Reset (new dng_jxl_proxy_curve);
5896 else
5897 baseCurve.Reset (new dng_jpeg_proxy_curve);
5898
5899 for (uint32 n = 0; n < kMaxColorPlanes; n++)
5900 {
5901 dstBlackLevel [n] = 0.0;
5902 }
5903
5904 const uint32 whiteLevel = use16bit ? 65535 : 255;
5905
5906 const real64 whiteLevel64 = real64 (whiteLevel);
5907
5908 if (isSceneReferred && (srcBlackLevel > 0.0))
5909 {
5910
5911 for (uint32 plane = 0; plane < srcImage.Planes (); plane++)
5912 {
5913
5914 if (lower [plane] < srcBlackLevel)
5915 {
5916
5917 upper [plane] = Max_real64 (upper [plane],
5918 srcBlackLevel +
5919 (srcBlackLevel - lower [plane]) *
5920 (1.0 / kMaxStage3BlackLevelNormalized - 1.0));
5921
5922 upper [plane] = Min_real64 (upper [plane], 1.0);
5923
5924 real64 negRange =
5925 baseCurve->EvaluateScene ((srcBlackLevel - lower [plane]) /
5926 (upper [plane] - srcBlackLevel));
5927
5928 real64 outBlack = negRange / (1.0 + negRange);
5929
5930 dstBlackLevel [plane] = Min_real64 (kMaxStage3BlackLevelNormalized * whiteLevel64,
5931 ceil (outBlack * whiteLevel64));
5932
5933 }
5934
5935 }
5936
5937 }
5938
5939 // Apply the gamma encoding, using dither when downsampling to 8-bit.
5940
5941 AutoPtr<dng_image> dstImage (host.Make_dng_image (srcImage.Bounds (),
5942 srcImage.Planes (),
5943 use16bit ? ttShort : ttByte));
5944
5945 {
5946
5947 DNG_REQUIRE (baseCurve.Get (),
5948 "missing base curve");
5949
5950 dng_encode_proxy_task task (host,
5951 srcImage,
5952 *dstImage,
5953 lower,
5954 upper,
5955 isSceneReferred,
5956 srcBlackLevel,
5957 dstBlackLevel,
5958 whiteLevel64,
5959 *baseCurve);
5960
5961 host.PerformAreaTask (task,
5962 srcImage.Bounds ());
5963
5964 }
5965
5966 // Add opcodes to undo the gamma encoding.
5967
5968 {
5969
5970 for (uint32 plane = 0; plane < srcImage.Planes (); plane++)
5971 {
5972
5973 dng_area_spec areaSpec (dng_rect (activeArea.Size ()),
5974 plane);
5975
5976 real64 coefficient [4];
5977
5978 coefficient [0] = 0.0;
5979
5980 if (isSceneReferred)
5981 {
5982 coefficient [1] = baseCurve->SceneSlope ();
5983 coefficient [2] = 0.0;
5984 coefficient [3] = 1.0 - coefficient [1];
5985 }
5986 else
5987 {
5988 coefficient [1] = baseCurve->OutputSlope ();
5989 coefficient [2] = 1.0 - coefficient [1];
5990 coefficient [3] = 0.0;
5991 }
5992
5993 if (lower [plane] < srcBlackLevel)
5994 {
5995
5996 real64 rescale = (upper [plane] - srcBlackLevel) / (1.0 - srcBlackLevel);
5997
5998 coefficient [0] *= rescale;
5999 coefficient [1] *= rescale;
6000 coefficient [2] *= rescale;
6001 coefficient [3] *= rescale;
6002
6003 }
6004
6005 else
6006 {
6007
6008 real64 rescale = (upper [plane] - lower [plane]) / (1.0 - srcBlackLevel);
6009
6010 coefficient [0] *= rescale;
6011 coefficient [1] *= rescale;
6012 coefficient [2] *= rescale;
6013 coefficient [3] *= rescale;
6014
6015 coefficient [0] += (lower [plane] - srcBlackLevel) / (1.0 - srcBlackLevel);
6016
6017 }
6018
6019 AutoPtr<dng_opcode> opcode (new dng_opcode_MapPolynomial (areaSpec,
6020 isSceneReferred ? 3 : 2,
6021 coefficient));
6022
6023 opcodeList.Append (opcode);
6024
6025 }
6026
6027 }
6028
6029 return dstImage.Release ();
6030
6031 }
6032
6033 /*****************************************************************************/
6034
6035 bool dng_negative::NeedLossyCompressMosaicJXL (dng_host &host) const
6036 {
6037
6038 if (!host.LossyMosaicJXL ())
6039 {
6040 return false;
6041 }
6042
6043 if (host.SaveDNGVersion () < dngVersion_1_7_1_0)
6044 {
6045 return false;
6046 }
6047
6048 if (!GetMosaicInfo () ||
6049 !GetMosaicInfo ()->IsColorFilterArray () ||
6050 GetMosaicInfo ()->fCFAPatternSize.h != 2 ||
6051 GetMosaicInfo ()->fCFAPatternSize.v != 2)
6052 {
6053 return false;
6054 }
6055
6056 if (RawLossyCompressedImage () &&
6057 RawLossyCompressedImage ()->fCompressionCode == ccJXL &&
6058 RawLossyCompressedImage ()->fJXLDistance != 0.0f)
6059 {
6060 return false;
6061 }
6062
6063 return true;
6064
6065 }
6066
6067 /*****************************************************************************/
6068
6069 class dng_lossy_mosaic_task : public dng_area_task
6070 , private dng_uncopyable
6071 {
6072
6073 public:
6074
6075 const dng_image &fSrcImage;
6076 dng_image &fDstImage;
6077
6078 dng_point fOffset;
6079
6080 private:
6081
6082 enum
6083 {
6084 kMaxThreads = 4
6085 };
6086
6087 AutoPtr<dng_memory_block> fBuffer [kMaxThreads];
6088
6089 public:
6090
6091 dng_lossy_mosaic_task (const dng_image &srcImage,
6092 dng_image &dstImage,
6093 const dng_point &offset)
6094
6095 : dng_area_task ("dng_lossy_mosaic_task")
6096
6097 , fSrcImage (srcImage)
6098 , fDstImage (dstImage)
6099 , fOffset (offset)
6100
6101 {
6102
6103 fMaxThreads = kMaxThreads;
6104
6105 fMaxTileSize = dng_point (512, 512);
6106
6107 }
6108
6109 dng_rect RepeatingTile1 () const override
6110 {
6111 return fDstImage.RepeatingTile ();
6112 }
6113
6114 void Start (uint32 threadCount,
6115 const dng_rect &dstArea,
6116 const dng_point &tileSize,
6117 dng_memory_allocator *allocator,
6118 dng_abort_sniffer *sniffer) override;
6119
6120 void Process (uint32 threadIndex,
6121 const dng_rect &tile,
6122 dng_abort_sniffer *sniffer) override;
6123
6124 };
6125
6126 /*****************************************************************************/
6127
6128 void dng_lossy_mosaic_task::Start (uint32 threadCount,
6129 const dng_rect & /* dstArea */,
6130 const dng_point &tileSize,
6131 dng_memory_allocator *allocator,
6132 dng_abort_sniffer * /* sniffer */)
6133 {
6134
6135 uint32 bufferSize = tileSize.h *
6136 tileSize.v *
6137 fDstImage.PixelSize ();
6138
6139 for (uint32 threadIndex = 0; threadIndex < threadCount; threadIndex++)
6140 {
6141
6142 fBuffer [threadIndex].Reset (allocator->Allocate (bufferSize));
6143
6144 }
6145
6146 }
6147
6148 /*****************************************************************************/
6149
6150 void dng_lossy_mosaic_task::Process (uint32 threadIndex,
6151 const dng_rect &tile,
6152 dng_abort_sniffer * /* sniffer */)
6153 {
6154
6155 dng_pixel_buffer dstBuffer;
6156
6157 dstBuffer.fArea = tile;
6158 dstBuffer.fPlane = 0;
6159 dstBuffer.fPlanes = 1;
6160 dstBuffer.fPlaneStep = 1;
6161 dstBuffer.fColStep = 1;
6162 dstBuffer.fRowStep = tile.W ();
6163 dstBuffer.fPixelType = fDstImage.PixelType ();
6164 dstBuffer.fPixelSize = fDstImage.PixelSize ();
6165 dstBuffer.fData = fBuffer [threadIndex]->Buffer ();
6166 dstBuffer.fDirty = true;
6167
6168 dng_pixel_buffer srcBuffer = dstBuffer;
6169
6170 srcBuffer.fArea = srcBuffer.fArea - fOffset;
6171
6172 fSrcImage.Get (srcBuffer,
6173 dng_image::edge_repeat,
6174 2,
6175 2);
6176
6177 fDstImage.Put (dstBuffer);
6178
6179 }
6180
6181 /*****************************************************************************/
6182
6183 void dng_negative::LossyCompressMosaicJXL (dng_host &host,
6184 dng_image_writer &writer)
6185 {
6186
6187 if (NeedLossyCompressMosaicJXL (host))
6188 {
6189
6190 if (RawImage ().PixelType () == ttShort &&
6191 RawImage ().Planes () == 1 &&
6192 RawImage ().Height () >= 2 &&
6193 RawImage ().Width () >= 2)
6194 {
6195
6196 // Figure out tile size and padding so tile seams don't cross
6197 // color fields.
6198
6199 dng_point oldSize = RawImage ().Size ();
6200
6201 dng_point fieldSize;
6202
6203 fieldSize.v = (oldSize.v + 1) / 2;
6204 fieldSize.h = (oldSize.h + 1) / 2;
6205
6206 dng_point tileSize;
6207
6208 {
6209
6210 dng_ifd tempIFD;
6211
6212 tempIFD.fSamplesPerPixel = 1;
6213
6214 tempIFD.fBitsPerSample [0] = 16;
6215
6216 tempIFD.fImageLength = fieldSize.v;
6217 tempIFD.fImageWidth = fieldSize.h;
6218
6219 tempIFD.FindTileSize (1024 * 1024);
6220
6221 tileSize.v = tempIFD.fTileLength;
6222 tileSize.h = tempIFD.fTileWidth;
6223
6224 }
6225
6226 fieldSize.v = ((fieldSize.v + tileSize.v - 1) / tileSize.v) * tileSize.v;
6227 fieldSize.h = ((fieldSize.h + tileSize.h - 1) / tileSize.h) * tileSize.h;
6228
6229 dng_point paddedSize;
6230
6231 paddedSize.v = fieldSize.v * 2;
6232 paddedSize.h = fieldSize.h * 2;
6233
6234 dng_point padOffset;
6235
6236 padOffset.v = (paddedSize.v - oldSize.v) / 2;
6237 padOffset.h = (paddedSize.h - oldSize.h) / 2;
6238
6239 dng_rect activeArea (padOffset.v,
6240 padOffset.h,
6241 padOffset.v + oldSize.v,
6242 padOffset.h + oldSize.h);
6243
6244 if (paddedSize != oldSize)
6245 {
6246
6247 AutoPtr<dng_image> paddedImage (host.Make_dng_image (dng_rect (paddedSize),
6248 1,
6249 ttShort));
6250
6251 {
6252
6253 dng_lossy_mosaic_task task (RawImage (),
6254 *paddedImage,
6255 padOffset);
6256
6257 host.PerformAreaTask (task, paddedImage->Bounds ());
6258
6259 }
6260
6261 // This padded image becomes the new raw image.
6262
6263 fRawImage.Reset (paddedImage.Release ());
6264
6265 // Adjust active area for padding.
6266
6267 SetActiveArea (activeArea);
6268
6269 // We just re-created the linearization info, so copy back
6270 // the raw black level so it gets written to output DNG.
6271
6272 SetBlackLevel (fRawImageBlackLevel);
6273
6274 }
6275
6276 // Range/curve encode image for better compression.
6277
6278 {
6279
6280 real64 dstBlackLevel [kMaxColorPlanes];
6281
6282 fRawImage.Reset (EncodeImageForCompression (host,
6283 RawImage (),
6284 activeArea,
6285 true, // isSceneReferred
6286 true, // use16Bit
6287 fRawImageBlackLevel * (1.0 / 65535.0),
6288 dstBlackLevel,
6289 fOpcodeList2));
6290
6291 SetBlackLevel (Round_int32 (dstBlackLevel [0]));
6292
6293 }
6294
6295 // Apply interleaving to a temporary image.
6296
6297 AutoPtr<dng_image> tempImage (host.Make_dng_image (RawImage ().Bounds (),
6298 RawImage ().Planes (),
6299 RawImage ().PixelType ()));
6300
6301 Interleave2D (host,
6302 RawImage (),
6303 *tempImage,
6304 2,
6305 2,
6306 true);
6307
6308 // Compress.
6309
6310 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6311
6312 {
6313
6314 dng_ifd tempIFD;
6315
6316 tempIFD.fNewSubFileType = sfMainImage;
6317
6318 tempIFD.fPhotometricInterpretation = piLinearRaw;
6319
6320 tempIFD.fCompression = ccJXL;
6321
6322 tempIFD.fSamplesPerPixel = 1;
6323
6324 tempIFD.fBitsPerSample [0] = 16;
6325
6326 tempIFD.fImageLength = paddedSize.v;
6327 tempIFD.fImageWidth = paddedSize.h;
6328
6329 tempIFD.fTileLength = tileSize.v;
6330 tempIFD.fTileWidth = tileSize.h;
6331
6332 tempIFD.fUsesTiles = true;
6333
6334 AutoPtr<dng_jxl_encode_settings> settings
6335 (host.MakeJXLEncodeSettings (dng_host::use_case_LossyMosaic,
6336 *tempImage,
6337 this));
6338
6339 tempIFD.fJXLEncodeSettings.reset (settings.Release ());
6340
6341 AutoPtr<JxlColorEncoding> encoding (new JxlColorEncoding);
6342
6343 memset (encoding.Get (), 0, sizeof (JxlColorEncoding));
6344
6345 // EncodeImageForCompression leaves the image far from linear gamma,
6346 // so let's pretend it is sRGB gamma.
6347
6348 encoding->color_space = JXL_COLOR_SPACE_GRAY;
6349 encoding->white_point = JXL_WHITE_POINT_D65; // unused
6350 encoding->primaries = JXL_PRIMARIES_2100; // unused
6351 encoding->transfer_function = JXL_TRANSFER_FUNCTION_SRGB;
6352
6353 tempIFD.fJXLColorEncoding.reset (encoding.Release ());
6354
6355 lossyImage->EncodeTiles (host,
6356 writer,
6357 *tempImage,
6358 tempIFD);
6359
6360 }
6361
6362 lossyImage->fRowInterleaveFactor = 2;
6363 lossyImage->fColumnInterleaveFactor = 2;
6364
6365 fRawLossyCompressedImage.Reset (lossyImage.Release ());
6366
6367 ClearRawLossyCompressedImageDigest ();
6368
6369 ClearRawImageDigest ();
6370
6371 }
6372
6373 }
6374
6375 }
6376
6377 /*****************************************************************************/
6378
6379 void dng_negative::CompressTransparencyMaskJXL (dng_host &host,
6380 dng_image_writer &writer,
6381 bool nearLosslessOK)
6382 {
6383
6384 if (host.SaveDNGVersion () != 0 &&
6385 host.SaveDNGVersion () < MinBackwardVersionForCompression (ccJXL))
6386 {
6387 return;
6388 }
6389
6390 if (!RawLossyCompressedTransparencyMask () &&
6391 RawTransparencyMask () != nullptr &&
6392 SupportsJXL (*RawTransparencyMask ()) &&
6393 (RawTransparencyMask ()->PixelType () != ttFloat || RawTransparencyMaskBitDepth () == 16))
6394 {
6395
6396 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6397
6398 lossyImage->Encode (host,
6399 writer,
6400 *RawTransparencyMask (),
6401 nearLosslessOK ? dng_host::use_case_Transparency
6402 : dng_host::use_case_LosslessTransparency,
6403 this);
6404
6405 fRawLossyCompressedTransparencyMask.Reset (lossyImage.Release ());
6406
6407 ClearRawImageDigest ();
6408
6409 }
6410
6411 }
6412
6413 /*****************************************************************************/
6414
6415 void dng_negative::CompressDepthMapJXL (dng_host &host,
6416 dng_image_writer &writer,
6417 bool nearLosslessOK)
6418 {
6419
6420 if (host.SaveDNGVersion () != 0 &&
6421 host.SaveDNGVersion () < MinBackwardVersionForCompression (ccJXL))
6422 {
6423 return;
6424 }
6425
6426 if (!RawLossyCompressedDepthMap () &&
6427 RawDepthMap () != nullptr &&
6428 SupportsJXL (*RawDepthMap ()) &&
6429 RawDepthMap ()->PixelType () != ttFloat)
6430 {
6431
6432 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6433
6434 lossyImage->Encode (host,
6435 writer,
6436 *RawDepthMap (),
6437 nearLosslessOK ? dng_host::use_case_Depth
6438 : dng_host::use_case_LosslessDepth,
6439 this);
6440
6441 fRawLossyCompressedDepthMap.Reset (lossyImage.Release ());
6442
6443 }
6444
6445 }
6446
6447 /*****************************************************************************/
6448
6449 void dng_negative::CompressSemanticMasksJXL (dng_host &host,
6450 dng_image_writer &writer,
6451 bool nearLosslessOK)
6452 {
6453
6454 if (host.SaveDNGVersion () != 0 &&
6455 host.SaveDNGVersion () < MinBackwardVersionForCompression (ccJXL))
6456 {
6457 return;
6458 }
6459
6460 // JXL compress semantic masks, if not already compressed.
6461
6462 const uint32 maskCount = NumSemanticMasks ();
6463
6464 for (uint32 i = 0; i < maskCount; i++)
6465 {
6466
6467 auto &mask = fSemanticMasks [i];
6468
6469 if (!mask.fLossyCompressed.get () &&
6470 SupportsJXL (*mask.fMask) &&
6471 (mask.fMask->PixelType () != ttFloat || nearLosslessOK))
6472 {
6473
6474 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6475
6476 lossyImage->Encode (host,
6477 writer,
6478 *mask.fMask,
6479 nearLosslessOK ? dng_host::use_case_SemanticMask
6480 : dng_host::use_case_LosslessSemanticMask,
6481 this);
6482
6483 mask.fLossyCompressed.reset (lossyImage.Release ());
6484
6485 }
6486
6487 }
6488
6489 }
6490
6491 /*****************************************************************************/
6492
6493 void dng_negative::LosslessCompressJXL (dng_host &host,
6494 dng_image_writer &writer,
6495 bool nearLosslessOK)
6496 {
6497
6498 if (host.SaveDNGVersion () != 0 &&
6499 host.SaveDNGVersion () < MinBackwardVersionForCompression (ccJXL))
6500 {
6501 return;
6502 }
6503
6504 // JXL compress main image, if not already compressed.
6505
6506 if (!RawLossyCompressedImage ())
6507 {
6508
6509 if (GetMosaicInfo () &&
6510 GetMosaicInfo ()->IsColorFilterArray ())
6511 {
6512
6513 if (host.SaveDNGVersion () >= dngVersion_1_7_1_0 &&
6514 GetMosaicInfo ()->fCFAPatternSize.h >= 2 &&
6515 GetMosaicInfo ()->fCFAPatternSize.h < (int32) RawImage ().Width () &&
6516 GetMosaicInfo ()->fCFAPatternSize.v >= 2 &&
6517 GetMosaicInfo ()->fCFAPatternSize.v < (int32) RawImage ().Height () &&
6518 RawImage ().Planes () == 1 &&
6519 RawImage ().PixelType () == ttShort)
6520 {
6521
6522 // First, apply interleaving to a temporary image.
6523
6524 AutoPtr<dng_image> tempImage (host.Make_dng_image (RawImage ().Bounds (),
6525 RawImage ().Planes (),
6526 RawImage ().PixelType ()));
6527
6528 Interleave2D (host,
6529 RawImage (),
6530 *tempImage,
6531 GetMosaicInfo ()->fCFAPatternSize.v,
6532 GetMosaicInfo ()->fCFAPatternSize.h,
6533 true);
6534
6535 // Compress.
6536
6537 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6538
6539 lossyImage->Encode (host,
6540 writer,
6541 *tempImage,
6542 dng_host::use_case_LosslessMosaic,
6543 this);
6544
6545 lossyImage->fRowInterleaveFactor = GetMosaicInfo ()->fCFAPatternSize.v;
6546 lossyImage->fColumnInterleaveFactor = GetMosaicInfo ()->fCFAPatternSize.h;
6547
6548 fRawLossyCompressedImage.Reset (lossyImage.Release ());
6549
6550 ClearRawLossyCompressedImageDigest ();
6551
6552 ClearRawImageDigest ();
6553
6554 }
6555
6556 }
6557
6558 else
6559 {
6560
6561 if (SupportsJXL (RawImage ()) &&
6562 (RawImage ().PixelType () != ttFloat || RawFloatBitDepth () == 16))
6563 {
6564
6565 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6566
6567 lossyImage->Encode (host,
6568 writer,
6569 RawImage (),
6570 nearLosslessOK ? dng_host::use_case_MainImage
6571 : dng_host::use_case_LosslessMainImage,
6572 this);
6573
6574 fRawLossyCompressedImage.Reset (lossyImage.Release ());
6575
6576 ClearRawLossyCompressedImageDigest ();
6577
6578 ClearRawImageDigest ();
6579
6580 }
6581
6582 }
6583
6584 }
6585
6586 // JXL compress enhanced image, if not already compressed.
6587
6588 if (!EnhancedLossyCompressedImage () &&
6589 EnhanceParams ().NotEmpty () &&
6590 &RawImage () != Stage3Image () &&
6591 SupportsJXL (*Stage3Image ()) &&
6592 (Stage3Image ()->PixelType () == ttShort || nearLosslessOK))
6593 {
6594
6595 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
6596
6597 lossyImage->Encode (host,
6598 writer,
6599 *RawTransparencyMask (),
6600 nearLosslessOK ? dng_host::use_case_EnhancedImage
6601 : dng_host::use_case_LosslessEnhancedImage,
6602 this);
6603
6604 fEnhancedLossyCompressedImage.Reset (lossyImage.Release ());
6605
6606 }
6607
6608 // JXL compress transparency mask, if not already compressed.
6609
6610 CompressTransparencyMaskJXL (host,
6611 writer,
6612 nearLosslessOK);
6613
6614 // JXL compress depth map, if not already compressed.
6615
6616 CompressDepthMapJXL (host,
6617 writer,
6618 nearLosslessOK);
6619
6620 // JXL compress semantic masks, if not already compressed.
6621
6622 CompressSemanticMasksJXL (host,
6623 writer,
6624 nearLosslessOK);
6625
6626 }
6627
6628 /******************************************************************************/
6629
6630 dng_image * dng_negative::EncodeRawProxy (dng_host &host,
6631 const dng_image &srcImage,
6632 dng_opcode_list &opcodeList,
6633 real64 *blackLevel) const
6634 {
6635
6636 bool use16bit = SupportsJXL (srcImage) &&
6637 (!host.SaveDNGVersion () ||
6638 host.SaveDNGVersion () >= MinBackwardVersionForCompression (ccJXL));
6639
6640 return EncodeImageForCompression (host,
6641 srcImage,
6642 srcImage.Bounds (),
6643 IsSceneReferred (),
6644 use16bit,
6645 Stage3BlackLevelNormalized (),
6646 blackLevel,
6647 opcodeList);
6648
6649 }
6650
6651 /******************************************************************************/
6652
6653 void dng_negative::AdjustGainMapForStage3 (dng_host & /* host */)
6654 {
6655
6656 // For dng_sdk, the stage3 image's color space is always the same as the
6657 // raw image's color space, so any gain map does not need adjusting.
6658
6659 }
6660
6661 /******************************************************************************/
6662
6663 void dng_negative::AdjustProfileForStage3 ()
6664 {
6665
6666 // For dng_sdk, the stage3 image's color space is always the same as the
6667 // raw image's color space.
6668
6669 }
6670
6671 /******************************************************************************/
6672
6673 void dng_negative::ConvertToProxy (dng_host &host,
6674 dng_image_writer &writer,
6675 uint32 proxySize,
6676 uint64 proxyCount)
6677 {
6678
6679 if (!proxySize)
6680 {
6681 proxySize = kMaxImageSide;
6682 }
6683
6684 if (!proxyCount)
6685 {
6686 proxyCount = (uint64) proxySize *
6687 (uint64) proxySize;
6688 }
6689
6690 // Is this a (possibly) downsampled proxy?
6691
6692 bool nonFullSizeProxy = (proxySize < kMaxImageSide) ||
6693 (proxyCount < (uint64) kMaxImageSide *
6694 (uint64) kMaxImageSide);
6695
6696 // Don't need to keep private data around in non-full size proxies.
6697
6698 if (nonFullSizeProxy)
6699 {
6700
6701 ClearMakerNote ();
6702
6703 ClearPrivateData ();
6704
6705 }
6706
6707 // When converting Enhanced images to proxy, make sure to set the
6708 // OriginalDefault... fields to reflect the Enhanced image size, not the
6709 // standard resolution size.
6710
6711 if (RawDefaultCropSizeH ().As_real64 () < DefaultCropSizeH ().As_real64 () &&
6712 RawDefaultCropSizeV ().As_real64 () < DefaultCropSizeV ().As_real64 ())
6713 {
6714
6715 // Clear any existing values.
6716
6717 SetOriginalDefaultFinalSize (dng_point ());
6718
6719 SetOriginalBestQualityFinalSize (dng_point ());
6720
6721 SetOriginalDefaultCropSize (dng_urational (),
6722 dng_urational ());
6723
6724 // Set the values from scratch.
6725
6726 SetDefaultOriginalSizes ();
6727
6728 }
6729
6730 const bool useJXL = (ColorChannels () == 1 ||
6731 ColorChannels () == 3) &&
6732 (!host.SaveDNGVersion () ||
6733 host.SaveDNGVersion () >= MinBackwardVersionForCompression (ccJXL));
6734
6735 // See if we already have an acceptable proxy raw image.
6736
6737 bool rawImageOK = false;
6738
6739 real64 pixelAspect = PixelAspectRatio ();
6740
6741 bool nonSquarePixels = pixelAspect < 0.99 ||
6742 pixelAspect > 1.01;
6743
6744 if (fRawImage.Get () &&
6745 fRawImage->Bounds () == DefaultCropArea () &&
6746 fRawImage->Bounds ().H () <= proxySize &&
6747 fRawImage->Bounds ().W () <= proxySize &&
6748 (uint64) fRawImage->Bounds ().H () *
6749 (uint64) fRawImage->Bounds ().W () <= proxyCount &&
6750 fRawToFullScaleH == 1.0 &&
6751 fRawToFullScaleV == 1.0 &&
6752 !nonSquarePixels &&
6753 fEnhanceParams.IsEmpty () &&
6754 (!GetMosaicInfo () || !GetMosaicInfo ()->IsColorFilterArray ()))
6755 {
6756
6757 if (fRawImage->PixelType () == ttByte)
6758 {
6759
6760 rawImageOK = fRawLossyCompressedImage.Get () != nullptr;
6761
6762 }
6763
6764 else if (fRawImage->PixelType () == ttShort)
6765 {
6766
6767 rawImageOK = fRawLossyCompressedImage.Get () != nullptr;
6768
6769 }
6770
6771 else if (fRawImage->PixelType () == ttFloat)
6772 {
6773
6774 if (RawFloatBitDepth () == 16)
6775 {
6776
6777 if (useJXL)
6778 {
6779 rawImageOK = fRawLossyCompressedImage.Get () != nullptr;
6780 }
6781
6782 else
6783 {
6784 rawImageOK = true;
6785 }
6786
6787 }
6788
6789 }
6790
6791 }
6792
6793 // Even if we already used lossy JPEG to encode the raw image, we should
6794 // still recompress the data as JXL if allowed for the size savings.
6795
6796 if (rawImageOK &&
6797 useJXL &&
6798 fRawLossyCompressedImage.Get () &&
6799 fRawLossyCompressedImage->fCompressionCode != ccJXL)
6800 {
6801
6802 rawImageOK = false;
6803
6804 }
6805
6806 // If the raw lossy compressed image is known to be lossless JXL, then
6807 // we should not use it for a lossy proxy.
6808
6809 if (RawLossyCompressedImage () &&
6810 RawLossyCompressedImage ()->fCompressionCode == ccJXL &&
6811 RawLossyCompressedImage ()->fJXLDistance == 0.0f)
6812 {
6813
6814 rawImageOK = false;
6815
6816 }
6817
6818 if (!rawImageOK)
6819 {
6820
6821 // Adjust for any color matrix difference between the
6822 // raw image and the stage3 image.
6823
6824 AdjustGainMapForStage3 (host);
6825
6826 AdjustProfileForStage3 ();
6827
6828 // Clear any grabbed raw image, since we are going to start
6829 // building the proxy with the stage3 image.
6830
6831 fRawImage.Reset ();
6832
6833 fRawDefaultScaleH.Clear ();
6834 fRawDefaultScaleV.Clear ();
6835
6836 fRawBestQualityScale.Clear ();
6837
6838 fRawDefaultCropSizeH.Clear ();
6839 fRawDefaultCropSizeV.Clear ();
6840
6841 fRawDefaultCropOriginH.Clear ();
6842 fRawDefaultCropOriginV.Clear ();
6843
6844 fRawImageBlackLevel = 0;
6845
6846 ClearRawLossyCompressedImage ();
6847
6848 SetRawFloatBitDepth (0);
6849
6850 ClearLinearizationInfo ();
6851
6852 ClearMosaicInfo ();
6853
6854 fOpcodeList1.Clear ();
6855 fOpcodeList2.Clear ();
6856 fOpcodeList3.Clear ();
6857
6858 ClearRawImageDigest ();
6859
6860 ClearRawLossyCompressedImageDigest ();
6861
6862 // Discard the enhanced information since discarded
6863 // its source.
6864
6865 fEnhanceParams.Clear ();
6866
6867 fEnhancedLossyCompressedImage.Reset ();
6868
6869 }
6870
6871 // Trim off extra pixels outside the default crop area.
6872
6873 const dng_rect defaultCropArea = DefaultCropArea ();
6874
6875 const dng_rect originalStage3Bounds = Stage3Image ()->Bounds ();
6876
6877 if (!rawImageOK)
6878 {
6879
6880 if (originalStage3Bounds != defaultCropArea)
6881 {
6882
6883 const dng_rect s3bounds = originalStage3Bounds;
6884
6885 fStage3Image->Trim (defaultCropArea);
6886
6887 if (fTransparencyMask.Get ())
6888 {
6889 fTransparencyMask->Trim (defaultCropArea);
6890 fRawTransparencyMask.Reset ();
6891 fRawLossyCompressedTransparencyMask.Reset ();
6892 }
6893
6894 if (fDepthMap.Get ())
6895 {
6896 fDepthMap->Trim (defaultCropArea);
6897 fRawDepthMap.Reset ();
6898 fRawLossyCompressedDepthMap.Reset ();
6899 }
6900
6901 // Adjust origin and spacing of profile gain table map.
6902
6903 if (HasProfileGainTableMap ())
6904 {
6905
6906 const auto &gainTableMap = ProfileGainTableMap ();
6907
6908 // Adjust origin.
6909
6910 const dng_point_real64 &oldOrigin = gainTableMap.Origin ();
6911
6912 dng_point_real64 originPix
6913 (Lerp_real64 (s3bounds.t, s3bounds.b, oldOrigin.v),
6914 Lerp_real64 (s3bounds.l, s3bounds.r, oldOrigin.h));
6915
6916 dng_point_real64 newOrigin
6917 ((originPix.v - defaultCropArea.t) / defaultCropArea.H (),
6918 (originPix.h - defaultCropArea.l) / defaultCropArea.W ());
6919
6920 // Adjust spacing.
6921
6922 const dng_point_real64 &oldSpacing = gainTableMap.Spacing ();
6923
6924 dng_point_real64 newSpacing = oldSpacing;
6925
6926 const dng_point &points = gainTableMap.Points ();
6927
6928 if (points.h > 1)
6929 {
6930
6931 newSpacing.h *= ((real64) s3bounds.W () /
6932 (real64) defaultCropArea.W ());
6933
6934 }
6935
6936 if (points.v > 1)
6937 {
6938
6939 newSpacing.v *= ((real64) s3bounds.H () /
6940 (real64) defaultCropArea.H ());
6941
6942 }
6943
6944 // Deal with original buffer.
6945
6946 // We want to convert the gain map to 8-bit to save sapce.
6947
6948 AutoPtr<dng_memory_block> originalBuffer;
6949
6950 real32 gainMin = gainTableMap.GainMin ();
6951 real32 gainMax = gainTableMap.GainMax ();
6952
6953 // If original buffer is present and already 8-bit, then no change
6954 // is needed. Just make a copy to hand off to the new gain table
6955 // map.
6956
6957 if (gainTableMap.IsUint8 () &&
6958 gainTableMap.HasOriginalBuffer ())
6959 {
6960
6961 originalBuffer.Reset
6962 (gainTableMap.OriginalBuffer ()->Clone (host.Allocator ()));
6963
6964 }
6965
6966 // Otherwise, we need to convert to 8-bit. Scan the fp32 values
6967 // for the min & max gains.
6968
6969 else
6970 {
6971
6972 const real32 *ptr = gainTableMap.Block ()->Buffer_real32 ();
6973
6974 uint32 entries = (gainTableMap.DataStorageBytes () /
6975 gainTableMap.BytesPerEntry ());
6976
6977 for (uint32 i = 0; i < entries; i++)
6978 {
6979 gainMin = Min_real32 (gainMin, ptr [i]);
6980 gainMax = Max_real32 (gainMax, ptr [i]);
6981 }
6982
6983 }
6984
6985 // Make the new gain table map.
6986
6987 AutoPtr<dng_gain_table_map> newMap
6988 (new dng_gain_table_map (host.Allocator (),
6989 gainTableMap.Points (),
6990 newSpacing,
6991 newOrigin,
6992 gainTableMap.NumTablePoints (),
6993 gainTableMap.MapInputWeights (),
6994 0, // store as uint8
6995 gainTableMap.Gamma (),
6996 gainMin,
6997 gainMax));
6998
6999 // Copy over fp32 points.
7000
7001 memcpy (newMap ->Block ()->Buffer_real32 (),
7002 gainTableMap.Block ()->Buffer_real32 (),
7003 (size_t) gainTableMap.SampleBytes ());
7004
7005 // Copy over original buffer, if any.
7006
7007 if (originalBuffer.Get ())
7008 newMap->SetOriginalBuffer (originalBuffer);
7009
7010 // Replace the existing map.
7011
7012 SetProfileGainTableMap (newMap);
7013
7014 }
7015
7016 fDefaultCropOriginH = dng_urational (0, 1);
7017 fDefaultCropOriginV = dng_urational (0, 1);
7018
7019 }
7020
7021 // Figure out the requested proxy pixel size.
7022
7023 real64 aspectRatio = AspectRatio ();
7024
7025 dng_point newSize (proxySize, proxySize);
7026
7027 if (aspectRatio >= 1.0)
7028 {
7029 newSize.v = Max_int32 (1, Round_int32 (proxySize / aspectRatio));
7030 }
7031 else
7032 {
7033 newSize.h = Max_int32 (1, Round_int32 (proxySize * aspectRatio));
7034 }
7035
7036 newSize.v = Min_int32 (newSize.v, DefaultFinalHeight ());
7037 newSize.h = Min_int32 (newSize.h, DefaultFinalWidth ());
7038
7039 if ((uint64) newSize.v *
7040 (uint64) newSize.h > proxyCount)
7041 {
7042
7043 if (aspectRatio >= 1.0)
7044 {
7045
7046 newSize.h = (uint32) sqrt (proxyCount * aspectRatio);
7047
7048 newSize.v = Max_int32 (1, Round_int32 (newSize.h / aspectRatio));
7049
7050 }
7051
7052 else
7053 {
7054
7055 newSize.v = (uint32) sqrt (proxyCount / aspectRatio);
7056
7057 newSize.h = Max_int32 (1, Round_int32 (newSize.v * aspectRatio));
7058
7059 }
7060
7061 }
7062
7063 // If this is fewer pixels, downsample the stage 3 image to that size.
7064
7065 dng_point oldSize = defaultCropArea.Size ();
7066
7067 if ((uint64) newSize.v * (uint64) newSize.h <
7068 (uint64) oldSize.v * (uint64) oldSize.h || nonSquarePixels)
7069 {
7070
7071 const dng_image &srcImage (*Stage3Image ());
7072
7073 AutoPtr<dng_image> dstImage (host.Make_dng_image (newSize,
7074 srcImage.Planes (),
7075 srcImage.PixelType ()));
7076
7077 host.ResampleImage (srcImage,
7078 *dstImage);
7079
7080 fStage3Image.Reset (dstImage.Release ());
7081
7082 fDefaultCropSizeH = dng_urational (newSize.h, 1);
7083 fDefaultCropSizeV = dng_urational (newSize.v, 1);
7084
7085 fDefaultScaleH = dng_urational (1, 1);
7086 fDefaultScaleV = dng_urational (1, 1);
7087
7088 fBestQualityScale = dng_urational (1, 1);
7089
7090 fRawToFullScaleH = 1.0;
7091 fRawToFullScaleV = 1.0;
7092
7093 }
7094
7095 // If there is still a raw to full scale factor, we need to
7096 // remove it and adjust the crop coordinates.
7097
7098 else if (fRawToFullScaleH != 1.0 ||
7099 fRawToFullScaleV != 1.0)
7100 {
7101
7102 fDefaultCropSizeH = dng_urational (oldSize.h, 1);
7103 fDefaultCropSizeV = dng_urational (oldSize.v, 1);
7104
7105 fDefaultScaleH = dng_urational (1, 1);
7106 fDefaultScaleV = dng_urational (1, 1);
7107
7108 fBestQualityScale = dng_urational (1, 1);
7109
7110 fRawToFullScaleH = 1.0;
7111 fRawToFullScaleV = 1.0;
7112
7113 }
7114
7115 // Convert 32-bit floating point images to 16-bit floating point to
7116 // save space.
7117
7118 if (RawImage ().PixelType () == ttFloat &&
7119 RawFloatBitDepth () != 16)
7120 {
7121
7122 fRawImage.Reset (host.Make_dng_image (Stage3Image ()->Bounds (),
7123 Stage3Image ()->Planes (),
7124 ttFloat));
7125
7126 fRawImageBlackLevel = 0;
7127
7128 LimitFloatBitDepth (host,
7129 *Stage3Image (),
7130 *fRawImage,
7131 16,
7132 32768.0f);
7133
7134 SetRawFloatBitDepth (16);
7135
7136 SetWhiteLevel (32768);
7137
7138 }
7139
7140 // Lossy compress raw image if required.
7141
7142 if (!fRawLossyCompressedImage.Get ())
7143 {
7144
7145 if (useJXL)
7146 {
7147
7148 if (RawImage ().PixelType () == ttFloat)
7149 {
7150
7151 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
7152
7153 lossyImage->Encode (host,
7154 writer,
7155 RawImage (),
7156 nonFullSizeProxy ? dng_host::use_case_ProxyImage
7157 : dng_host::use_case_EncodedMainImage,
7158 this);
7159
7160 fRawLossyCompressedImage.Reset (lossyImage.Release ());
7161
7162 }
7163
7164 else
7165 {
7166
7167 real64 blackLevel [kMaxColorPlanes];
7168
7169 fRawImage.Reset (EncodeRawProxy (host,
7170 *Stage3Image (),
7171 fOpcodeList2,
7172 blackLevel));
7173
7174 fRawImageBlackLevel = 0;
7175
7176 if (fRawImage.Get ())
7177 {
7178
7179 for (uint32 plane = 0; plane < fRawImage->Planes (); plane++)
7180 {
7181 SetBlackLevel (blackLevel [plane], plane);
7182 }
7183
7184 }
7185
7186 AutoPtr<dng_jxl_image> lossyImage (new dng_jxl_image);
7187
7188 lossyImage->Encode (host,
7189 writer,
7190 RawImage (),
7191 nonFullSizeProxy ? dng_host::use_case_ProxyImage
7192 : dng_host::use_case_EncodedMainImage,
7193 this);
7194
7195 fRawLossyCompressedImage.Reset (lossyImage.Release ());
7196
7197 }
7198
7199 }
7200
7201 else
7202 {
7203
7204 if (RawImage ().PixelType () == ttShort)
7205 {
7206
7207 real64 blackLevel [kMaxColorPlanes];
7208
7209 fRawImage.Reset (EncodeRawProxy (host,
7210 *Stage3Image (),
7211 fOpcodeList2,
7212 blackLevel));
7213
7214 fRawImageBlackLevel = 0;
7215
7216 if (fRawImage.Get ())
7217 {
7218
7219 SetWhiteLevel (255);
7220
7221 for (uint32 plane = 0; plane < fRawImage->Planes (); plane++)
7222 {
7223 SetBlackLevel (blackLevel [plane], plane);
7224 }
7225
7226 }
7227
7228 }
7229
7230 // Compute JPEG compressed version.
7231
7232 if (RawImage ().PixelType () == ttByte)
7233 {
7234
7235 AutoPtr<dng_jpeg_image> jpegImage (new dng_jpeg_image);
7236
7237 jpegImage->Encode (host,
7238 *this,
7239 writer,
7240 RawImage ());
7241
7242 fRawLossyCompressedImage.Reset (jpegImage.Release ());
7243
7244 }
7245
7246 }
7247
7248 }
7249
7250 }
7251
7252 // Deal with transparency mask.
7253
7254 if (TransparencyMask ())
7255 {
7256
7257 const bool convertTo8Bit = true;
7258
7259 ResizeTransparencyToMatchStage3 (host, convertTo8Bit);
7260
7261 if (fRawTransparencyMask.Get ())
7262 {
7263
7264 if (fRawTransparencyMask->Bounds () != TransparencyMask ()->Bounds () ||
7265 fRawTransparencyMask->PixelType () != ttByte)
7266 {
7267 fRawTransparencyMask.Reset (fTransparencyMask->Clone ());
7268 fRawLossyCompressedTransparencyMask.Reset ();
7269 }
7270
7271 }
7272
7273 CompressTransparencyMaskJXL (host,
7274 writer,
7275 true);
7276
7277 }
7278
7279 // Deal with depth map.
7280
7281 if (DepthMap ())
7282 {
7283
7284 ResizeDepthToMatchStage3 (host);
7285
7286 if (fRawDepthMap.Get ())
7287 {
7288
7289 if (fRawDepthMap->Bounds ().W () > fDepthMap->Bounds ().W () ||
7290 fRawDepthMap->Bounds ().H () > fDepthMap->Bounds ().H ())
7291 {
7292 fRawDepthMap.Reset ();
7293 fRawLossyCompressedDepthMap.Reset ();
7294 }
7295
7296 }
7297
7298 CompressDepthMapJXL (host,
7299 writer,
7300 true);
7301
7302 }
7303
7304 // Deal with semantic masks.
7305
7306 AdjustSemanticMasksForProxy (host,
7307 writer,
7308 originalStage3Bounds,
7309 defaultCropArea);
7310
7311 // Recompute the raw data unique ID, since we changed the image data.
7312
7313 RecomputeRawDataUniqueID (host);
7314
7315 }
7316
7317 /*****************************************************************************/
7318
7319 bool dng_negative::IsProxy () const
7320 {
7321
7322 return (DefaultCropSizeH () != OriginalDefaultCropSizeH ()) &&
7323 (DefaultCropSizeV () != OriginalDefaultCropSizeV ());
7324
7325 }
7326
7327 /*****************************************************************************/
7328
7329 dng_linearization_info * dng_negative::MakeLinearizationInfo ()
7330 {
7331
7332 dng_linearization_info *info = new dng_linearization_info ();
7333
7334 if (!info)
7335 {
7336 ThrowMemoryFull ();
7337 }
7338
7339 return info;
7340
7341 }
7342
7343 /*****************************************************************************/
7344
7345 void dng_negative::NeedLinearizationInfo ()
7346 {
7347
7348 if (!fLinearizationInfo.Get ())
7349 {
7350
7351 fLinearizationInfo.Reset (MakeLinearizationInfo ());
7352
7353 }
7354
7355 }
7356
7357 /*****************************************************************************/
7358
7359 dng_mosaic_info * dng_negative::MakeMosaicInfo ()
7360 {
7361
7362 dng_mosaic_info *info = new dng_mosaic_info ();
7363
7364 if (!info)
7365 {
7366 ThrowMemoryFull ();
7367 }
7368
7369 return info;
7370
7371 }
7372
7373 /*****************************************************************************/
7374
7375 void dng_negative::NeedMosaicInfo ()
7376 {
7377
7378 if (!fMosaicInfo.Get ())
7379 {
7380
7381 fMosaicInfo.Reset (MakeMosaicInfo ());
7382
7383 }
7384
7385 }
7386
7387 /*****************************************************************************/
7388
7389 void dng_negative::SetTransparencyMask (AutoPtr<dng_image> &image,
7390 uint32 bitDepth)
7391 {
7392
7393 fTransparencyMask.Reset (image.Release ());
7394
7395 fRawTransparencyMaskBitDepth = bitDepth;
7396
7397 }
7398
7399 /*****************************************************************************/
7400
7401 void dng_negative::ClearTransparencyMask ()
7402 {
7403
7404 fTransparencyMask.Reset ();
7405
7406 fRawTransparencyMask.Reset ();
7407
7408 fRawTransparencyMaskBitDepth = 0;
7409
7410 }
7411
7412 /*****************************************************************************/
7413
7414 const dng_image * dng_negative::TransparencyMask () const
7415 {
7416
7417 return fTransparencyMask.Get ();
7418
7419 }
7420
7421 /*****************************************************************************/
7422
7423 const dng_image * dng_negative::RawTransparencyMask () const
7424 {
7425
7426 if (fRawTransparencyMask.Get ())
7427 {
7428
7429 return fRawTransparencyMask.Get ();
7430
7431 }
7432
7433 return TransparencyMask ();
7434
7435 }
7436
7437 /*****************************************************************************/
7438
7439 uint32 dng_negative::RawTransparencyMaskBitDepth () const
7440 {
7441
7442 if (fRawTransparencyMaskBitDepth)
7443 {
7444
7445 return fRawTransparencyMaskBitDepth;
7446
7447 }
7448
7449 const dng_image *mask = RawTransparencyMask ();
7450
7451 if (mask)
7452 {
7453
7454 switch (mask->PixelType ())
7455 {
7456
7457 case ttByte:
7458 return 8;
7459
7460 case ttShort:
7461 return 16;
7462
7463 case ttFloat:
7464 return 32;
7465
7466 default:
7467 ThrowProgramError ();
7468
7469 }
7470
7471 }
7472
7473 return 0;
7474
7475 }
7476
7477 /*****************************************************************************/
7478
7479 void dng_negative::ReadTransparencyMask (dng_host &host,
7480 dng_stream &stream,
7481 dng_info &info)
7482 {
7483
7484 if (info.fMaskIndex != -1)
7485 {
7486
7487 // Allocate image we are reading.
7488
7489 dng_ifd &maskIFD = *info.fIFD [info.fMaskIndex];
7490
7491 fTransparencyMask.Reset (host.Make_dng_image (maskIFD.Bounds (),
7492 1,
7493 maskIFD.PixelType ()));
7494
7495 // Do we need to keep the lossy compressed data?
7496
7497 fRawLossyCompressedTransparencyMask.Reset (KeepLossyCompressedImage (host,
7498 maskIFD));
7499
7500 // Read the image.
7501
7502 maskIFD.ReadImage (host,
7503 stream,
7504 *fTransparencyMask.Get (),
7505 fRawLossyCompressedTransparencyMask.Get ());
7506
7507 // Remember the pixel depth.
7508
7509 fRawTransparencyMaskBitDepth = maskIFD.fBitsPerSample [0];
7510
7511 // Remember if transparency mask was lossy compressed.
7512
7513 fTransparencyMaskWasLossyCompressed = (maskIFD.fCompression == ccLossyJPEG ||
7514 maskIFD.fCompression == ccJXL);
7515
7516 }
7517
7518 }
7519
7520 /*****************************************************************************/
7521
7522 void dng_negative::ResizeTransparencyToMatchStage3 (dng_host &host,
7523 bool convertTo8Bit)
7524 {
7525
7526 if (TransparencyMask ())
7527 {
7528
7529 if ((TransparencyMask ()->Bounds () != fStage3Image->Bounds ()) ||
7530 (TransparencyMask ()->PixelType () != ttByte && convertTo8Bit))
7531 {
7532
7533 AutoPtr<dng_image> newMask (host.Make_dng_image (fStage3Image->Bounds (),
7534 1,
7535 convertTo8Bit ?
7536 ttByte :
7537 TransparencyMask ()->PixelType ()));
7538
7539 host.ResampleImage (*TransparencyMask (),
7540 *newMask);
7541
7542 fTransparencyMask.Reset (newMask.Release ());
7543
7544 if (!fRawTransparencyMask.Get ())
7545 {
7546 fRawTransparencyMaskBitDepth = 0;
7547 }
7548
7549 else if (convertTo8Bit)
7550 {
7551 fRawTransparencyMaskBitDepth = 8;
7552 }
7553
7554 }
7555
7556 }
7557
7558 }
7559
7560 /*****************************************************************************/
7561
7562 bool dng_negative::NeedFlattenTransparency (dng_host & /* host */)
7563 {
7564
7565 return false;
7566
7567 }
7568
7569 /*****************************************************************************/
7570
7571 void dng_negative::FlattenTransparency (dng_host & /* host */)
7572 {
7573
7574 ThrowNotYetImplemented ("FlattenTransparency");
7575
7576 }
7577
7578 /*****************************************************************************/
7579
7580 const dng_image * dng_negative::UnflattenedStage3Image () const
7581 {
7582
7583 if (fUnflattenedStage3Image.Get ())
7584 {
7585
7586 return fUnflattenedStage3Image.Get ();
7587
7588 }
7589
7590 return fStage3Image.Get ();
7591
7592 }
7593
7594 /*****************************************************************************/
7595
7596 void dng_negative::SetDepthMap (AutoPtr<dng_image> &depthMap)
7597 {
7598
7599 fDepthMap.Reset (depthMap.Release ());
7600
7601 SetHasDepthMap (fDepthMap.Get () != NULL);
7602
7603 }
7604
7605 /*****************************************************************************/
7606
7607 void dng_negative::ReadDepthMap (dng_host &host,
7608 dng_stream &stream,
7609 dng_info &info)
7610 {
7611
7612 if (info.fDepthIndex != -1)
7613 {
7614
7615 // Allocate image we are reading.
7616
7617 dng_ifd &depthIFD = *info.fIFD [info.fDepthIndex];
7618
7619 fDepthMap.Reset (host.Make_dng_image (depthIFD.Bounds (),
7620 1,
7621 depthIFD.PixelType ()));
7622
7623 // Keep lossy compressed depth image?
7624
7625 fRawLossyCompressedDepthMap.Reset (KeepLossyCompressedImage (host,
7626 depthIFD));
7627
7628 // Read the image.
7629
7630 depthIFD.ReadImage (host,
7631 stream,
7632 *fDepthMap.Get (),
7633 fRawLossyCompressedDepthMap.Get ());
7634
7635 SetHasDepthMap (fDepthMap.Get () != NULL);
7636
7637 }
7638
7639 }
7640
7641 /*****************************************************************************/
7642
7643 void dng_negative::ResizeDepthToMatchStage3 (dng_host &host)
7644 {
7645
7646 if (DepthMap ())
7647 {
7648
7649 if (DepthMap ()->Bounds () != fStage3Image->Bounds ())
7650 {
7651
7652 // If we are upsampling, and have not grabbed the raw depth map
7653 // yet, do so now.
7654
7655 if (!fRawDepthMap.Get ())
7656 {
7657
7658 uint64 imagePixels = fStage3Image->Bounds ().H () * (uint64)
7659 fStage3Image->Bounds ().W ();
7660
7661 uint64 depthPixels = DepthMap ()->Bounds ().H () * (uint64)
7662 DepthMap ()->Bounds ().W ();
7663
7664 if (depthPixels < imagePixels)
7665 {
7666 fRawDepthMap.Reset (fDepthMap->Clone ());
7667 }
7668
7669 }
7670
7671 AutoPtr<dng_image> newMap (host.Make_dng_image (fStage3Image->Bounds (),
7672 1,
7673 DepthMap ()->PixelType ()));
7674
7675 host.ResampleImage (*DepthMap (),
7676 *newMap);
7677
7678 fDepthMap.Reset (newMap.Release ());
7679
7680 }
7681
7682 }
7683
7684 }
7685
7686 /*****************************************************************************/
7687
7688 void dng_negative::ResizeSemanticMasksToMatchStage3 (dng_host &host)
7689 {
7690
7691 if (!HasSemanticMask ())
7692 return;
7693
7694 if (!fStage3Image.Get ())
7695 return;
7696
7697 const dng_rect dstBounds = fStage3Image->Bounds ();
7698
7699 for (uint32 i = 0; i < NumSemanticMasks (); i++)
7700 {
7701
7702 const_dng_image_sptr mask = SemanticMask (i).fMask;
7703
7704 if (mask && (mask->Bounds () != dstBounds))
7705 {
7706
7707 AutoPtr<dng_image> image
7708 (host.Make_dng_image (dstBounds,
7709 mask->Planes (),
7710 mask->PixelType ()));
7711
7712 host.ResampleImage (*mask,
7713 *image);
7714
7715 fSemanticMasks.at (i).fMask.reset (image.Release ());
7716
7717 }
7718
7719 }
7720
7721 }
7722
7723 /*****************************************************************************/
7724
7725 bool dng_negative::HasSemanticMask () const
7726 {
7727
7728 return !fSemanticMasks.empty ();
7729
7730 }
7731
7732 /*****************************************************************************/
7733
7734 bool dng_negative::HasSemanticMask (uint32 index) const
7735 {
7736
7737 if (((size_t) index) >= fSemanticMasks.size ())
7738 {
7739
7740 return false;
7741
7742 }
7743
7744 return fSemanticMasks [index].fMask != nullptr;
7745
7746 }
7747
7748 /*****************************************************************************/
7749
7750 uint32 dng_negative::NumSemanticMasks () const
7751 {
7752
7753 return (uint32) fSemanticMasks.size ();
7754
7755 }
7756
7757 /*****************************************************************************/
7758
7759 const dng_semantic_mask & dng_negative::SemanticMask (uint32 index) const
7760 {
7761
7762 if (((size_t) index) >= fSemanticMasks.size ())
7763 {
7764
7765 ThrowProgramError ("non-existent index in SemanticMask");
7766
7767 }
7768
7769 return fSemanticMasks [index];
7770
7771 }
7772
7773 /*****************************************************************************/
7774
7775 // For now the concept of a "raw" semantic mask is the same as the regular
7776 // semantic mask API (original resolution).
7777
7778 const dng_semantic_mask & dng_negative::RawSemanticMask (uint32 index) const
7779 {
7780
7781 return SemanticMask (index);
7782
7783 }
7784
7785 /*****************************************************************************/
7786
7787 void dng_negative::SetSemanticMask (uint32 index,
7788 const dng_semantic_mask &mask)
7789 {
7790
7791 if (!HasSemanticMask (index))
7792 {
7793
7794 ThrowProgramError ("non-existent index in SetSemanticMask");
7795
7796 }
7797
7798 DNG_REQUIRE (mask.fMask, "missing mask in SetSemanticMask");
7799
7800 fSemanticMasks [index] = mask;
7801
7802 }
7803
7804 /*****************************************************************************/
7805
7806 void dng_negative::AppendSemanticMask (const dng_semantic_mask &mask)
7807 {
7808
7809 DNG_REQUIRE (mask.fMask, "missing mask in AppendSemanticMask");
7810
7811 fSemanticMasks.push_back (mask);
7812
7813 }
7814
7815 /*****************************************************************************/
7816
7817 void dng_negative::ReadSemanticMasks (dng_host &host,
7818 dng_stream &stream,
7819 dng_info &info)
7820 {
7821
7822 DNG_REQUIRE (info.fSemanticMaskIndices.size () <= kMaxSemanticMasks,
7823 "Too many semantic masks");
7824
7825 std::vector<dng_semantic_mask> masks;
7826
7827 masks.reserve (info.fSemanticMaskIndices.size ());
7828
7829 for (const uint32 index : info.fSemanticMaskIndices)
7830 {
7831
7832 dng_ifd &ifd = *info.fIFD.at (index);
7833
7834 AutoPtr<dng_image> image (host.Make_dng_image (ifd.Bounds (),
7835 1,
7836 ifd.PixelType ()));
7837
7838 AutoPtr<dng_lossy_compressed_image> lossyCompressed (KeepLossyCompressedImage (host, ifd));
7839
7840 // Workaround for early files that use lossy JPEG with Compression tag
7841 // value 7.
7842
7843 #if 1
7844
7845 if (ifd.fCompression == ccJPEG)
7846 {
7847
7848 // First try to read it directly as Lossless JPEG.
7849
7850 bool tryLossyJPEG = false;
7851
7852 try
7853 {
7854
7855 ifd.ReadImage (host,
7856 stream,
7857 *image);
7858
7859 }
7860
7861 catch (const dng_exception &e)
7862 {
7863
7864 // If that doesn't work, then try Lossy JPEG.
7865
7866 if (e.ErrorCode () == dng_error_bad_format)
7867 {
7868
7869 tryLossyJPEG = true;
7870
7871 }
7872
7873 // Re-throw other exceptions.
7874
7875 else
7876 {
7877
7878 throw;
7879
7880 }
7881
7882 }
7883
7884 // TODO(erichan): JXL support for semantic masks, too?
7885
7886 if (tryLossyJPEG)
7887 {
7888
7889 AutoPtr<dng_ifd> ifdClone (ifd.Clone ());
7890
7891 ifdClone->fCompression = ccLossyJPEG;
7892
7893 lossyCompressed.Reset (KeepLossyCompressedImage (host, *ifdClone));
7894
7895 ifdClone->ReadImage (host,
7896 stream,
7897 *image,
7898 lossyCompressed.Get ());
7899
7900 }
7901
7902 }
7903
7904 else
7905 {
7906
7907 ifd.ReadImage (host,
7908 stream,
7909 *image,
7910 lossyCompressed.Get ());
7911
7912 }
7913
7914 #else
7915
7916 ifd.ReadImage (host,
7917 stream,
7918 *image,
7919 lossyCompressed.Get ());
7920
7921 #endif
7922
7923 dng_semantic_mask mask;
7924
7925 mask.fName = ifd.fSemanticName;
7926 mask.fInstanceID = ifd.fSemanticInstanceID;
7927 mask.fXMP = ifd.fSemanticXMP;
7928
7929 memcpy (mask.fMaskSubArea,
7930 ifd .fMaskSubArea,
7931 sizeof (ifd .fMaskSubArea));
7932
7933 mask.fMask.reset (image.Release ());
7934
7935 // If MaskSubArea is not valid, then zero all the fields.
7936
7937 if (!mask.IsMaskSubAreaValid ())
7938 {
7939
7940 memset (mask.fMaskSubArea,
7941 0,
7942 sizeof (mask.fMaskSubArea));
7943
7944 }
7945
7946 mask.fLossyCompressed.reset (lossyCompressed.Release ());
7947
7948 masks.push_back (mask);
7949
7950 }
7951
7952 fSemanticMasks = masks;
7953
7954 }
7955
7956 /*****************************************************************************/
7957
7958 bool dng_negative::HasProfileGainTableMap () const
7959 {
7960
7961 return fProfileGainTableMap != nullptr;
7962
7963 }
7964
7965 /*****************************************************************************/
7966
7967 const dng_gain_table_map & dng_negative::ProfileGainTableMap () const
7968 {
7969
7970 DNG_REQUIRE (HasProfileGainTableMap (), "Missing profile gain table map");
7971
7972 return *fProfileGainTableMap;
7973
7974 }
7975
7976 /*****************************************************************************/
7977
7978 void dng_negative::SetProfileGainTableMap
7979 (const std::shared_ptr<const dng_gain_table_map> &gainTableMap)
7980 {
7981
7982 fProfileGainTableMap = gainTableMap;
7983
7984 }
7985
7986 /*****************************************************************************/
7987
7988 void dng_negative::SetProfileGainTableMap (AutoPtr<dng_gain_table_map> &gainTableMap)
7989 {
7990
7991 fProfileGainTableMap.reset (gainTableMap.Release ());
7992
7993 }
7994
7995 /*****************************************************************************/
7996
7997 void dng_negative::AdjustSemanticMasksForProxy (dng_host &host,
7998 dng_image_writer &writer,
7999 const dng_rect &originalStage3Bounds,
8000 const dng_rect &defaultCropArea)
8001 {
8002
8003 if (!HasSemanticMask ())
8004 {
8005 return;
8006 }
8007
8008 DNG_REQUIRE (fStage3Image.Get (), "Missing stage3 image");
8009
8010 const dng_rect newStage3Bounds = fStage3Image->Bounds ();
8011
8012 // If original active area is different than the original default crop
8013 // area, so this means during proxy conversion, the main image will be
8014 // trimmed to the default crop area. This means we need to adjust the
8015 // semantic masks, too. We need to resample and trim the masks so that
8016 // they align properly with the trimmed main image. This is complicated by
8017 // the fact that semantic masks may may be pre-cropped to exclude zero
8018 // pixels (i.e., MaskSubArea support).
8019
8020 const bool trimmedToDefaultCrop = (originalStage3Bounds != defaultCropArea);
8021
8022 const uint32 maskCount = NumSemanticMasks ();
8023
8024 for (uint32 i = 0; i < maskCount; i++)
8025 {
8026
8027 auto &mask = fSemanticMasks [i];
8028
8029 DNG_REQUIRE (mask.fMask, "Missing mask");
8030
8031 const bool needDownsampleMask =
8032 (mask.fMask->Bounds ().W () > newStage3Bounds.W () ||
8033 mask.fMask->Bounds ().H () > newStage3Bounds.H ()) ||
8034 (mask.fMask->PixelType () != ttByte);
8035
8036 if (needDownsampleMask || trimmedToDefaultCrop)
8037 {
8038
8039 AutoPtr<dng_image> image;
8040
8041 // Can we just resample directly to proxy size?
8042
8043 if (!mask.IsMaskSubAreaValid () & !trimmedToDefaultCrop)
8044 {
8045
8046 image.Reset (host.Make_dng_image (newStage3Bounds,
8047 1,
8048 ttByte));
8049
8050 host.ResampleImage (*mask.fMask,
8051 *image);
8052
8053 }
8054
8055 // Else we need to first create a full size trimmed mask.
8056
8057 else
8058 {
8059
8060 // If we need to perform a second downsample step, then use the
8061 // original mask pixel type as the intermediate pixel type.
8062
8063 const bool needResizeToFinalArea =
8064 (newStage3Bounds.Size () != defaultCropArea.Size ());
8065
8066 const uint32 fullResPixelType =
8067 needResizeToFinalArea ? mask.fMask->PixelType ()
8068 : ttByte;
8069
8070 AutoPtr<dng_image> fullResMask
8071 (host.Make_dng_image (originalStage3Bounds,
8072 1,
8073 fullResPixelType));
8074
8075 if (mask.IsMaskSubAreaValid ())
8076 {
8077
8078 // MaskSubArea case.
8079
8080 // Make a zero-filled image that represents the uncropped mask
8081 // area (corresponding logically to the active area, or
8082 // originalStage3Bounds).
8083
8084 dng_point origin;
8085
8086 dng_rect srcArea;
8087
8088 mask.CalcMaskSubArea (origin, srcArea);
8089
8090 const uint32 srcPixelType = mask.fMask->PixelType ();
8091
8092 AutoPtr<dng_image> srcImage
8093 (host.Make_dng_image (srcArea,
8094 1,
8095 srcPixelType));
8096
8097 srcImage->SetZero (srcArea);
8098
8099 // Copy the mask into the zero-filled image.
8100
8101 AutoPtr<dng_image> subImage (mask.fMask->Clone ());
8102
8103 subImage->Offset (origin);
8104
8105 srcImage->CopyArea (*subImage,
8106 subImage->Bounds (),
8107 0,
8108 0,
8109 1);
8110
8111 // Resample to active area.
8112
8113 host.ResampleImage (*srcImage,
8114 *fullResMask);
8115
8116 }
8117
8118 else
8119 {
8120
8121 // Without MaskSubArea case. Resample directly.
8122
8123 host.ResampleImage (*mask.fMask,
8124 *fullResMask);
8125
8126 }
8127
8128 // Trim to default crop area.
8129
8130 fullResMask->Trim (defaultCropArea);
8131
8132 image.Reset (fullResMask.Release ());
8133
8134 // Resize to new area, if needed.
8135
8136 if (needResizeToFinalArea)
8137 {
8138
8139 AutoPtr<dng_image> temp
8140 (host.Make_dng_image (newStage3Bounds,
8141 1,
8142 ttByte));
8143
8144 host.ResampleImage (*image,
8145 *temp);
8146
8147 image.Reset (temp.Release ());
8148
8149 }
8150
8151 }
8152
8153 // Store.
8154
8155 mask.fMask.reset (image.Release ());
8156
8157 // Clear MaskSubArea.
8158
8159 memset (mask.fMaskSubArea, 0, sizeof (mask.fMaskSubArea));
8160
8161 // Lossy compressed data is no longer valid.
8162
8163 mask.fLossyCompressed.reset ();
8164
8165 }
8166
8167 }
8168
8169 CompressSemanticMasksJXL (host,
8170 writer,
8171 true);
8172
8173 }
8174
8175 /*****************************************************************************/