Debian Codegraph @

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

raw
1 /*****************************************************************************/
2 // Copyright 2006-2022 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_image_writer.h"
10
11 #include "dng_abort_sniffer.h"
12 #include "dng_area_task.h"
13 #include "dng_big_table.h"
14 #include "dng_bottlenecks.h"
15 #include "dng_camera_profile.h"
16 #include "dng_color_space.h"
17 #include "dng_exceptions.h"
18 #include "dng_exif.h"
19 #include "dng_flags.h"
20 #include "dng_gain_map.h"
21 #include "dng_globals.h"
22 #include "dng_host.h"
23 #include "dng_ifd.h"
24 #include "dng_image.h"
25 #include "dng_jpeg_image.h"
26 #include "dng_jxl.h"
27 #include "dng_lossless_jpeg.h"
28 #include "dng_memory.h"
29 #include "dng_memory_stream.h"
30 #include "dng_negative.h"
31 #include "dng_pixel_buffer.h"
32 #include "dng_preview.h"
33 #include "dng_read_image.h"
34 #include "dng_safe_arithmetic.h"
35 #include "dng_shared.h"
36 #include "dng_stream.h"
37 #include "dng_string_list.h"
38 #include "dng_tag_codes.h"
39 #include "dng_tag_values.h"
40 #include "dng_utils.h"
41
42 #if qDNGUseXMP
43 #include "dng_xmp.h"
44 #endif
45
46 #include "zlib.h"
47
48 #if qDNGUseLibJPEG
49 #include "dng_jpeglib.h"
50 #endif
51
52 #include <atomic>
53
54 /*****************************************************************************/
55
56 // Defines for testing DNG 1.2 features.
57
58 //#define qTestRowInterleave 2
59
60 //#define qTestSubTileBlockRows 2
61 //#define qTestSubTileBlockCols 2
62
63 /*****************************************************************************/
64
65 // Defines for testing DNG 1.7 features.
66
67 //#define qTestColumnInterleave 2
68
69 /*****************************************************************************/
70
71 dng_resolution::dng_resolution ()
72
73 : fXResolution ()
74 , fYResolution ()
75
76 , fResolutionUnit (0)
77
78 {
79
80 }
81
82 /******************************************************************************/
83
84 static void SpoolAdobeData (dng_stream &stream,
85 const dng_metadata *metadata,
86 const dng_jpeg_preview *preview,
87 const dng_memory_block *imageResources)
88 {
89
90 TempBigEndian tempEndian (stream);
91
92 #if qDNGUseXMP
93
94 if (metadata && metadata->GetXMP ())
95 {
96
97 bool marked = false;
98
99 if (metadata->GetXMP ()->GetBoolean (XMP_NS_XAP_RIGHTS,
100 "Marked",
101 marked))
102 {
103
104 stream.Put_uint32 (DNG_CHAR4 ('8','B','I','M'));
105 stream.Put_uint16 (1034);
106 stream.Put_uint16 (0);
107
108 stream.Put_uint32 (1);
109
110 stream.Put_uint8 (marked ? 1 : 0);
111
112 stream.Put_uint8 (0);
113
114 }
115
116 dng_string webStatement;
117
118 if (metadata->GetXMP ()->GetString (XMP_NS_XAP_RIGHTS,
119 "WebStatement",
120 webStatement))
121 {
122
123 dng_memory_data buffer;
124
125 uint32 size = webStatement.Get_SystemEncoding (buffer);
126
127 if (size > 0)
128 {
129
130 stream.Put_uint32 (DNG_CHAR4 ('8','B','I','M'));
131 stream.Put_uint16 (1035);
132 stream.Put_uint16 (0);
133
134 stream.Put_uint32 (size);
135
136 stream.Put (buffer.Buffer (), size);
137
138 if (size & 1)
139 stream.Put_uint8 (0);
140
141 }
142
143 }
144
145 }
146
147 #endif // qDNGUseXMP
148
149 if (preview)
150 {
151
152 preview->SpoolAdobeThumbnail (stream);
153
154 }
155
156 if (metadata && metadata->IPTCLength ())
157 {
158
159 dng_fingerprint iptcDigest = metadata->IPTCDigest ();
160
161 if (iptcDigest.IsValid ())
162 {
163
164 stream.Put_uint32 (DNG_CHAR4 ('8','B','I','M'));
165 stream.Put_uint16 (1061);
166 stream.Put_uint16 (0);
167
168 stream.Put_uint32 (16);
169
170 stream.Put (iptcDigest.data, 16);
171
172 }
173
174 }
175
176 if (imageResources)
177 {
178
179 uint32 size = imageResources->LogicalSize ();
180
181 stream.Put (imageResources->Buffer (), size);
182
183 if (size & 1)
184 stream.Put_uint8 (0);
185
186 }
187
188 }
189
190 /******************************************************************************/
191
192 static dng_memory_block * BuildAdobeData (dng_host &host,
193 const dng_metadata *metadata,
194 const dng_jpeg_preview *preview,
195 const dng_memory_block *imageResources)
196 {
197
198 dng_memory_stream stream (host.Allocator ());
199
200 SpoolAdobeData (stream,
201 metadata,
202 preview,
203 imageResources);
204
205 return stream.AsMemoryBlock (host.Allocator ());
206
207 }
208
209 /*****************************************************************************/
210
211 tag_string::tag_string (uint16 code,
212 const dng_string &s,
213 bool forceASCII)
214
215 : tiff_tag (code, ttAscii, 0)
216
217 , fString (s)
218
219 {
220
221 if (forceASCII)
222 {
223
224 // Metadata working group recommendation - go ahead
225 // write UTF-8 into ASCII tag strings, rather than
226 // actually force the strings to ASCII. There is a matching
227 // change on the reading side to assume UTF-8 if the string
228 // contains a valid UTF-8 string.
229 //
230 // fString.ForceASCII ();
231
232 }
233
234 else if (!fString.IsASCII ())
235 {
236
237 fType = ttByte;
238
239 }
240
241 fCount = fString.Length () + 1;
242
243 }
244
245 /*****************************************************************************/
246
247 void tag_string::Put (dng_stream &stream) const
248 {
249
250 stream.Put (fString.Get (), Size ());
251
252 }
253
254 /*****************************************************************************/
255
256 tag_encoded_text::tag_encoded_text (uint16 code,
257 const dng_string &text)
258
259 : tiff_tag (code, ttUndefined, 0)
260
261 , fText (text)
262
263 , fUTF16 ()
264
265 {
266
267 if (fText.IsASCII ())
268 {
269
270 fCount = 8 + fText.Length ();
271
272 }
273
274 else
275 {
276
277 fCount = 8 + fText.Get_UTF16 (fUTF16) * 2;
278
279 }
280
281 }
282
283 /*****************************************************************************/
284
285 void tag_encoded_text::Put (dng_stream &stream) const
286 {
287
288 if (fUTF16.Buffer ())
289 {
290
291 stream.Put ("UNICODE\000", 8);
292
293 uint32 chars = (fCount - 8) >> 1;
294
295 const uint16 *buf = fUTF16.Buffer_uint16 ();
296
297 for (uint32 j = 0; j < chars; j++)
298 {
299
300 stream.Put_uint16 (buf [j]);
301
302 }
303
304 }
305
306 else
307 {
308
309 stream.Put ("ASCII\000\000\000", 8);
310
311 stream.Put (fText.Get (), fCount - 8);
312
313 }
314
315 }
316
317 /*****************************************************************************/
318
319 void tag_data_ptr::Put (dng_stream &stream) const
320 {
321
322 // If we are swapping bytes, we need to swap with the right size
323 // entries.
324
325 if (stream.SwapBytes ())
326 {
327
328 switch (Type ())
329 {
330
331 // Two byte entries.
332
333 case ttShort:
334 case ttSShort:
335 case ttUnicode:
336 {
337
338 const uint16 *p = (const uint16 *) fData;
339
340 uint32 entries = (Size () >> 1);
341
342 for (uint32 j = 0; j < entries; j++)
343 {
344
345 stream.Put_uint16 (p [j]);
346
347 }
348
349 return;
350
351 }
352
353 // Four byte entries.
354
355 case ttLong:
356 case ttSLong:
357 case ttRational:
358 case ttSRational:
359 case ttIFD:
360 case ttFloat:
361 case ttComplex:
362 {
363
364 const uint32 *p = (const uint32 *) fData;
365
366 uint32 entries = (Size () >> 2);
367
368 for (uint32 j = 0; j < entries; j++)
369 {
370
371 stream.Put_uint32 (p [j]);
372
373 }
374
375 return;
376
377 }
378
379 // Eight byte entries.
380
381 case ttDouble:
382 case ttLong8:
383 case ttSLong8:
384 case ttIFD8:
385 {
386
387 const real64 *p = (const real64 *) fData;
388
389 uint32 entries = (Size () >> 3);
390
391 for (uint32 j = 0; j < entries; j++)
392 {
393
394 stream.Put_real64 (p [j]);
395
396 }
397
398 return;
399
400 }
401
402 // Entries don't need to be byte swapped. Fall through
403 // to non-byte swapped case.
404
405 default:
406 {
407
408 break;
409
410 }
411
412 }
413
414 }
415
416 // Non-byte swapped case.
417
418 stream.Put (fData, Size ());
419
420 }
421
422 /******************************************************************************/
423
424 void tag_big_uint::Put (dng_stream &stream) const
425 {
426
427 if (fType == ttLong)
428 {
429
430 if (fValue > 0xFFFFFFFF)
431 {
432 ThrowProgramError ("tag_big_uint overflow");
433 }
434
435 stream.Put_uint32 ((uint32) fValue);
436
437 }
438
439 else
440 {
441 stream.Put_uint64 (fValue);
442 }
443
444 }
445
446 /******************************************************************************/
447
448 void tag_big_uints::Put (dng_stream &stream) const
449 {
450
451 const uint64 *buffer = fData.Buffer_uint64 ();
452
453 for (uint32 index = 0; index < fCount; index++)
454 {
455
456 uint64 x = buffer [index];
457
458 if (fType == ttLong)
459 {
460
461 if (x > 0xFFFFFFFF)
462 {
463 ThrowProgramError ("tag_big_uints overflow");
464 }
465
466 stream.Put_uint32 ((uint32) x);
467
468 }
469
470 else
471 {
472 stream.Put_uint64 (x);
473 }
474
475 }
476
477 }
478
479 /******************************************************************************/
480
481 tag_matrix::tag_matrix (uint16 code,
482 const dng_matrix &m)
483
484 : tag_srational_ptr (code, fEntry, m.Rows () * m.Cols ())
485
486 {
487
488 uint32 index = 0;
489
490 for (uint32 r = 0; r < m.Rows (); r++)
491 for (uint32 c = 0; c < m.Cols (); c++)
492 {
493
494 fEntry [index].Set_real64 (m [r] [c], 10000);
495
496 index++;
497
498 }
499
500 }
501
502 /******************************************************************************/
503
504 tag_icc_profile::tag_icc_profile (const void *profileData,
505 uint32 profileSize)
506
507 : tag_data_ptr (tcICCProfile,
508 ttUndefined,
509 0,
510 NULL)
511
512 {
513
514 if (profileData && profileSize)
515 {
516
517 SetCount (profileSize);
518 SetData (profileData);
519
520 }
521
522 }
523
524 /******************************************************************************/
525
526 void tag_cfa_pattern::Put (dng_stream &stream) const
527 {
528
529 stream.Put_uint16 ((uint16) fCols);
530 stream.Put_uint16 ((uint16) fRows);
531
532 for (uint32 col = 0; col < fCols; col++)
533 for (uint32 row = 0; row < fRows; row++)
534 {
535
536 stream.Put_uint8 (fPattern [row * kMaxCFAPattern + col]);
537
538 }
539
540 }
541
542 /******************************************************************************/
543
544 tag_exif_date_time::tag_exif_date_time (uint16 code,
545 const dng_date_time &dt)
546
547 : tag_data_ptr (code, ttAscii, 20, fData)
548
549 {
550
551 if (dt.IsValid ())
552 {
553
554 snprintf (fData,
555 20,
556 "%04d:%02d:%02d %02d:%02d:%02d",
557 (int) dt.fYear,
558 (int) dt.fMonth,
559 (int) dt.fDay,
560 (int) dt.fHour,
561 (int) dt.fMinute,
562 (int) dt.fSecond);
563
564 }
565
566 }
567
568 /******************************************************************************/
569
570 tag_iptc::tag_iptc (const void *data,
571 uint32 length)
572
573 : tiff_tag (tcIPTC_NAA, ttLong, (length + 3) >> 2)
574
575 , fData (data )
576 , fLength (length)
577
578 {
579
580 }
581
582 /******************************************************************************/
583
584 void tag_iptc::Put (dng_stream &stream) const
585 {
586
587 // Note: For historical compatibility reasons, the standard TIFF data
588 // type for IPTC data is ttLong, but without byte swapping. This really
589 // should be ttUndefined, but doing the right thing would break some
590 // existing readers.
591
592 stream.Put (fData, fLength);
593
594 // Pad with zeros to get to long word boundary.
595
596 uint32 extra = fCount * 4 - fLength;
597
598 while (extra--)
599 {
600 stream.Put_uint8 (0);
601 }
602
603 }
604
605 /******************************************************************************/
606
607 tag_xmp::tag_xmp (const dng_xmp *xmp)
608
609 : tag_uint8_ptr (tcXMP, NULL, 0)
610
611 , fBuffer ()
612
613 {
614
615 #if qDNGUseXMP
616
617 if (xmp)
618 {
619
620 fBuffer.Reset (xmp->Serialize (true));
621
622 if (fBuffer.Get ())
623 {
624
625 SetData (fBuffer->Buffer_uint8 ());
626
627 SetCount (fBuffer->LogicalSize ());
628
629 }
630
631 }
632
633 #endif // qDNGUseXMP
634
635 }
636
637 /******************************************************************************/
638
639 void dng_tiff_directory::Add (tiff_tag *tag)
640 {
641
642 // Tags must be sorted in increasing order of tag code.
643
644 for (size_t j = 0; j < fTag.size (); j++)
645 {
646
647 if (tag->Code () < fTag [j]->Code ())
648 {
649 fTag.insert (fTag.begin () + j, tag);
650 return;
651 }
652
653 }
654
655 fTag.push_back (tag);
656
657 }
658
659 /******************************************************************************/
660
661 void dng_tiff_directory::SetBigTIFF (bool isBigTIFF)
662 {
663
664 fBigTIFF = isBigTIFF;
665
666 for (size_t index = 0; index < fTag.size (); index++)
667 {
668
669 fTag [index]->SetBigTIFF (isBigTIFF);
670
671 }
672
673 }
674
675 /******************************************************************************/
676
677 uint32 dng_tiff_directory::Size () const
678 {
679
680 if (!fTag.size ()) return 0;
681
682 uint32 size = fBigTIFF ? (uint32) fTag.size () * 20 + 16
683 : (uint32) fTag.size () * 12 + 6;
684
685 for (size_t index = 0; index < fTag.size (); index++)
686 {
687
688 uint32 tagSize = fTag [index]->Size ();
689
690 if (tagSize > (uint32)(fBigTIFF ? 8 : 4))
691 {
692
693 size += (tagSize + 1) & ~1;
694
695 }
696
697 }
698
699 return size;
700
701 }
702
703 /******************************************************************************/
704
705 void dng_tiff_directory::Put (dng_stream &stream,
706 OffsetsBase offsetsBase,
707 uint64 explicitBase) const
708 {
709
710 if (!fTag.size ()) return;
711
712 uint64 bigData = fBigTIFF ? fTag.size () * 20 + 16
713 : fTag.size () * 12 + 6;
714
715 if (offsetsBase == offsetsRelativeToStream)
716 bigData += stream.Position ();
717
718 else if (offsetsBase == offsetsRelativeToExplicitBase)
719 bigData += explicitBase;
720
721 if (fBigTIFF)
722 stream.Put_uint64 ((uint64) fTag.size ());
723 else
724 stream.Put_uint16 ((uint16) fTag.size ());
725
726 for (size_t index = 0; index < fTag.size (); index++)
727 {
728
729 const tiff_tag &tag = *fTag [index];
730
731 stream.Put_uint16 (tag.Code ());
732 stream.Put_uint16 (tag.Type ());
733
734 if (fBigTIFF)
735 stream.Put_uint64 ((uint64) tag.Count ());
736 else
737 stream.Put_uint32 ((uint32) tag.Count ());
738
739 uint32 size = tag.Size ();
740
741 if (size <= (uint32)(fBigTIFF ? 8 : 4))
742 {
743
744 tag.Put (stream);
745
746 while (size < (uint32)(fBigTIFF ? 8 : 4))
747 {
748 stream.Put_uint8 (0);
749 size++;
750 }
751
752 }
753
754 else
755 {
756
757 if (fBigTIFF)
758 stream.Put_uint64 (bigData);
759 else
760 stream.Put_uint32 ((uint32) bigData);
761
762 bigData += (size + 1) & ~1;
763
764 }
765
766 }
767
768 // Next IFD offset
769
770 if (fBigTIFF)
771 stream.Put_uint64 (fChained);
772 else
773 stream.Put_uint32 ((uint32) fChained);
774
775 for (size_t index = 0; index < fTag.size (); index++)
776 {
777
778 const tiff_tag &tag = *fTag [index];
779
780 uint32 size = tag.Size ();
781
782 if (size > (uint32)(fBigTIFF ? 8 : 4))
783 {
784
785 tag.Put (stream);
786
787 if (size & 1)
788 stream.Put_uint8 (0);
789
790 }
791
792 }
793
794 }
795
796 /******************************************************************************/
797
798 dng_basic_tag_set::dng_basic_tag_set (dng_tiff_directory &directory,
799 const dng_ifd &info)
800
801 : fNewSubFileType (tcNewSubFileType, info.fNewSubFileType)
802
803 , fImageWidth (tcImageWidth , info.fImageWidth )
804 , fImageLength (tcImageLength, info.fImageLength)
805
806 , fPhotoInterpretation (tcPhotometricInterpretation,
807 (uint16) info.fPhotometricInterpretation)
808
809 , fFillOrder (tcFillOrder, 1)
810
811 , fSamplesPerPixel (tcSamplesPerPixel, (uint16) info.fSamplesPerPixel)
812
813 , fBitsPerSampleData (info.fSamplesPerPixel)
814
815 , fBitsPerSample (tcBitsPerSample,
816 fBitsPerSampleData.data (),
817 info.fSamplesPerPixel)
818
819 , fStrips (info.fUsesStrips)
820
821 , fTileWidth (tcTileWidth, info.fTileWidth)
822
823 , fTileLength (fStrips ? tcRowsPerStrip : tcTileLength,
824 info.fTileLength)
825
826 , fTileOffsets (fStrips ? tcStripOffsets : tcTileOffsets,
827 info.TilesPerImage ())
828
829 , fTileByteCounts (fStrips ? tcStripByteCounts : tcTileByteCounts,
830 info.TilesPerImage (),
831 info.fCompression != ccUncompressed)
832
833 , fPlanarConfiguration (tcPlanarConfiguration, pcInterleaved)
834
835 , fCompression (tcCompression, (uint16) info.fCompression)
836 , fPredictor (tcPredictor , (uint16) info.fPredictor )
837
838 , fExtraSamplesData (info.fExtraSamplesCount)
839
840 , fExtraSamples (tcExtraSamples,
841 fExtraSamplesData.data (),
842 info.fExtraSamplesCount)
843
844 , fSampleFormatData (info.fSamplesPerPixel)
845
846 , fSampleFormat (tcSampleFormat,
847 fSampleFormatData.data (),
848 info.fSamplesPerPixel)
849
850 , fRowInterleaveFactor (tcRowInterleaveFactor,
851 (uint16) info.fRowInterleaveFactor)
852
853 , fColumnInterleaveFactor (tcColumnInterleaveFactor,
854 (uint16) info.fColumnInterleaveFactor)
855
856 , fSubTileBlockSize (tcSubTileBlockSize,
857 fSubTileBlockSizeData,
858 2)
859
860 , fJXLDistance (tcJXLDistance)
861 , fJXLEffort (tcJXLEffort)
862 , fJXLDecodeSpeed (tcJXLDecodeSpeed)
863
864 {
865
866 uint32 j;
867
868 for (j = 0; j < info.fSamplesPerPixel; j++)
869 {
870
871 fBitsPerSampleData [j] = (uint16) info.fBitsPerSample [0];
872
873 }
874
875 directory.Add (&fNewSubFileType);
876
877 directory.Add (&fImageWidth);
878 directory.Add (&fImageLength);
879
880 directory.Add (&fPhotoInterpretation);
881
882 directory.Add (&fSamplesPerPixel);
883
884 directory.Add (&fBitsPerSample);
885
886 if (info.fBitsPerSample [0] != 8 &&
887 info.fBitsPerSample [0] != 16 &&
888 info.fBitsPerSample [0] != 32)
889 {
890
891 directory.Add (&fFillOrder);
892
893 }
894
895 if (!fStrips)
896 {
897
898 directory.Add (&fTileWidth);
899
900 }
901
902 directory.Add (&fTileLength);
903
904 directory.Add (&fTileOffsets);
905 directory.Add (&fTileByteCounts);
906
907 directory.Add (&fPlanarConfiguration);
908
909 directory.Add (&fCompression);
910
911 if (info.fPredictor != cpNullPredictor)
912 {
913
914 directory.Add (&fPredictor);
915
916 }
917
918 if (info.fExtraSamplesCount != 0)
919 {
920
921 for (j = 0; j < info.fExtraSamplesCount; j++)
922 {
923 fExtraSamplesData [j] = (uint16) info.fExtraSamples [j];
924 }
925
926 directory.Add (&fExtraSamples);
927
928 }
929
930 if (info.fSampleFormat [0] != sfUnsignedInteger)
931 {
932
933 for (j = 0; j < info.fSamplesPerPixel; j++)
934 {
935 fSampleFormatData [j] = (uint16) info.fSampleFormat [j];
936 }
937
938 directory.Add (&fSampleFormat);
939
940 }
941
942 if (info.fRowInterleaveFactor != 1)
943 {
944
945 directory.Add (&fRowInterleaveFactor);
946
947 }
948
949 if (info.fColumnInterleaveFactor != 1)
950 {
951
952 directory.Add (&fColumnInterleaveFactor);
953
954 }
955
956 if (info.fSubTileBlockRows != 1 ||
957 info.fSubTileBlockCols != 1)
958 {
959
960 fSubTileBlockSizeData [0] = (uint16) info.fSubTileBlockRows;
961 fSubTileBlockSizeData [1] = (uint16) info.fSubTileBlockCols;
962
963 directory.Add (&fSubTileBlockSize);
964
965 }
966
967 if (info.fCompression == ccJXL)
968 {
969
970 if (info.fJXLDistance >= 0.0f)
971 {
972
973 fJXLDistance.Set (info.fJXLDistance);
974
975 directory.Add (&fJXLDistance);
976
977 }
978
979 if (info.fJXLEffort >= 1)
980 {
981
982 fJXLEffort.Set (info.fJXLEffort);
983
984 directory.Add (&fJXLEffort);
985
986 }
987
988 if (info.fJXLDecodeSpeed >= 1)
989 {
990
991 fJXLDecodeSpeed.Set (info.fJXLDecodeSpeed);
992
993 directory.Add (&fJXLDecodeSpeed);
994
995 }
996
997 }
998
999 }
1000
1001 /******************************************************************************/
1002
1003 exif_tag_set::exif_tag_set (dng_tiff_directory &directory,
1004 const dng_exif &exif,
1005 bool makerNoteSafe,
1006 const void *makerNoteData,
1007 uint32 makerNoteLength,
1008 bool insideDNG)
1009
1010 : fExifIFD ()
1011 , fGPSIFD ()
1012
1013 , fExifLink (tcExifIFD, 0)
1014 , fGPSLink (tcGPSInfo, 0)
1015
1016 , fAddedExifLink (false)
1017 , fAddedGPSLink (false)
1018
1019 , fExifVersion (tcExifVersion, ttUndefined, 4, fExifVersionData)
1020
1021 , fExposureTime (tcExposureTime , exif.fExposureTime )
1022 , fShutterSpeedValue (tcShutterSpeedValue, exif.fShutterSpeedValue)
1023
1024 , fFNumber (tcFNumber , exif.fFNumber )
1025 , fApertureValue (tcApertureValue, exif.fApertureValue)
1026
1027 , fBrightnessValue (tcBrightnessValue, exif.fBrightnessValue)
1028
1029 , fExposureBiasValue (tcExposureBiasValue, exif.fExposureBiasValue)
1030
1031 , fMaxApertureValue (tcMaxApertureValue , exif.fMaxApertureValue)
1032
1033 , fSubjectDistance (tcSubjectDistance, exif.fSubjectDistance)
1034
1035 , fFocalLength (tcFocalLength, exif.fFocalLength)
1036
1037 // Special case: the EXIF 2.2 standard represents ISO speed ratings with 2 bytes,
1038 // which cannot hold ISO speed ratings above 65535 (e.g., 102400). In these
1039 // cases, we write the maximum representable ISO speed rating value in the EXIF
1040 // tag, i.e., 65535.
1041
1042 , fISOSpeedRatings (tcISOSpeedRatings,
1043 (uint16) Min_uint32 (65535,
1044 exif.fISOSpeedRatings [0]))
1045
1046 , fSensitivityType (tcSensitivityType, (uint16) exif.fSensitivityType)
1047
1048 , fStandardOutputSensitivity (tcStandardOutputSensitivity, exif.fStandardOutputSensitivity)
1049
1050 , fRecommendedExposureIndex (tcRecommendedExposureIndex, exif.fRecommendedExposureIndex)
1051
1052 , fISOSpeed (tcISOSpeed, exif.fISOSpeed)
1053
1054 , fISOSpeedLatitudeyyy (tcISOSpeedLatitudeyyy, exif.fISOSpeedLatitudeyyy)
1055
1056 , fISOSpeedLatitudezzz (tcISOSpeedLatitudezzz, exif.fISOSpeedLatitudezzz)
1057
1058 , fFlash (tcFlash, (uint16) exif.fFlash)
1059
1060 , fExposureProgram (tcExposureProgram, (uint16) exif.fExposureProgram)
1061
1062 , fMeteringMode (tcMeteringMode, (uint16) exif.fMeteringMode)
1063
1064 , fLightSource (tcLightSource, (uint16) exif.fLightSource)
1065
1066 , fSensingMethod (tcSensingMethodExif, (uint16) exif.fSensingMethod)
1067
1068 , fFocalLength35mm (tcFocalLengthIn35mmFilm, (uint16) exif.fFocalLengthIn35mmFilm)
1069
1070 , fFileSourceData ((uint8) exif.fFileSource)
1071 , fFileSource (tcFileSource, ttUndefined, 1, &fFileSourceData)
1072
1073 , fSceneTypeData ((uint8) exif.fSceneType)
1074 , fSceneType (tcSceneType, ttUndefined, 1, &fSceneTypeData)
1075
1076 , fCFAPattern (tcCFAPatternExif,
1077 exif.fCFARepeatPatternRows,
1078 exif.fCFARepeatPatternCols,
1079 &exif.fCFAPattern [0] [0])
1080
1081 , fCustomRendered (tcCustomRendered , (uint16) exif.fCustomRendered )
1082 , fExposureMode (tcExposureMode , (uint16) exif.fExposureMode )
1083 , fWhiteBalance (tcWhiteBalance , (uint16) exif.fWhiteBalance )
1084 , fSceneCaptureType (tcSceneCaptureType , (uint16) exif.fSceneCaptureType )
1085 , fGainControl (tcGainControl , (uint16) exif.fGainControl )
1086 , fContrast (tcContrast , (uint16) exif.fContrast )
1087 , fSaturation (tcSaturation , (uint16) exif.fSaturation )
1088 , fSharpness (tcSharpness , (uint16) exif.fSharpness )
1089 , fSubjectDistanceRange (tcSubjectDistanceRange, (uint16) exif.fSubjectDistanceRange)
1090
1091 , fDigitalZoomRatio (tcDigitalZoomRatio, exif.fDigitalZoomRatio)
1092
1093 , fExposureIndex (tcExposureIndexExif, exif.fExposureIndex)
1094
1095 , fImageNumber (tcImageNumber, exif.fImageNumber)
1096
1097 , fSelfTimerMode (tcSelfTimerMode, (uint16) exif.fSelfTimerMode)
1098
1099 , fBatteryLevelA (tcBatteryLevel, exif.fBatteryLevelA)
1100 , fBatteryLevelR (tcBatteryLevel, exif.fBatteryLevelR)
1101
1102 , fColorSpace (tcColorSpace, (uint16) exif.fColorSpace)
1103
1104 , fFocalPlaneXResolution (tcFocalPlaneXResolutionExif, exif.fFocalPlaneXResolution)
1105 , fFocalPlaneYResolution (tcFocalPlaneYResolutionExif, exif.fFocalPlaneYResolution)
1106
1107 , fFocalPlaneResolutionUnit (tcFocalPlaneResolutionUnitExif, (uint16) exif.fFocalPlaneResolutionUnit)
1108
1109 , fSubjectArea (tcSubjectArea, fSubjectAreaData, exif.fSubjectAreaCount)
1110
1111 , fLensInfo (tcLensInfo, fLensInfoData, 4)
1112
1113 , fDateTime (tcDateTime , exif.fDateTime .DateTime ())
1114 , fDateTimeOriginal (tcDateTimeOriginal , exif.fDateTimeOriginal .DateTime ())
1115 , fDateTimeDigitized (tcDateTimeDigitized, exif.fDateTimeDigitized.DateTime ())
1116
1117 , fSubsecTime (tcSubsecTime, exif.fDateTime .Subseconds ())
1118 , fSubsecTimeOriginal (tcSubsecTimeOriginal, exif.fDateTimeOriginal .Subseconds ())
1119 , fSubsecTimeDigitized (tcSubsecTimeDigitized, exif.fDateTimeDigitized.Subseconds ())
1120
1121 , fOffsetTime (tcOffsetTime, exif.fDateTime .OffsetTime ())
1122 , fOffsetTimeOriginal (tcOffsetTimeOriginal, exif.fDateTimeOriginal .OffsetTime ())
1123 , fOffsetTimeDigitized (tcOffsetTimeDigitized, exif.fDateTimeDigitized.OffsetTime ())
1124
1125 , fMake (tcMake, exif.fMake)
1126
1127 , fModel (tcModel, exif.fModel)
1128
1129 , fArtist (tcArtist, exif.fArtist)
1130
1131 , fSoftware (tcSoftware, exif.fSoftware)
1132
1133 , fCopyright (tcCopyright, exif.fCopyright)
1134
1135 , fImageDescription (tcImageDescription, exif.fImageDescription)
1136
1137 , fSerialNumber (tcCameraSerialNumber, exif.fCameraSerialNumber)
1138
1139 , fMakerNoteSafety (tcMakerNoteSafety, makerNoteSafe ? 1 : 0)
1140
1141 , fMakerNote (tcMakerNote, ttUndefined, makerNoteLength, makerNoteData)
1142
1143 , fUserComment (tcUserComment, exif.fUserComment)
1144
1145 , fImageUniqueID (tcImageUniqueID, ttAscii, 33, fImageUniqueIDData)
1146
1147 // EXIF 2.3 tags.
1148
1149 , fCameraOwnerName (tcCameraOwnerNameExif, exif.fOwnerName )
1150 , fBodySerialNumber (tcCameraSerialNumberExif, exif.fCameraSerialNumber)
1151 , fLensSpecification (tcLensSpecificationExif, fLensInfoData, 4 )
1152 , fLensMake (tcLensMakeExif, exif.fLensMake )
1153 , fLensModel (tcLensModelExif, exif.fLensName )
1154 , fLensSerialNumber (tcLensSerialNumberExif, exif.fLensSerialNumber )
1155
1156 // EXIF 2.3.1 tags.
1157
1158 , fTemperature (tcTemperature, exif.fTemperature )
1159 , fHumidity (tcHumidity, exif.fHumidity )
1160 , fPressure (tcPressure, exif.fPressure )
1161 , fWaterDepth (tcWaterDepth, exif.fWaterDepth )
1162 , fAcceleration (tcAcceleration, exif.fAcceleration )
1163 , fCameraElevationAngle (tcCameraElevationAngle, exif.fCameraElevationAngle)
1164
1165 , fGPSVersionID (tcGPSVersionID, fGPSVersionData, 4)
1166
1167 , fGPSLatitudeRef (tcGPSLatitudeRef, exif.fGPSLatitudeRef)
1168 , fGPSLatitude (tcGPSLatitude, exif.fGPSLatitude, 3)
1169
1170 , fGPSLongitudeRef (tcGPSLongitudeRef, exif.fGPSLongitudeRef)
1171 , fGPSLongitude (tcGPSLongitude, exif.fGPSLongitude, 3)
1172
1173 , fGPSAltitudeRef (tcGPSAltitudeRef, (uint8) exif.fGPSAltitudeRef)
1174 , fGPSAltitude (tcGPSAltitude, exif.fGPSAltitude )
1175
1176 , fGPSTimeStamp (tcGPSTimeStamp, exif.fGPSTimeStamp, 3)
1177
1178 , fGPSSatellites (tcGPSSatellites , exif.fGPSSatellites )
1179 , fGPSStatus (tcGPSStatus , exif.fGPSStatus )
1180 , fGPSMeasureMode (tcGPSMeasureMode, exif.fGPSMeasureMode)
1181
1182 , fGPSDOP (tcGPSDOP, exif.fGPSDOP)
1183
1184 , fGPSSpeedRef (tcGPSSpeedRef, exif.fGPSSpeedRef)
1185 , fGPSSpeed (tcGPSSpeed , exif.fGPSSpeed )
1186
1187 , fGPSTrackRef (tcGPSTrackRef, exif.fGPSTrackRef)
1188 , fGPSTrack (tcGPSTrack , exif.fGPSTrack )
1189
1190 , fGPSImgDirectionRef (tcGPSImgDirectionRef, exif.fGPSImgDirectionRef)
1191 , fGPSImgDirection (tcGPSImgDirection , exif.fGPSImgDirection )
1192
1193 , fGPSMapDatum (tcGPSMapDatum, exif.fGPSMapDatum)
1194
1195 , fGPSDestLatitudeRef (tcGPSDestLatitudeRef, exif.fGPSDestLatitudeRef)
1196 , fGPSDestLatitude (tcGPSDestLatitude, exif.fGPSDestLatitude, 3)
1197
1198 , fGPSDestLongitudeRef (tcGPSDestLongitudeRef, exif.fGPSDestLongitudeRef)
1199 , fGPSDestLongitude (tcGPSDestLongitude, exif.fGPSDestLongitude, 3)
1200
1201 , fGPSDestBearingRef (tcGPSDestBearingRef, exif.fGPSDestBearingRef)
1202 , fGPSDestBearing (tcGPSDestBearing , exif.fGPSDestBearing )
1203
1204 , fGPSDestDistanceRef (tcGPSDestDistanceRef, exif.fGPSDestDistanceRef)
1205 , fGPSDestDistance (tcGPSDestDistance , exif.fGPSDestDistance )
1206
1207 , fGPSProcessingMethod (tcGPSProcessingMethod, exif.fGPSProcessingMethod)
1208 , fGPSAreaInformation (tcGPSAreaInformation , exif.fGPSAreaInformation )
1209
1210 , fGPSDateStamp (tcGPSDateStamp, exif.fGPSDateStamp)
1211
1212 , fGPSDifferential (tcGPSDifferential, (uint16) exif.fGPSDifferential)
1213
1214 , fGPSHPositioningError (tcGPSHPositioningError, exif.fGPSHPositioningError)
1215
1216 {
1217
1218 if (exif.fExifVersion)
1219 {
1220
1221 fExifVersionData [0] = (uint8) (exif.fExifVersion >> 24);
1222 fExifVersionData [1] = (uint8) (exif.fExifVersion >> 16);
1223 fExifVersionData [2] = (uint8) (exif.fExifVersion >> 8);
1224 fExifVersionData [3] = (uint8) (exif.fExifVersion );
1225
1226 fExifIFD.Add (&fExifVersion);
1227
1228 }
1229
1230 if (exif.fExposureTime.IsValid ())
1231 {
1232 fExifIFD.Add (&fExposureTime);
1233 }
1234
1235 if (exif.fShutterSpeedValue.IsValid ())
1236 {
1237 fExifIFD.Add (&fShutterSpeedValue);
1238 }
1239
1240 if (exif.fFNumber.IsValid ())
1241 {
1242 fExifIFD.Add (&fFNumber);
1243 }
1244
1245 if (exif.fApertureValue.IsValid ())
1246 {
1247 fExifIFD.Add (&fApertureValue);
1248 }
1249
1250 if (exif.fBrightnessValue.IsValid ())
1251 {
1252 fExifIFD.Add (&fBrightnessValue);
1253 }
1254
1255 if (exif.fExposureBiasValue.IsValid ())
1256 {
1257 fExifIFD.Add (&fExposureBiasValue);
1258 }
1259
1260 if (exif.fMaxApertureValue.IsValid ())
1261 {
1262 fExifIFD.Add (&fMaxApertureValue);
1263 }
1264
1265 if (exif.fSubjectDistance.IsValid ())
1266 {
1267 fExifIFD.Add (&fSubjectDistance);
1268 }
1269
1270 if (exif.fFocalLength.IsValid ())
1271 {
1272 fExifIFD.Add (&fFocalLength);
1273 }
1274
1275 if (exif.fISOSpeedRatings [0] != 0)
1276 {
1277 fExifIFD.Add (&fISOSpeedRatings);
1278 }
1279
1280 if (exif.fFlash <= 0x0FFFF)
1281 {
1282 fExifIFD.Add (&fFlash);
1283 }
1284
1285 if (exif.fExposureProgram <= 0x0FFFF)
1286 {
1287 fExifIFD.Add (&fExposureProgram);
1288 }
1289
1290 if (exif.fMeteringMode <= 0x0FFFF)
1291 {
1292 fExifIFD.Add (&fMeteringMode);
1293 }
1294
1295 if (exif.fLightSource <= 0x0FFFF)
1296 {
1297 fExifIFD.Add (&fLightSource);
1298 }
1299
1300 if (exif.fSensingMethod <= 0x0FFFF)
1301 {
1302 fExifIFD.Add (&fSensingMethod);
1303 }
1304
1305 if (exif.fFocalLengthIn35mmFilm != 0)
1306 {
1307 fExifIFD.Add (&fFocalLength35mm);
1308 }
1309
1310 if (exif.fFileSource <= 0x0FF)
1311 {
1312 fExifIFD.Add (&fFileSource);
1313 }
1314
1315 if (exif.fSceneType <= 0x0FF)
1316 {
1317 fExifIFD.Add (&fSceneType);
1318 }
1319
1320 if (exif.fCFARepeatPatternRows &&
1321 exif.fCFARepeatPatternCols)
1322 {
1323 fExifIFD.Add (&fCFAPattern);
1324 }
1325
1326 if (exif.fCustomRendered <= 0x0FFFF)
1327 {
1328 fExifIFD.Add (&fCustomRendered);
1329 }
1330
1331 if (exif.fExposureMode <= 0x0FFFF)
1332 {
1333 fExifIFD.Add (&fExposureMode);
1334 }
1335
1336 if (exif.fWhiteBalance <= 0x0FFFF)
1337 {
1338 fExifIFD.Add (&fWhiteBalance);
1339 }
1340
1341 if (exif.fSceneCaptureType <= 0x0FFFF)
1342 {
1343 fExifIFD.Add (&fSceneCaptureType);
1344 }
1345
1346 if (exif.fGainControl <= 0x0FFFF)
1347 {
1348 fExifIFD.Add (&fGainControl);
1349 }
1350
1351 if (exif.fContrast <= 0x0FFFF)
1352 {
1353 fExifIFD.Add (&fContrast);
1354 }
1355
1356 if (exif.fSaturation <= 0x0FFFF)
1357 {
1358 fExifIFD.Add (&fSaturation);
1359 }
1360
1361 if (exif.fSharpness <= 0x0FFFF)
1362 {
1363 fExifIFD.Add (&fSharpness);
1364 }
1365
1366 if (exif.fSubjectDistanceRange <= 0x0FFFF)
1367 {
1368 fExifIFD.Add (&fSubjectDistanceRange);
1369 }
1370
1371 if (exif.fDigitalZoomRatio.IsValid ())
1372 {
1373 fExifIFD.Add (&fDigitalZoomRatio);
1374 }
1375
1376 if (exif.fExposureIndex.IsValid ())
1377 {
1378 fExifIFD.Add (&fExposureIndex);
1379 }
1380
1381 if (insideDNG) // TIFF-EP only tags
1382 {
1383
1384 if (exif.fImageNumber != 0xFFFFFFFF)
1385 {
1386 directory.Add (&fImageNumber);
1387 }
1388
1389 if (exif.fSelfTimerMode <= 0x0FFFF)
1390 {
1391 directory.Add (&fSelfTimerMode);
1392 }
1393
1394 if (exif.fBatteryLevelA.NotEmpty ())
1395 {
1396 directory.Add (&fBatteryLevelA);
1397 }
1398
1399 else if (exif.fBatteryLevelR.IsValid ())
1400 {
1401 directory.Add (&fBatteryLevelR);
1402 }
1403
1404 }
1405
1406 if (exif.fColorSpace == 1 ||
1407 exif.fColorSpace == 0xFFFF)
1408 {
1409 fExifIFD.Add (&fColorSpace);
1410 }
1411
1412 if (exif.fFocalPlaneXResolution.IsValid ())
1413 {
1414 fExifIFD.Add (&fFocalPlaneXResolution);
1415 }
1416
1417 if (exif.fFocalPlaneYResolution.IsValid ())
1418 {
1419 fExifIFD.Add (&fFocalPlaneYResolution);
1420 }
1421
1422 if (exif.fFocalPlaneResolutionUnit <= 0x0FFFF)
1423 {
1424 fExifIFD.Add (&fFocalPlaneResolutionUnit);
1425 }
1426
1427 if (exif.fSubjectAreaCount)
1428 {
1429
1430 fSubjectAreaData [0] = (uint16) exif.fSubjectArea [0];
1431 fSubjectAreaData [1] = (uint16) exif.fSubjectArea [1];
1432 fSubjectAreaData [2] = (uint16) exif.fSubjectArea [2];
1433 fSubjectAreaData [3] = (uint16) exif.fSubjectArea [3];
1434
1435 fExifIFD.Add (&fSubjectArea);
1436
1437 }
1438
1439 if (exif.fLensInfo [0].IsValid () &&
1440 exif.fLensInfo [1].IsValid ())
1441 {
1442
1443 fLensInfoData [0] = exif.fLensInfo [0];
1444 fLensInfoData [1] = exif.fLensInfo [1];
1445 fLensInfoData [2] = exif.fLensInfo [2];
1446 fLensInfoData [3] = exif.fLensInfo [3];
1447
1448 if (insideDNG)
1449 {
1450 directory.Add (&fLensInfo);
1451 }
1452
1453 }
1454
1455 if (exif.fDateTime.IsValid ())
1456 {
1457
1458 directory.Add (&fDateTime);
1459
1460 if (exif.fDateTime.Subseconds ().NotEmpty ())
1461 {
1462 fExifIFD.Add (&fSubsecTime);
1463 }
1464
1465 }
1466
1467 if (exif.fDateTimeOriginal.IsValid ())
1468 {
1469
1470 fExifIFD.Add (&fDateTimeOriginal);
1471
1472 if (exif.fDateTimeOriginal.Subseconds ().NotEmpty ())
1473 {
1474 fExifIFD.Add (&fSubsecTimeOriginal);
1475 }
1476
1477 }
1478
1479 if (exif.fDateTimeDigitized.IsValid ())
1480 {
1481
1482 fExifIFD.Add (&fDateTimeDigitized);
1483
1484 if (exif.fDateTimeDigitized.Subseconds ().NotEmpty ())
1485 {
1486 fExifIFD.Add (&fSubsecTimeDigitized);
1487 }
1488
1489 }
1490
1491 if (exif.fMake.NotEmpty ())
1492 {
1493 directory.Add (&fMake);
1494 }
1495
1496 if (exif.fModel.NotEmpty ())
1497 {
1498 directory.Add (&fModel);
1499 }
1500
1501 if (exif.fArtist.NotEmpty ())
1502 {
1503 directory.Add (&fArtist);
1504 }
1505
1506 if (exif.fSoftware.NotEmpty ())
1507 {
1508 directory.Add (&fSoftware);
1509 }
1510
1511 if (exif.fCopyright.NotEmpty ())
1512 {
1513 directory.Add (&fCopyright);
1514 }
1515
1516 if (exif.fImageDescription.NotEmpty ())
1517 {
1518 directory.Add (&fImageDescription);
1519 }
1520
1521 if (exif.fCameraSerialNumber.NotEmpty () && insideDNG)
1522 {
1523 directory.Add (&fSerialNumber);
1524 }
1525
1526 if (makerNoteSafe && makerNoteData)
1527 {
1528
1529 directory.Add (&fMakerNoteSafety);
1530
1531 fExifIFD.Add (&fMakerNote);
1532
1533 }
1534
1535 if (exif.fUserComment.NotEmpty ())
1536 {
1537 fExifIFD.Add (&fUserComment);
1538 }
1539
1540 if (exif.fImageUniqueID.IsValid ())
1541 {
1542
1543 for (uint32 j = 0; j < 16; j++)
1544 {
1545
1546 snprintf (fImageUniqueIDData + j * 2,
1547 33,
1548 "%02X",
1549 (unsigned) exif.fImageUniqueID.data [j]);
1550
1551 }
1552
1553 fExifIFD.Add (&fImageUniqueID);
1554
1555 }
1556
1557 if (exif.AtLeastVersion0230 ())
1558 {
1559
1560 if (exif.fSensitivityType != 0)
1561 {
1562
1563 fExifIFD.Add (&fSensitivityType);
1564
1565 }
1566
1567 // Sensitivity tags. Do not write these extra tags unless the SensitivityType
1568 // and PhotographicSensitivity (i.e., ISOSpeedRatings) values are valid.
1569
1570 if (exif.fSensitivityType != 0 &&
1571 exif.fISOSpeedRatings [0] != 0)
1572 {
1573
1574 // Standard Output Sensitivity (SOS).
1575
1576 if (exif.fStandardOutputSensitivity != 0)
1577 {
1578 fExifIFD.Add (&fStandardOutputSensitivity);
1579 }
1580
1581 // Recommended Exposure Index (REI).
1582
1583 if (exif.fRecommendedExposureIndex != 0)
1584 {
1585 fExifIFD.Add (&fRecommendedExposureIndex);
1586 }
1587
1588 // ISO Speed.
1589
1590 if (exif.fISOSpeed != 0)
1591 {
1592
1593 fExifIFD.Add (&fISOSpeed);
1594
1595 if (exif.fISOSpeedLatitudeyyy != 0 &&
1596 exif.fISOSpeedLatitudezzz != 0)
1597 {
1598
1599 fExifIFD.Add (&fISOSpeedLatitudeyyy);
1600 fExifIFD.Add (&fISOSpeedLatitudezzz);
1601
1602 }
1603
1604 }
1605
1606 }
1607
1608 if (exif.fOwnerName.NotEmpty ())
1609 {
1610 fExifIFD.Add (&fCameraOwnerName);
1611 }
1612
1613 if (exif.fCameraSerialNumber.NotEmpty ())
1614 {
1615 fExifIFD.Add (&fBodySerialNumber);
1616 }
1617
1618 if (exif.fLensInfo [0].IsValid () &&
1619 exif.fLensInfo [1].IsValid ())
1620 {
1621 fExifIFD.Add (&fLensSpecification);
1622 }
1623
1624 if (exif.fLensMake.NotEmpty ())
1625 {
1626 fExifIFD.Add (&fLensMake);
1627 }
1628
1629 if (exif.fLensName.NotEmpty ())
1630 {
1631 fExifIFD.Add (&fLensModel);
1632 }
1633
1634 if (exif.fLensSerialNumber.NotEmpty ())
1635 {
1636 fExifIFD.Add (&fLensSerialNumber);
1637 }
1638
1639 }
1640
1641 if (exif.AtLeastVersion0231 ())
1642 {
1643
1644 if (exif.fDateTime.IsValid () &&
1645 exif.fDateTime.TimeZone ().IsValid ())
1646 {
1647 fExifIFD.Add (&fOffsetTime);
1648 }
1649
1650 if (exif.fDateTimeOriginal.IsValid () &&
1651 exif.fDateTimeOriginal.TimeZone ().IsValid ())
1652 {
1653 fExifIFD.Add (&fOffsetTimeOriginal);
1654 }
1655
1656 if (exif.fDateTimeDigitized.IsValid () &&
1657 exif.fDateTimeDigitized.TimeZone ().IsValid ())
1658 {
1659 fExifIFD.Add (&fOffsetTimeDigitized);
1660 }
1661
1662 if (exif.fTemperature.IsValid ())
1663 {
1664 fExifIFD.Add (&fTemperature);
1665 }
1666
1667 if (exif.fHumidity.IsValid ())
1668 {
1669 fExifIFD.Add (&fHumidity);
1670 }
1671
1672 if (exif.fPressure.IsValid ())
1673 {
1674 fExifIFD.Add (&fPressure);
1675 }
1676
1677 if (exif.fWaterDepth.IsValid ())
1678 {
1679 fExifIFD.Add (&fWaterDepth);
1680 }
1681
1682 if (exif.fAcceleration.IsValid ())
1683 {
1684 fExifIFD.Add (&fAcceleration);
1685 }
1686
1687 if (exif.fCameraElevationAngle.IsValid ())
1688 {
1689 fExifIFD.Add (&fCameraElevationAngle);
1690 }
1691
1692 }
1693
1694 if (exif.fGPSVersionID)
1695 {
1696
1697 fGPSVersionData [0] = (uint8) (exif.fGPSVersionID >> 24);
1698 fGPSVersionData [1] = (uint8) (exif.fGPSVersionID >> 16);
1699 fGPSVersionData [2] = (uint8) (exif.fGPSVersionID >> 8);
1700 fGPSVersionData [3] = (uint8) (exif.fGPSVersionID );
1701
1702 fGPSIFD.Add (&fGPSVersionID);
1703
1704 }
1705
1706 if (exif.fGPSLatitudeRef.NotEmpty () &&
1707 exif.fGPSLatitude [0].IsValid ())
1708 {
1709 fGPSIFD.Add (&fGPSLatitudeRef);
1710 fGPSIFD.Add (&fGPSLatitude );
1711 }
1712
1713 if (exif.fGPSLongitudeRef.NotEmpty () &&
1714 exif.fGPSLongitude [0].IsValid ())
1715 {
1716 fGPSIFD.Add (&fGPSLongitudeRef);
1717 fGPSIFD.Add (&fGPSLongitude );
1718 }
1719
1720 if (exif.fGPSAltitudeRef <= 0x0FF)
1721 {
1722 fGPSIFD.Add (&fGPSAltitudeRef);
1723 }
1724
1725 if (exif.fGPSAltitude.IsValid ())
1726 {
1727 fGPSIFD.Add (&fGPSAltitude);
1728 }
1729
1730 if (exif.fGPSTimeStamp [0].IsValid ())
1731 {
1732 fGPSIFD.Add (&fGPSTimeStamp);
1733 }
1734
1735 if (exif.fGPSSatellites.NotEmpty ())
1736 {
1737 fGPSIFD.Add (&fGPSSatellites);
1738 }
1739
1740 if (exif.fGPSStatus.NotEmpty ())
1741 {
1742 fGPSIFD.Add (&fGPSStatus);
1743 }
1744
1745 if (exif.fGPSMeasureMode.NotEmpty ())
1746 {
1747 fGPSIFD.Add (&fGPSMeasureMode);
1748 }
1749
1750 if (exif.fGPSDOP.IsValid ())
1751 {
1752 fGPSIFD.Add (&fGPSDOP);
1753 }
1754
1755 if (exif.fGPSSpeedRef.NotEmpty ())
1756 {
1757 fGPSIFD.Add (&fGPSSpeedRef);
1758 }
1759
1760 if (exif.fGPSSpeed.IsValid ())
1761 {
1762 fGPSIFD.Add (&fGPSSpeed);
1763 }
1764
1765 if (exif.fGPSTrackRef.NotEmpty ())
1766 {
1767 fGPSIFD.Add (&fGPSTrackRef);
1768 }
1769
1770 if (exif.fGPSTrack.IsValid ())
1771 {
1772 fGPSIFD.Add (&fGPSTrack);
1773 }
1774
1775 if (exif.fGPSImgDirectionRef.NotEmpty ())
1776 {
1777 fGPSIFD.Add (&fGPSImgDirectionRef);
1778 }
1779
1780 if (exif.fGPSImgDirection.IsValid ())
1781 {
1782 fGPSIFD.Add (&fGPSImgDirection);
1783 }
1784
1785 if (exif.fGPSMapDatum.NotEmpty ())
1786 {
1787 fGPSIFD.Add (&fGPSMapDatum);
1788 }
1789
1790 if (exif.fGPSDestLatitudeRef.NotEmpty () &&
1791 exif.fGPSDestLatitude [0].IsValid ())
1792 {
1793 fGPSIFD.Add (&fGPSDestLatitudeRef);
1794 fGPSIFD.Add (&fGPSDestLatitude );
1795 }
1796
1797 if (exif.fGPSDestLongitudeRef.NotEmpty () &&
1798 exif.fGPSDestLongitude [0].IsValid ())
1799 {
1800 fGPSIFD.Add (&fGPSDestLongitudeRef);
1801 fGPSIFD.Add (&fGPSDestLongitude );
1802 }
1803
1804 if (exif.fGPSDestBearingRef.NotEmpty ())
1805 {
1806 fGPSIFD.Add (&fGPSDestBearingRef);
1807 }
1808
1809 if (exif.fGPSDestBearing.IsValid ())
1810 {
1811 fGPSIFD.Add (&fGPSDestBearing);
1812 }
1813
1814 if (exif.fGPSDestDistanceRef.NotEmpty ())
1815 {
1816 fGPSIFD.Add (&fGPSDestDistanceRef);
1817 }
1818
1819 if (exif.fGPSDestDistance.IsValid ())
1820 {
1821 fGPSIFD.Add (&fGPSDestDistance);
1822 }
1823
1824 if (exif.fGPSProcessingMethod.NotEmpty ())
1825 {
1826 fGPSIFD.Add (&fGPSProcessingMethod);
1827 }
1828
1829 if (exif.fGPSAreaInformation.NotEmpty ())
1830 {
1831 fGPSIFD.Add (&fGPSAreaInformation);
1832 }
1833
1834 if (exif.fGPSDateStamp.NotEmpty ())
1835 {
1836 fGPSIFD.Add (&fGPSDateStamp);
1837 }
1838
1839 if (exif.fGPSDifferential <= 0x0FFFF)
1840 {
1841 fGPSIFD.Add (&fGPSDifferential);
1842 }
1843
1844 if (exif.AtLeastVersion0230 ())
1845 {
1846
1847 if (exif.fGPSHPositioningError.IsValid ())
1848 {
1849 fGPSIFD.Add (&fGPSHPositioningError);
1850 }
1851
1852 }
1853
1854 AddLinks (directory);
1855
1856 }
1857
1858 /******************************************************************************/
1859
1860 void exif_tag_set::AddLinks (dng_tiff_directory &directory)
1861 {
1862
1863 if (fExifIFD.Size () != 0 && !fAddedExifLink)
1864 {
1865
1866 directory.Add (&fExifLink);
1867
1868 fAddedExifLink = true;
1869
1870 }
1871
1872 if (fGPSIFD.Size () != 0 && !fAddedGPSLink)
1873 {
1874
1875 directory.Add (&fGPSLink);
1876
1877 fAddedGPSLink = true;
1878
1879 }
1880
1881 }
1882
1883 /******************************************************************************/
1884
1885 class range_tag_set
1886 {
1887
1888 private:
1889
1890 uint32 fActiveAreaData [4];
1891
1892 tag_uint32_ptr fActiveArea;
1893
1894 uint32 fMaskedAreaData [kMaxMaskedAreas * 4];
1895
1896 tag_uint32_ptr fMaskedAreas;
1897
1898 tag_uint16_ptr fLinearizationTable;
1899
1900 uint16 fBlackLevelRepeatDimData [2];
1901
1902 tag_uint16_ptr fBlackLevelRepeatDim;
1903
1904 dng_urational fBlackLevelData [kMaxBlackPattern *
1905 kMaxBlackPattern *
1906 kMaxColorPlanes];
1907
1908 tag_urational_ptr fBlackLevel;
1909
1910 dng_memory_data fBlackLevelDeltaHData;
1911 dng_memory_data fBlackLevelDeltaVData;
1912
1913 tag_srational_ptr fBlackLevelDeltaH;
1914 tag_srational_ptr fBlackLevelDeltaV;
1915
1916 uint16 fWhiteLevelData16 [kMaxColorPlanes];
1917 uint32 fWhiteLevelData32 [kMaxColorPlanes];
1918
1919 tag_uint16_ptr fWhiteLevel16;
1920 tag_uint32_ptr fWhiteLevel32;
1921
1922 public:
1923
1924 range_tag_set (dng_tiff_directory &directory,
1925 const dng_negative &negative);
1926
1927 };
1928
1929 /******************************************************************************/
1930
1931 range_tag_set::range_tag_set (dng_tiff_directory &directory,
1932 const dng_negative &negative)
1933
1934 : fActiveArea (tcActiveArea,
1935 fActiveAreaData,
1936 4)
1937
1938 , fMaskedAreas (tcMaskedAreas,
1939 fMaskedAreaData,
1940 0)
1941
1942 , fLinearizationTable (tcLinearizationTable,
1943 NULL,
1944 0)
1945
1946 , fBlackLevelRepeatDim (tcBlackLevelRepeatDim,
1947 fBlackLevelRepeatDimData,
1948 2)
1949
1950 , fBlackLevel (tcBlackLevel,
1951 fBlackLevelData)
1952
1953 , fBlackLevelDeltaHData ()
1954 , fBlackLevelDeltaVData ()
1955
1956 , fBlackLevelDeltaH (tcBlackLevelDeltaH)
1957 , fBlackLevelDeltaV (tcBlackLevelDeltaV)
1958
1959 , fWhiteLevel16 (tcWhiteLevel,
1960 fWhiteLevelData16)
1961
1962 , fWhiteLevel32 (tcWhiteLevel,
1963 fWhiteLevelData32)
1964
1965 {
1966
1967 const dng_image &rawImage (negative.RawImage ());
1968
1969 const dng_linearization_info *rangeInfo = negative.GetLinearizationInfo ();
1970
1971 if (rangeInfo)
1972 {
1973
1974 // ActiveArea:
1975
1976 {
1977
1978 const dng_rect &r = rangeInfo->fActiveArea;
1979
1980 if (r.NotEmpty ())
1981 {
1982
1983 fActiveAreaData [0] = r.t;
1984 fActiveAreaData [1] = r.l;
1985 fActiveAreaData [2] = r.b;
1986 fActiveAreaData [3] = r.r;
1987
1988 directory.Add (&fActiveArea);
1989
1990 }
1991
1992 }
1993
1994 // MaskedAreas:
1995
1996 if (rangeInfo->fMaskedAreaCount)
1997 {
1998
1999 fMaskedAreas.SetCount (rangeInfo->fMaskedAreaCount * 4);
2000
2001 for (uint32 index = 0; index < rangeInfo->fMaskedAreaCount; index++)
2002 {
2003
2004 const dng_rect &r = rangeInfo->fMaskedArea [index];
2005
2006 fMaskedAreaData [index * 4 + 0] = r.t;
2007 fMaskedAreaData [index * 4 + 1] = r.l;
2008 fMaskedAreaData [index * 4 + 2] = r.b;
2009 fMaskedAreaData [index * 4 + 3] = r.r;
2010
2011 }
2012
2013 directory.Add (&fMaskedAreas);
2014
2015 }
2016
2017 // LinearizationTable:
2018
2019 if (rangeInfo->fLinearizationTable.Get ())
2020 {
2021
2022 fLinearizationTable.SetData (rangeInfo->fLinearizationTable->Buffer_uint16 () );
2023 fLinearizationTable.SetCount (rangeInfo->fLinearizationTable->LogicalSize () >> 1);
2024
2025 directory.Add (&fLinearizationTable);
2026
2027 }
2028
2029 // BlackLevelRepeatDim:
2030
2031 {
2032
2033 fBlackLevelRepeatDimData [0] = (uint16) rangeInfo->fBlackLevelRepeatRows;
2034 fBlackLevelRepeatDimData [1] = (uint16) rangeInfo->fBlackLevelRepeatCols;
2035
2036 directory.Add (&fBlackLevelRepeatDim);
2037
2038 }
2039
2040 // BlackLevel:
2041
2042 {
2043
2044 uint32 index = 0;
2045
2046 for (uint16 v = 0; v < rangeInfo->fBlackLevelRepeatRows; v++)
2047 {
2048
2049 for (uint32 h = 0; h < rangeInfo->fBlackLevelRepeatCols; h++)
2050 {
2051
2052 for (uint32 c = 0; c < rawImage.Planes (); c++)
2053 {
2054
2055 fBlackLevelData [index++] = rangeInfo->BlackLevel (v, h, c);
2056
2057 }
2058
2059 }
2060
2061 }
2062
2063 fBlackLevel.SetCount (rangeInfo->fBlackLevelRepeatRows *
2064 rangeInfo->fBlackLevelRepeatCols * rawImage.Planes ());
2065
2066 directory.Add (&fBlackLevel);
2067
2068 }
2069
2070 // BlackLevelDeltaH:
2071
2072 if (rangeInfo->ColumnBlackCount ())
2073 {
2074
2075 uint32 count = rangeInfo->ColumnBlackCount ();
2076
2077 fBlackLevelDeltaHData.Allocate (count, sizeof (dng_srational));
2078
2079 dng_srational *blacks = (dng_srational *) fBlackLevelDeltaHData.Buffer ();
2080
2081 for (uint32 col = 0; col < count; col++)
2082 {
2083
2084 blacks [col] = rangeInfo->ColumnBlack (col);
2085
2086 }
2087
2088 fBlackLevelDeltaH.SetData (blacks);
2089 fBlackLevelDeltaH.SetCount (count );
2090
2091 directory.Add (&fBlackLevelDeltaH);
2092
2093 }
2094
2095 // BlackLevelDeltaV:
2096
2097 if (rangeInfo->RowBlackCount ())
2098 {
2099
2100 uint32 count = rangeInfo->RowBlackCount ();
2101
2102 fBlackLevelDeltaVData.Allocate (count, sizeof (dng_srational));
2103
2104 dng_srational *blacks = (dng_srational *) fBlackLevelDeltaVData.Buffer ();
2105
2106 for (uint32 row = 0; row < count; row++)
2107 {
2108
2109 blacks [row] = rangeInfo->RowBlack (row);
2110
2111 }
2112
2113 fBlackLevelDeltaV.SetData (blacks);
2114 fBlackLevelDeltaV.SetCount (count );
2115
2116 directory.Add (&fBlackLevelDeltaV);
2117
2118 }
2119
2120 }
2121
2122 else if (negative.RawImageBlackLevel ())
2123 {
2124
2125 for (uint32 c = 0; c < rawImage.Planes (); c++)
2126 {
2127
2128 fBlackLevelData [c] = dng_urational (negative.RawImageBlackLevel (), 1);
2129
2130 }
2131
2132 fBlackLevel.SetCount (rawImage.Planes ());
2133
2134 directory.Add (&fBlackLevel);
2135
2136 }
2137
2138 // WhiteLevel:
2139
2140 // Only use the 32-bit data type if we must use it since there
2141 // are some lazy (non-Adobe) DNG readers out there.
2142
2143 bool needs32 = false;
2144
2145 fWhiteLevel16.SetCount (rawImage.Planes ());
2146 fWhiteLevel32.SetCount (rawImage.Planes ());
2147
2148 for (uint32 c = 0; c < fWhiteLevel16.Count (); c++)
2149 {
2150
2151 fWhiteLevelData32 [c] = negative.WhiteLevel (c);
2152
2153 if (fWhiteLevelData32 [c] > 0x0FFFF)
2154 {
2155 needs32 = true;
2156 }
2157
2158 fWhiteLevelData16 [c] = (uint16) fWhiteLevelData32 [c];
2159
2160 }
2161
2162 if (needs32)
2163 {
2164 directory.Add (&fWhiteLevel32);
2165 }
2166
2167 else
2168 {
2169 directory.Add (&fWhiteLevel16);
2170 }
2171
2172 }
2173
2174 /******************************************************************************/
2175
2176 class mosaic_tag_set
2177 {
2178
2179 private:
2180
2181 uint16 fCFARepeatPatternDimData [2];
2182
2183 tag_uint16_ptr fCFARepeatPatternDim;
2184
2185 uint8 fCFAPatternData [kMaxCFAPattern *
2186 kMaxCFAPattern];
2187
2188 tag_uint8_ptr fCFAPattern;
2189
2190 uint8 fCFAPlaneColorData [kMaxColorPlanes];
2191
2192 tag_uint8_ptr fCFAPlaneColor;
2193
2194 tag_uint16 fCFALayout;
2195
2196 tag_uint32 fGreenSplit;
2197
2198 public:
2199
2200 mosaic_tag_set (dng_tiff_directory &directory,
2201 const dng_mosaic_info &info);
2202
2203 };
2204
2205 /******************************************************************************/
2206
2207 mosaic_tag_set::mosaic_tag_set (dng_tiff_directory &directory,
2208 const dng_mosaic_info &info)
2209
2210 : fCFARepeatPatternDim (tcCFARepeatPatternDim,
2211 fCFARepeatPatternDimData,
2212 2)
2213
2214 , fCFAPattern (tcCFAPattern,
2215 fCFAPatternData)
2216
2217 , fCFAPlaneColor (tcCFAPlaneColor,
2218 fCFAPlaneColorData)
2219
2220 , fCFALayout (tcCFALayout,
2221 (uint16) info.fCFALayout)
2222
2223 , fGreenSplit (tcBayerGreenSplit,
2224 info.fBayerGreenSplit)
2225
2226 {
2227
2228 if (info.IsColorFilterArray ())
2229 {
2230
2231 // CFARepeatPatternDim:
2232
2233 fCFARepeatPatternDimData [0] = (uint16) info.fCFAPatternSize.v;
2234 fCFARepeatPatternDimData [1] = (uint16) info.fCFAPatternSize.h;
2235
2236 directory.Add (&fCFARepeatPatternDim);
2237
2238 // CFAPattern:
2239
2240 fCFAPattern.SetCount (info.fCFAPatternSize.v *
2241 info.fCFAPatternSize.h);
2242
2243 for (int32 r = 0; r < info.fCFAPatternSize.v; r++)
2244 {
2245
2246 for (int32 c = 0; c < info.fCFAPatternSize.h; c++)
2247 {
2248
2249 fCFAPatternData [r * info.fCFAPatternSize.h + c] = info.fCFAPattern [r] [c];
2250
2251 }
2252
2253 }
2254
2255 directory.Add (&fCFAPattern);
2256
2257 // CFAPlaneColor:
2258
2259 fCFAPlaneColor.SetCount (info.fColorPlanes);
2260
2261 for (uint32 j = 0; j < info.fColorPlanes; j++)
2262 {
2263
2264 fCFAPlaneColorData [j] = info.fCFAPlaneColor [j];
2265
2266 }
2267
2268 directory.Add (&fCFAPlaneColor);
2269
2270 // CFALayout:
2271
2272 fCFALayout.Set ((uint16) info.fCFALayout);
2273
2274 directory.Add (&fCFALayout);
2275
2276 // BayerGreenSplit: (only include if the pattern is a Bayer pattern)
2277
2278 if (info.fCFAPatternSize == dng_point (2, 2) &&
2279 info.fColorPlanes == 3)
2280 {
2281
2282 directory.Add (&fGreenSplit);
2283
2284 }
2285
2286 }
2287
2288 }
2289
2290 /******************************************************************************/
2291
2292 class color_tag_set
2293 {
2294
2295 private:
2296
2297 uint32 fColorChannels;
2298
2299 tag_matrix fCameraCalibration1;
2300 tag_matrix fCameraCalibration2;
2301 tag_matrix fCameraCalibration3;
2302
2303 tag_string fCameraCalibrationSignature;
2304
2305 tag_string fAsShotProfileName;
2306
2307 dng_urational fAnalogBalanceData [4];
2308
2309 tag_urational_ptr fAnalogBalance;
2310
2311 dng_urational fAsShotNeutralData [4];
2312
2313 tag_urational_ptr fAsShotNeutral;
2314
2315 dng_urational fAsShotWhiteXYData [2];
2316
2317 tag_urational_ptr fAsShotWhiteXY;
2318
2319 tag_urational fLinearResponseLimit;
2320
2321 public:
2322
2323 color_tag_set (dng_tiff_directory &directory,
2324 const dng_negative &negative);
2325
2326 };
2327
2328 /******************************************************************************/
2329
2330 color_tag_set::color_tag_set (dng_tiff_directory &directory,
2331 const dng_negative &negative)
2332
2333 : fColorChannels (negative.ColorChannels ())
2334
2335 , fCameraCalibration1 (tcCameraCalibration1,
2336 negative.CameraCalibration1 ())
2337
2338 , fCameraCalibration2 (tcCameraCalibration2,
2339 negative.CameraCalibration2 ())
2340
2341 , fCameraCalibration3 (tcCameraCalibration3,
2342 negative.CameraCalibration3 ())
2343
2344 , fCameraCalibrationSignature (tcCameraCalibrationSignature,
2345 negative.CameraCalibrationSignature ())
2346
2347 , fAsShotProfileName (tcAsShotProfileName,
2348 negative.AsShotProfileName ())
2349
2350 , fAnalogBalance (tcAnalogBalance,
2351 fAnalogBalanceData,
2352 fColorChannels)
2353
2354 , fAsShotNeutral (tcAsShotNeutral,
2355 fAsShotNeutralData,
2356 fColorChannels)
2357
2358 , fAsShotWhiteXY (tcAsShotWhiteXY,
2359 fAsShotWhiteXYData,
2360 2)
2361
2362 , fLinearResponseLimit (tcLinearResponseLimit,
2363 negative.LinearResponseLimitR ())
2364
2365 {
2366
2367 if (fColorChannels > 1)
2368 {
2369
2370 uint32 channels2 = fColorChannels * fColorChannels;
2371
2372 if (fCameraCalibration1.Count () == channels2)
2373 {
2374
2375 directory.Add (&fCameraCalibration1);
2376
2377 }
2378
2379 if (fCameraCalibration2.Count () == channels2)
2380 {
2381
2382 directory.Add (&fCameraCalibration2);
2383
2384 }
2385
2386 if (fCameraCalibration3.Count () == channels2)
2387 {
2388
2389 directory.Add (&fCameraCalibration3);
2390
2391 }
2392
2393 if (fCameraCalibration1.Count () == channels2 ||
2394 fCameraCalibration2.Count () == channels2 ||
2395 fCameraCalibration3.Count () == channels2)
2396 {
2397
2398 if (negative.CameraCalibrationSignature ().NotEmpty ())
2399 {
2400
2401 directory.Add (&fCameraCalibrationSignature);
2402
2403 }
2404
2405 }
2406
2407 if (negative.AsShotProfileName ().NotEmpty ())
2408 {
2409
2410 directory.Add (&fAsShotProfileName);
2411
2412 }
2413
2414 for (uint32 j = 0; j < fColorChannels; j++)
2415 {
2416
2417 fAnalogBalanceData [j] = negative.AnalogBalanceR (j);
2418
2419 }
2420
2421 directory.Add (&fAnalogBalance);
2422
2423 if (negative.HasCameraNeutral ())
2424 {
2425
2426 for (uint32 k = 0; k < fColorChannels; k++)
2427 {
2428
2429 fAsShotNeutralData [k] = negative.CameraNeutralR (k);
2430
2431 }
2432
2433 directory.Add (&fAsShotNeutral);
2434
2435 }
2436
2437 else if (negative.HasCameraWhiteXY ())
2438 {
2439
2440 negative.GetCameraWhiteXY (fAsShotWhiteXYData [0],
2441 fAsShotWhiteXYData [1]);
2442
2443 directory.Add (&fAsShotWhiteXY);
2444
2445 }
2446
2447 directory.Add (&fLinearResponseLimit);
2448
2449 }
2450
2451 }
2452
2453 /******************************************************************************/
2454
2455 class profile_tag_set
2456 {
2457
2458 private:
2459
2460 tag_uint16 fCalibrationIlluminant1;
2461 tag_uint16 fCalibrationIlluminant2;
2462 tag_uint16 fCalibrationIlluminant3;
2463
2464 tag_data_ptr fIlluminantData1;
2465 tag_data_ptr fIlluminantData2;
2466 tag_data_ptr fIlluminantData3;
2467
2468 tag_matrix fColorMatrix1;
2469 tag_matrix fColorMatrix2;
2470 tag_matrix fColorMatrix3;
2471
2472 tag_matrix fForwardMatrix1;
2473 tag_matrix fForwardMatrix2;
2474 tag_matrix fForwardMatrix3;
2475
2476 tag_matrix fReductionMatrix1;
2477 tag_matrix fReductionMatrix2;
2478 tag_matrix fReductionMatrix3;
2479
2480 tag_string fProfileName;
2481 tag_string fProfileGroupName;
2482
2483 tag_string fProfileCalibrationSignature;
2484
2485 tag_uint32 fEmbedPolicyTag;
2486
2487 tag_string fCopyrightTag;
2488
2489 uint32 fHueSatMapDimData [3];
2490
2491 tag_uint32_ptr fHueSatMapDims;
2492
2493 tag_data_ptr fHueSatData1;
2494 tag_data_ptr fHueSatData2;
2495 tag_data_ptr fHueSatData3;
2496
2497 tag_uint32 fHueSatMapEncodingTag;
2498
2499 uint32 fLookTableDimData [3];
2500
2501 tag_uint32_ptr fLookTableDims;
2502
2503 tag_data_ptr fLookTableData;
2504
2505 tag_uint32 fLookTableEncodingTag;
2506
2507 tag_srational fBaselineExposureOffsetTag;
2508
2509 tag_uint32 fDefaultBlackRenderTag;
2510
2511 dng_memory_data fToneCurveBuffer;
2512
2513 tag_data_ptr fToneCurveTag;
2514
2515 tag_uint32 fToneMethodTag;
2516
2517 AutoPtr<dng_memory_block> fIlluminantBlock1;
2518 AutoPtr<dng_memory_block> fIlluminantBlock2;
2519 AutoPtr<dng_memory_block> fIlluminantBlock3;
2520
2521 AutoPtr<tag_owned_data_ptr> fProfileGainTableMapTag;
2522
2523 AutoPtr<tag_owned_data_ptr> fProfileDynamicRangeTag;
2524
2525 AutoPtr<tag_owned_data_ptr> fRGBTablesTag;
2526
2527 public:
2528
2529 profile_tag_set (dng_host &host,
2530 dng_tiff_directory &directory,
2531 const dng_camera_profile &profile);
2532
2533 };
2534
2535 /******************************************************************************/
2536
2537 profile_tag_set::profile_tag_set (dng_host &host,
2538 dng_tiff_directory &directory,
2539 const dng_camera_profile &profile)
2540
2541 : fCalibrationIlluminant1 (tcCalibrationIlluminant1,
2542 (uint16) profile.CalibrationIlluminant1 ())
2543
2544 , fCalibrationIlluminant2 (tcCalibrationIlluminant2,
2545 (uint16) profile.CalibrationIlluminant2 ())
2546
2547 , fCalibrationIlluminant3 (tcCalibrationIlluminant3,
2548 (uint16) profile.CalibrationIlluminant3 ())
2549
2550 , fIlluminantData1 (tcIlluminantData1,
2551 ttUndefined,
2552 profile.IlluminantData1 ().TagCount (),
2553 nullptr) // specify later
2554
2555 , fIlluminantData2 (tcIlluminantData2,
2556 ttUndefined,
2557 profile.IlluminantData2 ().TagCount (),
2558 nullptr) // specify later
2559
2560 , fIlluminantData3 (tcIlluminantData3,
2561 ttUndefined,
2562 profile.IlluminantData3 ().TagCount (),
2563 nullptr) // specify later
2564
2565 , fColorMatrix1 (tcColorMatrix1,
2566 profile.ColorMatrix1 ())
2567
2568 , fColorMatrix2 (tcColorMatrix2,
2569 profile.ColorMatrix2 ())
2570
2571 , fColorMatrix3 (tcColorMatrix3,
2572 profile.ColorMatrix3 ())
2573
2574 , fForwardMatrix1 (tcForwardMatrix1,
2575 profile.ForwardMatrix1 ())
2576
2577 , fForwardMatrix2 (tcForwardMatrix2,
2578 profile.ForwardMatrix2 ())
2579
2580 , fForwardMatrix3 (tcForwardMatrix3,
2581 profile.ForwardMatrix3 ())
2582
2583 , fReductionMatrix1 (tcReductionMatrix1,
2584 profile.ReductionMatrix1 ())
2585
2586 , fReductionMatrix2 (tcReductionMatrix2,
2587 profile.ReductionMatrix2 ())
2588
2589 , fReductionMatrix3 (tcReductionMatrix3,
2590 profile.ReductionMatrix3 ())
2591
2592 , fProfileName (tcProfileName,
2593 profile.Name (),
2594 false)
2595
2596 , fProfileGroupName (tcProfileGroupName,
2597 profile.GroupName (),
2598 false)
2599
2600 , fProfileCalibrationSignature (tcProfileCalibrationSignature,
2601 profile.ProfileCalibrationSignature (),
2602 false)
2603
2604 , fEmbedPolicyTag (tcProfileEmbedPolicy,
2605 profile.EmbedPolicy ())
2606
2607 , fCopyrightTag (tcProfileCopyright,
2608 profile.Copyright (),
2609 false)
2610
2611 , fHueSatMapDims (tcProfileHueSatMapDims,
2612 fHueSatMapDimData,
2613 3)
2614
2615 , fHueSatData1 (tcProfileHueSatMapData1,
2616 ttFloat,
2617 profile.HueSatDeltas1 ().DeltasCount () * 3,
2618 profile.HueSatDeltas1 ().GetConstDeltas ())
2619
2620 , fHueSatData2 (tcProfileHueSatMapData2,
2621 ttFloat,
2622 profile.HueSatDeltas2 ().DeltasCount () * 3,
2623 profile.HueSatDeltas2 ().GetConstDeltas ())
2624
2625 , fHueSatData3 (tcProfileHueSatMapData3,
2626 ttFloat,
2627 profile.HueSatDeltas3 ().DeltasCount () * 3,
2628 profile.HueSatDeltas3 ().GetConstDeltas ())
2629
2630 , fHueSatMapEncodingTag (tcProfileHueSatMapEncoding,
2631 profile.HueSatMapEncoding ())
2632
2633 , fLookTableDims (tcProfileLookTableDims,
2634 fLookTableDimData,
2635 3)
2636
2637 , fLookTableData (tcProfileLookTableData,
2638 ttFloat,
2639 profile.LookTable ().DeltasCount () * 3,
2640 profile.LookTable ().GetConstDeltas ())
2641
2642 , fLookTableEncodingTag (tcProfileLookTableEncoding,
2643 profile.LookTableEncoding ())
2644
2645 , fBaselineExposureOffsetTag (tcBaselineExposureOffset,
2646 profile.BaselineExposureOffset ())
2647
2648 , fDefaultBlackRenderTag (tcDefaultBlackRender,
2649 profile.DefaultBlackRender ())
2650
2651 , fToneCurveBuffer ()
2652
2653 , fToneCurveTag (tcProfileToneCurve,
2654 ttFloat,
2655 0,
2656 NULL)
2657
2658 , fToneMethodTag (tcProfileToneMethod,
2659 profile.ToneMethod ())
2660
2661 {
2662
2663 const uint32 illuminantModel = profile.IlluminantModel ();
2664
2665 const bool isTripleIlluminantModel = (illuminantModel == 3);
2666
2667 if (profile.HasColorMatrix1 ())
2668 {
2669
2670 uint32 colorChannels = profile.ColorMatrix1 ().Rows ();
2671
2672 directory.Add (&fCalibrationIlluminant1);
2673
2674 if (profile.CalibrationIlluminant1 () == lsOther &&
2675 profile.IlluminantData1 ().IsValid ())
2676 {
2677
2678 dng_memory_stream stream (host.Allocator ());
2679
2680 auto &tag = fIlluminantData1;
2681
2682 auto &block = fIlluminantBlock1;
2683
2684 profile.IlluminantData1 ().Put (stream);
2685
2686 block.Reset (stream.AsMemoryBlock (host.Allocator ()));
2687
2688 DNG_REQUIRE (block->LogicalSize () >= tag.Count (),
2689 "illuminant data block too small");
2690
2691 tag.SetData (block->Buffer ());
2692
2693 directory.Add (&tag);
2694
2695 }
2696
2697 directory.Add (&fColorMatrix1);
2698
2699 if (fForwardMatrix1.Count () == colorChannels * 3)
2700 {
2701
2702 directory.Add (&fForwardMatrix1);
2703
2704 }
2705
2706 if (colorChannels > 3 && fReductionMatrix1.Count () == colorChannels * 3)
2707 {
2708
2709 directory.Add (&fReductionMatrix1);
2710
2711 }
2712
2713 if (profile.HasColorMatrix2 ())
2714 {
2715
2716 directory.Add (&fCalibrationIlluminant2);
2717
2718 if (profile.CalibrationIlluminant2 () == lsOther &&
2719 profile.IlluminantData2 ().IsValid ())
2720 {
2721
2722 dng_memory_stream stream (host.Allocator ());
2723
2724 auto &tag = fIlluminantData2;
2725
2726 auto &block = fIlluminantBlock2;
2727
2728 profile.IlluminantData2 ().Put (stream);
2729
2730 block.Reset (stream.AsMemoryBlock (host.Allocator ()));
2731
2732 DNG_REQUIRE (block->LogicalSize () >= tag.Count (),
2733 "illuminant data block too small");
2734
2735 tag.SetData (block->Buffer ());
2736
2737 directory.Add (&tag);
2738
2739 }
2740
2741 directory.Add (&fColorMatrix2);
2742
2743 if (fForwardMatrix2.Count () == colorChannels * 3)
2744 {
2745
2746 directory.Add (&fForwardMatrix2);
2747
2748 }
2749
2750 if (colorChannels > 3 && fReductionMatrix2.Count () == colorChannels * 3)
2751 {
2752
2753 directory.Add (&fReductionMatrix2);
2754
2755 }
2756
2757 // Deal with 3rd illuminant.
2758
2759 if (isTripleIlluminantModel)
2760 {
2761
2762 directory.Add (&fCalibrationIlluminant3);
2763
2764 if (profile.CalibrationIlluminant3 () == lsOther &&
2765 profile.IlluminantData3 ().IsValid ())
2766 {
2767
2768 dng_memory_stream stream (host.Allocator ());
2769
2770 auto &tag = fIlluminantData3;
2771
2772 auto &block = fIlluminantBlock3;
2773
2774 profile.IlluminantData3 ().Put (stream);
2775
2776 block.Reset (stream.AsMemoryBlock (host.Allocator ()));
2777
2778 DNG_REQUIRE (block->LogicalSize () >= tag.Count (),
2779 "illuminant data block too small");
2780
2781 tag.SetData (block->Buffer ());
2782
2783 directory.Add (&tag);
2784
2785 }
2786
2787 directory.Add (&fColorMatrix3);
2788
2789 if (fForwardMatrix3.Count () == colorChannels * 3)
2790 {
2791
2792 directory.Add (&fForwardMatrix3);
2793
2794 }
2795
2796 if (colorChannels > 3 && fReductionMatrix3.Count () == colorChannels * 3)
2797 {
2798
2799 directory.Add (&fReductionMatrix3);
2800
2801 }
2802
2803 } // 3rd illuminant
2804
2805 }
2806
2807 if (profile.Name ().NotEmpty ())
2808 {
2809
2810 directory.Add (&fProfileName);
2811
2812 }
2813
2814 if (profile.GroupName ().NotEmpty ())
2815 {
2816
2817 directory.Add (&fProfileGroupName);
2818
2819 }
2820
2821 if (profile.ProfileCalibrationSignature ().NotEmpty ())
2822 {
2823
2824 directory.Add (&fProfileCalibrationSignature);
2825
2826 }
2827
2828 directory.Add (&fEmbedPolicyTag);
2829
2830 if (profile.Copyright ().NotEmpty ())
2831 {
2832
2833 directory.Add (&fCopyrightTag);
2834
2835 }
2836
2837 bool haveHueSat1 = profile.HueSatDeltas1 ().IsValid ();
2838
2839 bool haveHueSat2 = profile.HueSatDeltas2 ().IsValid () &&
2840 profile.HasColorMatrix2 ();
2841
2842 bool haveHueSat3 = isTripleIlluminantModel &&
2843 profile.HueSatDeltas3 ().IsValid ();
2844
2845 if (haveHueSat1 || haveHueSat2 || haveHueSat3)
2846 {
2847
2848 uint32 hueDivs = 0;
2849 uint32 satDivs = 0;
2850 uint32 valDivs = 0;
2851
2852 // Get the hue sat map dimensions. The following logic only checks
2853 // the first two hue sat maps. Per the DNG 1.6 spec it is invalid
2854 // to have a 3rd hue sat map unless the first two are both
2855 // present, so it's not necessary to check the 3rd.
2856
2857 if (haveHueSat1)
2858 {
2859
2860 profile.HueSatDeltas1 ().GetDivisions (hueDivs,
2861 satDivs,
2862 valDivs);
2863
2864 }
2865
2866 else
2867 {
2868
2869 profile.HueSatDeltas2 ().GetDivisions (hueDivs,
2870 satDivs,
2871 valDivs);
2872
2873 }
2874
2875 fHueSatMapDimData [0] = hueDivs;
2876 fHueSatMapDimData [1] = satDivs;
2877 fHueSatMapDimData [2] = valDivs;
2878
2879 directory.Add (&fHueSatMapDims);
2880
2881 // Don't bother including the ProfileHueSatMapEncoding tag unless it's
2882 // non-linear.
2883
2884 if (profile.HueSatMapEncoding () != encoding_Linear)
2885 {
2886
2887 directory.Add (&fHueSatMapEncodingTag);
2888
2889 }
2890
2891 }
2892
2893 if (haveHueSat1)
2894 {
2895
2896 directory.Add (&fHueSatData1);
2897
2898 }
2899
2900 if (haveHueSat2)
2901 {
2902
2903 directory.Add (&fHueSatData2);
2904
2905 }
2906
2907 if (haveHueSat3)
2908 {
2909
2910 directory.Add (&fHueSatData3);
2911
2912 }
2913
2914 if (profile.HasLookTable ())
2915 {
2916
2917 uint32 hueDivs = 0;
2918 uint32 satDivs = 0;
2919 uint32 valDivs = 0;
2920
2921 profile.LookTable ().GetDivisions (hueDivs,
2922 satDivs,
2923 valDivs);
2924
2925 fLookTableDimData [0] = hueDivs;
2926 fLookTableDimData [1] = satDivs;
2927 fLookTableDimData [2] = valDivs;
2928
2929 directory.Add (&fLookTableDims);
2930
2931 directory.Add (&fLookTableData);
2932
2933 // Don't bother including the ProfileLookTableEncoding tag unless it's
2934 // non-linear.
2935
2936 if (profile.LookTableEncoding () != encoding_Linear)
2937 {
2938
2939 directory.Add (&fLookTableEncodingTag);
2940
2941 }
2942
2943 }
2944
2945 // Don't bother including the BaselineExposureOffset tag unless it's both
2946 // valid and non-zero.
2947
2948 if (profile.BaselineExposureOffset ().IsValid ())
2949 {
2950
2951 if (profile.BaselineExposureOffset ().As_real64 () != 0.0)
2952 {
2953
2954 directory.Add (&fBaselineExposureOffsetTag);
2955
2956 }
2957
2958 }
2959
2960 if (profile.DefaultBlackRender () != defaultBlackRender_Auto)
2961 {
2962
2963 directory.Add (&fDefaultBlackRenderTag);
2964
2965 }
2966
2967 if (profile.ToneCurve ().IsValid ())
2968 {
2969
2970 // Tone curve stored as pairs of 32-bit coordinates. Probably could do with
2971 // 16-bits here, but should be small number of points so...
2972
2973 uint32 toneCurvePoints = (uint32) (profile.ToneCurve ().fCoord.size ());
2974
2975 fToneCurveBuffer.Allocate (dng_safe_uint32 (toneCurvePoints) * 2u,
2976 sizeof (real32));
2977
2978 real32 *points = fToneCurveBuffer.Buffer_real32 ();
2979
2980 fToneCurveTag.SetCount (toneCurvePoints * 2);
2981 fToneCurveTag.SetData (points);
2982
2983 for (uint32 i = 0; i < toneCurvePoints; i++)
2984 {
2985
2986 // Transpose coordinates so they are in a more expected
2987 // order (domain -> range).
2988
2989 points [i * 2 ] = (real32) profile.ToneCurve ().fCoord [i].h;
2990 points [i * 2 + 1] = (real32) profile.ToneCurve ().fCoord [i].v;
2991
2992 }
2993
2994 directory.Add (&fToneCurveTag);
2995
2996 }
2997
2998 if (profile.ToneMethod () != profileToneMethod_Unspecified)
2999 {
3000
3001 directory.Add (&fToneMethodTag);
3002
3003 }
3004
3005 // ProfileGainTableMap2.
3006
3007 if (profile.HasProfileGainTableMap ())
3008 {
3009
3010 dng_memory_stream tempStream (host.Allocator (),
3011 host.Sniffer ());
3012
3013 auto pgtm = profile.ShareProfileGainTableMap ();
3014
3015 // Always write version 2.
3016
3017 pgtm->PutStream (tempStream, true);
3018
3019 const_dng_memory_block_sptr block
3020 (tempStream.AsMemoryBlock (host.Allocator ()));
3021
3022 fProfileGainTableMapTag.Reset
3023 (new tag_owned_data_ptr (tcProfileGainTableMap2,
3024 ttUndefined,
3025 block->LogicalSize (),
3026 block));
3027
3028 directory.Add (fProfileGainTableMapTag.Get ());
3029
3030 }
3031
3032 // ProfileDynamicRange.
3033
3034 if (profile.DynamicRangeInfo ().IsValid () &&
3035 (profile.DynamicRangeInfo () != dng_camera_profile_dynamic_range ()))
3036 {
3037
3038 dng_memory_stream tempStream (host.Allocator (),
3039 host.Sniffer ());
3040
3041 profile.DynamicRangeInfo ().PutStream (tempStream);
3042
3043 const_dng_memory_block_sptr block
3044 (tempStream.AsMemoryBlock (host.Allocator ()));
3045
3046 fProfileDynamicRangeTag.Reset
3047 (new tag_owned_data_ptr (tcProfileDynamicRange,
3048 ttUndefined,
3049 block->LogicalSize (),
3050 block));
3051
3052 directory.Add (fProfileDynamicRangeTag.Get ());
3053
3054 }
3055
3056 // RGBTables.
3057
3058 if (profile.HasMaskedRGBTables () &&
3059 !profile.MaskedRGBTables ().IsNOP ())
3060 {
3061
3062 dng_memory_stream tempStream (host.Allocator (),
3063 host.Sniffer ());
3064
3065 profile.MaskedRGBTables ().PutStream (tempStream);
3066
3067 const_dng_memory_block_sptr block
3068 (tempStream.AsMemoryBlock (host.Allocator ()));
3069
3070 fRGBTablesTag.Reset
3071 (new tag_owned_data_ptr (tcRGBTables,
3072 ttUndefined,
3073 block->LogicalSize (),
3074 block));
3075
3076 directory.Add (fRGBTablesTag.Get ());
3077
3078 }
3079
3080 } // HasColorMatrix1
3081
3082 }
3083
3084 /******************************************************************************/
3085
3086 tiff_dng_extended_color_profile::tiff_dng_extended_color_profile
3087 (const dng_camera_profile &profile,
3088 bool includeModelRestriction)
3089
3090 : fProfile (profile)
3091
3092 , fProfileTagSet ()
3093
3094 , fCameraModelTag (tcUniqueCameraModel,
3095 fProfile.UniqueCameraModelRestriction ())
3096
3097 {
3098
3099 // Profile tags.
3100
3101 dng_host host;
3102
3103 fProfileTagSet.Reset (new profile_tag_set (host, *this, fProfile));
3104
3105 // Camera this profile is for.
3106
3107 if (includeModelRestriction)
3108 {
3109
3110 if (fProfile.UniqueCameraModelRestriction ().NotEmpty ())
3111 {
3112
3113 Add (&fCameraModelTag);
3114
3115 }
3116
3117 }
3118
3119 }
3120
3121 /******************************************************************************/
3122
3123 tiff_dng_extended_color_profile::~tiff_dng_extended_color_profile ()
3124 {
3125
3126 }
3127
3128 /******************************************************************************/
3129
3130 void tiff_dng_extended_color_profile::Put (dng_host & /* host */,
3131 dng_stream &stream)
3132 {
3133
3134 // Profile header.
3135
3136 stream.Put_uint16 (stream.BigEndian () ? byteOrderMM : byteOrderII);
3137
3138 stream.Put_uint16 (magicExtendedProfile);
3139
3140 stream.Put_uint32 (8);
3141
3142 // Write out directory.
3143
3144 dng_tiff_directory::Put (stream, offsetsRelativeToExplicitBase, 8);
3145
3146 }
3147
3148 /*****************************************************************************/
3149
3150 uint64 tiff_dng_extended_color_profile::DataSize ()
3151 {
3152
3153 return 8 + Size ();
3154
3155 }
3156
3157 /*****************************************************************************/
3158
3159 tag_dng_noise_profile::tag_dng_noise_profile (const dng_noise_profile &profile)
3160
3161 : tag_data_ptr (tcNoiseProfile,
3162 ttDouble,
3163 2 * profile.NumFunctions (),
3164 fValues)
3165
3166 {
3167
3168 DNG_REQUIRE (profile.NumFunctions () <= kMaxColorPlanes,
3169 "Too many noise functions in tag_dng_noise_profile.");
3170
3171 for (uint32 i = 0; i < profile.NumFunctions (); i++)
3172 {
3173
3174 fValues [(2 * i) ] = profile.NoiseFunction (i).Scale ();
3175 fValues [(2 * i) + 1] = profile.NoiseFunction (i).Offset ();
3176
3177 }
3178
3179 }
3180
3181 /******************************************************************************/
3182
3183 class big_table_tag_set
3184 {
3185
3186 private:
3187
3188 const dng_big_table_dictionary &fDictionary;
3189
3190 const dng_big_table_group_index &fGroupIndex;
3191
3192 tag_data_ptr fBigTableDigests;
3193 tag_data_ptr fBigTableOffsets;
3194 tag_data_ptr fBigTableByteCounts;
3195 tag_data_ptr fBigTableGroupIndex;
3196
3197 AutoPtr<dng_memory_block> fDigestsBuffer;
3198 AutoPtr<dng_memory_block> fOffsetsBuffer;
3199 AutoPtr<dng_memory_block> fByteCountsBuffer;
3200 AutoPtr<dng_memory_block> fGroupBuffer;
3201
3202 public:
3203
3204 big_table_tag_set (dng_host &host,
3205 dng_tiff_directory &directory,
3206 const dng_big_table_dictionary &dictionary,
3207 const dng_big_table_group_index &groupIndex);
3208
3209 void WriteData (dng_stream &stream);
3210
3211 uint64 DataSize ();
3212
3213 };
3214
3215 /*****************************************************************************/
3216
3217 big_table_tag_set::big_table_tag_set (dng_host &host,
3218 dng_tiff_directory &directory,
3219 const dng_big_table_dictionary &dictionary,
3220 const dng_big_table_group_index &groupIndex)
3221
3222 : fDictionary (dictionary)
3223
3224 , fGroupIndex (groupIndex)
3225
3226 , fBigTableDigests (tcBigTableDigests,
3227 ttByte,
3228 0,
3229 nullptr)
3230
3231 , fBigTableOffsets (tcBigTableOffsets,
3232 ttLong,
3233 0,
3234 nullptr)
3235
3236 , fBigTableByteCounts (tcBigTableByteCounts,
3237 ttLong,
3238 0,
3239 nullptr)
3240
3241 , fBigTableGroupIndex (tcBigTableGroupIndex,
3242 ttByte,
3243 0,
3244 nullptr)
3245
3246 {
3247
3248 if (!fDictionary.IsEmpty ())
3249 {
3250
3251 uint32 count = (uint32) fDictionary.Map ().size ();
3252
3253 fDigestsBuffer.Reset (host.Allocate (count * 16));
3254
3255 fBigTableDigests.SetCount (count * 16);
3256 fBigTableDigests.SetData (fDigestsBuffer->Buffer_uint8 ());
3257
3258 directory.Add (&fBigTableDigests);
3259
3260 fOffsetsBuffer.Reset (host.Allocate (count * sizeof (uint32)));
3261
3262 fBigTableOffsets.SetCount (count);
3263 fBigTableOffsets.SetData (fOffsetsBuffer->Buffer_uint32 ());
3264
3265 directory.Add (&fBigTableOffsets);
3266
3267 fByteCountsBuffer.Reset (host.Allocate (count * sizeof (uint32)));
3268
3269 fBigTableByteCounts.SetCount (count);
3270 fBigTableByteCounts.SetData (fByteCountsBuffer->Buffer_uint32 ());
3271
3272 directory.Add (&fBigTableByteCounts);
3273
3274 // Big table group index.
3275
3276 if (!groupIndex.IsEmpty ())
3277 {
3278
3279 const uint32 groups = (uint32) groupIndex.Map ().size ();
3280
3281 constexpr uint32 bytesPerGroup = 2 * 16;
3282
3283 const uint32 totalBytes = groups * bytesPerGroup;
3284
3285 fGroupBuffer.Reset (host.Allocate (totalBytes));
3286
3287 fBigTableGroupIndex.SetCount (totalBytes);
3288 fBigTableGroupIndex.SetData (fGroupBuffer->Buffer_uint8 ());
3289
3290 directory.Add (&fBigTableGroupIndex);
3291
3292 }
3293
3294 }
3295
3296 }
3297
3298 /*****************************************************************************/
3299
3300 void big_table_tag_set::WriteData (dng_stream &stream)
3301 {
3302
3303 if (!fDictionary.IsEmpty ())
3304 {
3305
3306 uint32 index = 0;
3307
3308 for (auto it = fDictionary.Map ().cbegin ();
3309 it != fDictionary.Map ().cend ();
3310 ++it)
3311 {
3312
3313 fOffsetsBuffer->Buffer_uint32 () [index] = (uint32) stream.Position ();
3314
3315 const dng_fingerprint &fingerprint = it->first;
3316
3317 memcpy (fDigestsBuffer->Buffer_uint8 () + index * 16,
3318 fingerprint.data,
3319 16);
3320
3321 const dng_ref_counted_block &block = it->second;
3322
3323 uint32 count = block.LogicalSize ();
3324
3325 fByteCountsBuffer->Buffer_uint32 () [index] = count;
3326
3327 stream.Put (block.Buffer_uint8 (), count);
3328
3329 stream.PadAlign2 ();
3330
3331 index++;
3332
3333 }
3334
3335 // Group index.
3336
3337 if (!fGroupIndex.IsEmpty ())
3338 {
3339
3340 uint8 *dPtr = fGroupBuffer->Buffer_uint8 ();
3341
3342 for (const auto &group : fGroupIndex.Map ())
3343 {
3344
3345 memcpy (dPtr , group.first .data, 16);
3346 memcpy (dPtr + 16, group.second.data, 16);
3347
3348 dPtr += 32;
3349
3350 }
3351
3352 }
3353
3354 }
3355
3356 }
3357
3358 /*****************************************************************************/
3359
3360 uint64 big_table_tag_set::DataSize ()
3361 {
3362
3363 uint64 result = 0;
3364
3365 if (!fDictionary.IsEmpty ())
3366 {
3367
3368 for (auto it = fDictionary.Map ().cbegin ();
3369 it != fDictionary.Map ().cend ();
3370 ++it)
3371 {
3372
3373 const dng_ref_counted_block &block = it->second;
3374
3375 uint32 count = block.LogicalSize ();
3376
3377 result += RoundUp2 (count);
3378
3379 }
3380
3381 }
3382
3383 return result;
3384
3385 }
3386
3387 /*****************************************************************************/
3388
3389 dng_image_writer::dng_image_writer ()
3390 {
3391
3392 }
3393
3394 /*****************************************************************************/
3395
3396 dng_image_writer::~dng_image_writer ()
3397 {
3398
3399 }
3400
3401 /*****************************************************************************/
3402
3403 uint32 dng_image_writer::CompressedBufferSize (const dng_ifd &ifd,
3404 uint32 uncompressedSize)
3405 {
3406
3407 const dng_safe_uint32 safeUncompressedSize (uncompressedSize);
3408
3409 switch (ifd.fCompression)
3410 {
3411
3412 case ccLZW:
3413 {
3414
3415 // Add lots of slop for LZW to expand data.
3416
3417 return (safeUncompressedSize * 2u + 1024u).Get ();
3418
3419 }
3420
3421 case ccDeflate:
3422 {
3423
3424 // ZLib says maximum is source size + 0.1% + 12 bytes.
3425
3426 const dng_safe_uint32 temp (uncompressedSize >> 8);
3427
3428 return (safeUncompressedSize + temp + 64u).Get ();
3429
3430 }
3431
3432 case ccJPEG:
3433 {
3434
3435 // If we are saving lossless JPEG from an 8-bit image, reserve
3436 // space to pad the data out to 16-bits.
3437
3438 if (ifd.fBitsPerSample [0] <= 8)
3439 {
3440
3441 return (safeUncompressedSize * 2u).Get ();
3442
3443 }
3444
3445 break;
3446
3447 }
3448
3449 default:
3450 break;
3451
3452 }
3453
3454 return 0;
3455
3456 }
3457
3458 /******************************************************************************/
3459
3460 static void EncodeDelta8 (uint8 *dPtr,
3461 uint32 rows,
3462 uint32 cols,
3463 uint32 channels)
3464 {
3465
3466 const uint32 dRowStep = cols * channels;
3467
3468 for (uint32 row = 0; row < rows; row++)
3469 {
3470
3471 for (uint32 col = cols - 1; col > 0; col--)
3472 {
3473
3474 for (uint32 channel = 0; channel < channels; channel++)
3475 {
3476
3477 dPtr [col * channels + channel] -= dPtr [(col - 1) * channels + channel];
3478
3479 }
3480
3481 }
3482
3483 dPtr += dRowStep;
3484
3485 }
3486
3487 }
3488
3489 /******************************************************************************/
3490
3491 static void EncodeDelta16 (uint16 *dPtr,
3492 uint32 rows,
3493 uint32 cols,
3494 uint32 channels)
3495 {
3496
3497 const uint32 dRowStep = cols * channels;
3498
3499 for (uint32 row = 0; row < rows; row++)
3500 {
3501
3502 for (uint32 col = cols - 1; col > 0; col--)
3503 {
3504
3505 for (uint32 channel = 0; channel < channels; channel++)
3506 {
3507
3508 dPtr [col * channels + channel] -= dPtr [(col - 1) * channels + channel];
3509
3510 }
3511
3512 }
3513
3514 dPtr += dRowStep;
3515
3516 }
3517
3518 }
3519
3520 /******************************************************************************/
3521
3522 static void EncodeDelta32 (uint32 *dPtr,
3523 uint32 rows,
3524 uint32 cols,
3525 uint32 channels)
3526 {
3527
3528 const uint32 dRowStep = cols * channels;
3529
3530 for (uint32 row = 0; row < rows; row++)
3531 {
3532
3533 for (uint32 col = cols - 1; col > 0; col--)
3534 {
3535
3536 for (uint32 channel = 0; channel < channels; channel++)
3537 {
3538
3539 dPtr [col * channels + channel] -= dPtr [(col - 1) * channels + channel];
3540
3541 }
3542
3543 }
3544
3545 dPtr += dRowStep;
3546
3547 }
3548
3549 }
3550
3551 /*****************************************************************************/
3552
3553 inline void EncodeDeltaBytes (uint8 *bytePtr, int32 cols, int32 channels)
3554 {
3555
3556 if (channels == 1)
3557 {
3558
3559 bytePtr += (cols - 1);
3560
3561 uint8 this0 = bytePtr [0];
3562
3563 for (int32 col = 1; col < cols; col++)
3564 {
3565
3566 uint8 prev0 = bytePtr [-1];
3567
3568 this0 -= prev0;
3569
3570 bytePtr [0] = this0;
3571
3572 this0 = prev0;
3573
3574 bytePtr -= 1;
3575
3576 }
3577
3578 }
3579
3580 else if (channels == 3)
3581 {
3582
3583 bytePtr += (cols - 1) * 3;
3584
3585 uint8 this0 = bytePtr [0];
3586 uint8 this1 = bytePtr [1];
3587 uint8 this2 = bytePtr [2];
3588
3589 for (int32 col = 1; col < cols; col++)
3590 {
3591
3592 uint8 prev0 = bytePtr [-3];
3593 uint8 prev1 = bytePtr [-2];
3594 uint8 prev2 = bytePtr [-1];
3595
3596 this0 -= prev0;
3597 this1 -= prev1;
3598 this2 -= prev2;
3599
3600 bytePtr [0] = this0;
3601 bytePtr [1] = this1;
3602 bytePtr [2] = this2;
3603
3604 this0 = prev0;
3605 this1 = prev1;
3606 this2 = prev2;
3607
3608 bytePtr -= 3;
3609
3610 }
3611
3612 }
3613
3614 else
3615 {
3616
3617 uint32 rowBytes = cols * channels;
3618
3619 bytePtr += rowBytes - 1;
3620
3621 for (uint32 col = channels; col < rowBytes; col++)
3622 {
3623
3624 bytePtr [0] -= bytePtr [-channels];
3625
3626 bytePtr--;
3627
3628 }
3629
3630 }
3631
3632 }
3633
3634 /*****************************************************************************/
3635
3636 static void EncodeFPDelta (uint8 *buffer,
3637 uint8 *temp,
3638 int32 cols,
3639 int32 channels,
3640 int32 bytesPerSample)
3641 {
3642
3643 int32 rowIncrement = cols * channels;
3644
3645 if (bytesPerSample == 2)
3646 {
3647
3648 const uint8 *src = buffer;
3649
3650 #if qDNGBigEndian
3651 uint8 *dst0 = temp;
3652 uint8 *dst1 = temp + rowIncrement;
3653 #else
3654 uint8 *dst1 = temp;
3655 uint8 *dst0 = temp + rowIncrement;
3656 #endif
3657
3658 for (int32 col = 0; col < rowIncrement; ++col)
3659 {
3660
3661 dst0 [col] = src [0];
3662 dst1 [col] = src [1];
3663
3664 src += 2;
3665
3666 }
3667
3668 }
3669
3670 else if (bytesPerSample == 3)
3671 {
3672
3673 const uint8 *src = buffer;
3674
3675 uint8 *dst0 = temp;
3676 uint8 *dst1 = temp + rowIncrement;
3677 uint8 *dst2 = temp + rowIncrement * 2;
3678
3679 for (int32 col = 0; col < rowIncrement; ++col)
3680 {
3681
3682 dst0 [col] = src [0];
3683 dst1 [col] = src [1];
3684 dst2 [col] = src [2];
3685
3686 src += 3;
3687
3688 }
3689
3690 }
3691
3692 else
3693 {
3694
3695 const uint8 *src = buffer;
3696
3697 #if qDNGBigEndian
3698 uint8 *dst0 = temp;
3699 uint8 *dst1 = temp + rowIncrement;
3700 uint8 *dst2 = temp + rowIncrement * 2;
3701 uint8 *dst3 = temp + rowIncrement * 3;
3702 #else
3703 uint8 *dst3 = temp;
3704 uint8 *dst2 = temp + rowIncrement;
3705 uint8 *dst1 = temp + rowIncrement * 2;
3706 uint8 *dst0 = temp + rowIncrement * 3;
3707 #endif
3708
3709 for (int32 col = 0; col < rowIncrement; ++col)
3710 {
3711
3712 dst0 [col] = src [0];
3713 dst1 [col] = src [1];
3714 dst2 [col] = src [2];
3715 dst3 [col] = src [3];
3716
3717 src += 4;
3718
3719 }
3720
3721 }
3722
3723 EncodeDeltaBytes (temp, cols*bytesPerSample, channels);
3724
3725 memcpy (buffer, temp, cols*bytesPerSample*channels);
3726
3727 }
3728
3729 /*****************************************************************************/
3730
3731 void dng_image_writer::EncodePredictor (dng_host &host,
3732 const dng_ifd &ifd,
3733 dng_pixel_buffer &buffer,
3734 AutoPtr<dng_memory_block> &tempBuffer)
3735 {
3736
3737 switch (ifd.fPredictor)
3738 {
3739
3740 case cpHorizontalDifference:
3741 case cpHorizontalDifferenceX2:
3742 case cpHorizontalDifferenceX4:
3743 {
3744
3745 int32 xFactor = 1;
3746
3747 if (ifd.fPredictor == cpHorizontalDifferenceX2)
3748 {
3749 xFactor = 2;
3750 }
3751
3752 else if (ifd.fPredictor == cpHorizontalDifferenceX4)
3753 {
3754 xFactor = 4;
3755 }
3756
3757 switch (buffer.fPixelType)
3758 {
3759
3760 case ttByte:
3761 {
3762
3763 EncodeDelta8 ((uint8 *) buffer.fData,
3764 buffer.fArea.H (),
3765 buffer.fArea.W () / xFactor,
3766 buffer.fPlanes * xFactor);
3767
3768 return;
3769
3770 }
3771
3772 case ttShort:
3773 {
3774
3775 EncodeDelta16 ((uint16 *) buffer.fData,
3776 buffer.fArea.H (),
3777 buffer.fArea.W () / xFactor,
3778 buffer.fPlanes * xFactor);
3779
3780 return;
3781
3782 }
3783
3784 case ttLong:
3785 {
3786
3787 EncodeDelta32 ((uint32 *) buffer.fData,
3788 buffer.fArea.H (),
3789 buffer.fArea.W () / xFactor,
3790 buffer.fPlanes * xFactor);
3791
3792 return;
3793
3794 }
3795
3796 default:
3797 break;
3798
3799 }
3800
3801 break;
3802
3803 }
3804
3805 case cpFloatingPoint:
3806 case cpFloatingPointX2:
3807 case cpFloatingPointX4:
3808 {
3809
3810 int32 xFactor = 1;
3811
3812 if (ifd.fPredictor == cpFloatingPointX2)
3813 {
3814 xFactor = 2;
3815 }
3816
3817 else if (ifd.fPredictor == cpFloatingPointX4)
3818 {
3819 xFactor = 4;
3820 }
3821
3822 if (buffer.fRowStep < 0)
3823 {
3824 ThrowProgramError ("Row step may not be negative");
3825 }
3826
3827 dng_safe_uint32 tempBufferSize =
3828 dng_safe_uint32 (buffer.fPixelSize) *
3829 static_cast<uint32> (buffer.fRowStep);
3830
3831 if (!tempBuffer.Get () ||
3832 tempBuffer->LogicalSize () < tempBufferSize.Get ())
3833 {
3834
3835 tempBuffer.Reset (host.Allocate (tempBufferSize.Get ()));
3836
3837 }
3838
3839 for (int32 row = buffer.fArea.t; row < buffer.fArea.b; row++)
3840 {
3841
3842 EncodeFPDelta ((uint8 *) buffer.DirtyPixel (row, buffer.fArea.l, buffer.fPlane),
3843 tempBuffer->Buffer_uint8 (),
3844 buffer.fArea.W () / xFactor,
3845 buffer.fPlanes * xFactor,
3846 buffer.fPixelSize);
3847
3848 }
3849
3850 return;
3851
3852 }
3853
3854 default:
3855 break;
3856
3857 }
3858
3859 if (ifd.fPredictor != cpNullPredictor)
3860 {
3861
3862 ThrowProgramError ();
3863
3864 }
3865
3866 }
3867
3868 /*****************************************************************************/
3869
3870 void dng_image_writer::ByteSwapBuffer (dng_host & /* host */,
3871 dng_pixel_buffer &buffer)
3872 {
3873
3874 uint32 pixels = buffer.fRowStep * buffer.fArea.H ();
3875
3876 switch (buffer.fPixelSize)
3877 {
3878
3879 case 2:
3880 {
3881
3882 DoSwapBytes16 ((uint16 *) buffer.fData,
3883 pixels);
3884
3885 break;
3886
3887 }
3888
3889 case 4:
3890 {
3891
3892 DoSwapBytes32 ((uint32 *) buffer.fData,
3893 pixels);
3894
3895 break;
3896
3897 }
3898
3899 default:
3900 break;
3901
3902 }
3903
3904 }
3905
3906 /*****************************************************************************/
3907
3908 void dng_image_writer::ReorderSubTileBlocks (const dng_ifd &ifd,
3909 dng_pixel_buffer &buffer,
3910 AutoPtr<dng_memory_block> &uncompressedBuffer,
3911 AutoPtr<dng_memory_block> &subTileBlockBuffer)
3912 {
3913
3914 uint32 blockRows = ifd.fSubTileBlockRows;
3915 uint32 blockCols = ifd.fSubTileBlockCols;
3916
3917 uint32 rowBlocks = buffer.fArea.H () / blockRows;
3918 uint32 colBlocks = buffer.fArea.W () / blockCols;
3919
3920 int32 rowStep = buffer.fRowStep * buffer.fPixelSize;
3921 int32 colStep = buffer.fColStep * buffer.fPixelSize;
3922
3923 int32 rowBlockStep = rowStep * blockRows;
3924 int32 colBlockStep = colStep * blockCols;
3925
3926 uint32 blockColBytes = blockCols * buffer.fPlanes * buffer.fPixelSize;
3927
3928 const uint8 *s0 = uncompressedBuffer->Buffer_uint8 ();
3929 uint8 *d0 = subTileBlockBuffer->Buffer_uint8 ();
3930
3931 for (uint32 rowBlock = 0; rowBlock < rowBlocks; rowBlock++)
3932 {
3933
3934 const uint8 *s1 = s0;
3935
3936 for (uint32 colBlock = 0; colBlock < colBlocks; colBlock++)
3937 {
3938
3939 const uint8 *s2 = s1;
3940
3941 for (uint32 blockRow = 0; blockRow < blockRows; blockRow++)
3942 {
3943
3944 for (uint32 j = 0; j < blockColBytes; j++)
3945 {
3946
3947 d0 [j] = s2 [j];
3948
3949 }
3950
3951 d0 += blockColBytes;
3952
3953 s2 += rowStep;
3954
3955 }
3956
3957 s1 += colBlockStep;
3958
3959 }
3960
3961 s0 += rowBlockStep;
3962
3963 }
3964
3965 // Copy back reordered pixels.
3966
3967 DoCopyBytes (subTileBlockBuffer->Buffer (),
3968 uncompressedBuffer->Buffer (),
3969 uncompressedBuffer->LogicalSize ());
3970
3971 }
3972
3973 /******************************************************************************/
3974
3975 class dng_lzw_compressor: private dng_uncopyable
3976 {
3977
3978 private:
3979
3980 enum
3981 {
3982 kResetCode = 256,
3983 kEndCode = 257,
3984 kTableSize = 4096
3985 };
3986
3987 // Compressor nodes have two son pointers. The low order bit of
3988 // the next code determines which pointer is used. This cuts the
3989 // number of nodes searched for the next code by two on average.
3990
3991 struct LZWCompressorNode
3992 {
3993 int16 final;
3994 int16 son0;
3995 int16 son1;
3996 int16 brother;
3997 };
3998
3999 dng_memory_data fBuffer;
4000
4001 LZWCompressorNode *fTable;
4002
4003 uint8 *fDstPtr;
4004
4005 int32 fBitOffset;
4006
4007 int32 fNextCode;
4008
4009 int32 fCodeSize;
4010
4011 public:
4012
4013 dng_lzw_compressor ();
4014
4015 void Compress (const uint8 *sPtr,
4016 uint8 *dPtr,
4017 uint32 sCount,
4018 uint32 &dCount);
4019
4020 private:
4021
4022 void InitTable ();
4023
4024 int32 SearchTable (int32 w, int32 k) const
4025 {
4026
4027 DNG_ASSERT ((w >= 0) && (w <= kTableSize),
4028 "Bad w value in dng_lzw_compressor::SearchTable");
4029
4030 int32 son0 = fTable [w] . son0;
4031 int32 son1 = fTable [w] . son1;
4032
4033 // Branchless version of:
4034 // int32 code = (k & 1) ? son1 : son0;
4035
4036 int32 code = son0 + ((-((int32) (k & 1))) & (son1 - son0));
4037
4038 while (code > 0 && fTable [code].final != k)
4039 {
4040 code = fTable [code].brother;
4041 }
4042
4043 return code;
4044
4045 }
4046
4047 void AddTable (int32 w, int32 k);
4048
4049 void PutCodeWord (int32 code);
4050
4051 };
4052
4053 /******************************************************************************/
4054
4055 dng_lzw_compressor::dng_lzw_compressor ()
4056
4057 : fBuffer ()
4058 , fTable (NULL)
4059 , fDstPtr (NULL)
4060 , fBitOffset (0)
4061 , fNextCode (0)
4062 , fCodeSize (0)
4063
4064 {
4065
4066 fBuffer.Allocate (kTableSize, sizeof (LZWCompressorNode));
4067
4068 fTable = (LZWCompressorNode *) fBuffer.Buffer ();
4069
4070 }
4071
4072 /******************************************************************************/
4073
4074 void dng_lzw_compressor::InitTable ()
4075 {
4076
4077 fCodeSize = 9;
4078
4079 fNextCode = 258;
4080
4081 LZWCompressorNode *node = &fTable [0];
4082
4083 for (int32 code = 0; code < 256; ++code)
4084 {
4085
4086 node->final = (int16) code;
4087 node->son0 = -1;
4088 node->son1 = -1;
4089 node->brother = -1;
4090
4091 node++;
4092
4093 }
4094
4095 }
4096
4097 /******************************************************************************/
4098
4099 void dng_lzw_compressor::AddTable (int32 w, int32 k)
4100 {
4101
4102 DNG_ASSERT ((w >= 0) && (w <= kTableSize),
4103 "Bad w value in dng_lzw_compressor::AddTable");
4104
4105 LZWCompressorNode *node = &fTable [w];
4106
4107 int32 nextCode = fNextCode;
4108
4109 DNG_ASSERT ((nextCode >= 0) && (nextCode <= kTableSize),
4110 "Bad fNextCode value in dng_lzw_compressor::AddTable");
4111
4112 LZWCompressorNode *node2 = &fTable [nextCode];
4113
4114 fNextCode++;
4115
4116 int32 oldSon;
4117
4118 if( k&1 )
4119 {
4120 oldSon = node->son1;
4121 node->son1 = (int16) nextCode;
4122 }
4123 else
4124 {
4125 oldSon = node->son0;
4126 node->son0 = (int16) nextCode;
4127 }
4128
4129 node2->final = (int16) k;
4130 node2->son0 = -1;
4131 node2->son1 = -1;
4132 node2->brother = (int16) oldSon;
4133
4134 if (nextCode == (1 << fCodeSize) - 1)
4135 {
4136 if (fCodeSize != 12)
4137 fCodeSize++;
4138 }
4139
4140 }
4141
4142 /******************************************************************************/
4143
4144 void dng_lzw_compressor::PutCodeWord (int32 code)
4145 {
4146
4147 int32 bit = (int32) (fBitOffset & 7);
4148
4149 int32 offset1 = fBitOffset >> 3;
4150 int32 offset2 = (fBitOffset + fCodeSize - 1) >> 3;
4151
4152 int32 shift1 = (fCodeSize + bit) - 8;
4153 int32 shift2 = (fCodeSize + bit) - 16;
4154
4155 uint8 byte1 = (uint8) (code >> shift1);
4156
4157 uint8 *dstPtr1 = fDstPtr + offset1;
4158 uint8 *dstPtr3 = fDstPtr + offset2;
4159
4160 if (offset1 + 1 == offset2)
4161 {
4162
4163 uint8 byte2 = (uint8) (code << (-shift2));
4164
4165 if (bit)
4166 *dstPtr1 |= byte1;
4167 else
4168 *dstPtr1 = byte1;
4169
4170 *dstPtr3 = byte2;
4171
4172 }
4173
4174 else
4175 {
4176
4177 int32 shift3 = (fCodeSize + bit) - 24;
4178
4179 uint8 byte2 = (uint8) (code >> shift2);
4180 uint8 byte3 = (uint8) (code << (-shift3));
4181
4182 uint8 *dstPtr2 = fDstPtr + (offset1 + 1);
4183
4184 if (bit)
4185 *dstPtr1 |= byte1;
4186 else
4187 *dstPtr1 = byte1;
4188
4189 *dstPtr2 = byte2;
4190
4191 *dstPtr3 = byte3;
4192
4193 }
4194
4195 fBitOffset += fCodeSize;
4196
4197 }
4198
4199 /******************************************************************************/
4200
4201 void dng_lzw_compressor::Compress (const uint8 *sPtr,
4202 uint8 *dPtr,
4203 uint32 sCount,
4204 uint32 &dCount)
4205 {
4206
4207 fDstPtr = dPtr;
4208
4209 fBitOffset = 0;
4210
4211 InitTable ();
4212
4213 PutCodeWord (kResetCode);
4214
4215 int32 code = -1;
4216
4217 int32 pixel;
4218
4219 if (sCount > 0)
4220 {
4221
4222 pixel = *sPtr;
4223 sPtr = sPtr + 1;
4224 code = pixel;
4225
4226 sCount--;
4227
4228 while (sCount--)
4229 {
4230
4231 pixel = *sPtr;
4232 sPtr = sPtr + 1;
4233
4234 int32 newCode = SearchTable (code, pixel);
4235
4236 if (newCode == -1)
4237 {
4238
4239 PutCodeWord (code);
4240
4241 if (fNextCode < 4093)
4242 {
4243 AddTable (code, pixel);
4244 }
4245 else
4246 {
4247 PutCodeWord (kResetCode);
4248 InitTable ();
4249 }
4250
4251 code = pixel;
4252
4253 }
4254
4255 else
4256 code = newCode;
4257
4258 }
4259
4260 }
4261
4262 if (code != -1)
4263 {
4264 PutCodeWord (code);
4265 AddTable (code, 0);
4266 }
4267
4268 PutCodeWord (kEndCode);
4269
4270 dCount = (fBitOffset + 7) >> 3;
4271
4272 }
4273
4274 /*****************************************************************************/
4275
4276 #if qDNGUseLibJPEG
4277
4278 /*****************************************************************************/
4279
4280 static void dng_error_exit (j_common_ptr cinfo)
4281 {
4282
4283 // Output message.
4284
4285 (*cinfo->err->output_message) (cinfo);
4286
4287 // Convert to a dng_exception.
4288
4289 switch (cinfo->err->msg_code)
4290 {
4291
4292 case JERR_OUT_OF_MEMORY:
4293 {
4294 ThrowMemoryFull ();
4295 break;
4296 }
4297
4298 default:
4299 {
4300 ThrowBadFormat ();
4301 }
4302
4303 }
4304
4305 }
4306
4307 /*****************************************************************************/
4308
4309 static void dng_output_message (j_common_ptr cinfo)
4310 {
4311
4312 // Format message to string.
4313
4314 char buffer [JMSG_LENGTH_MAX];
4315
4316 (*cinfo->err->format_message) (cinfo, buffer);
4317
4318 // Report the libjpeg message as a warning.
4319
4320 ReportWarning ("libjpeg", buffer);
4321
4322 }
4323
4324 /*****************************************************************************/
4325
4326 struct dng_jpeg_stream_dest
4327 {
4328
4329 struct jpeg_destination_mgr pub;
4330
4331 dng_stream *fStream;
4332
4333 uint8 fBuffer [4096];
4334
4335 };
4336
4337 /*****************************************************************************/
4338
4339 static void dng_init_destination (j_compress_ptr cinfo)
4340 {
4341
4342 dng_jpeg_stream_dest *dest = (dng_jpeg_stream_dest *) cinfo->dest;
4343
4344 dest->pub.next_output_byte = dest->fBuffer;
4345 dest->pub.free_in_buffer = sizeof (dest->fBuffer);
4346
4347 }
4348
4349 /*****************************************************************************/
4350
4351 static boolean dng_empty_output_buffer (j_compress_ptr cinfo)
4352 {
4353
4354 dng_jpeg_stream_dest *dest = (dng_jpeg_stream_dest *) cinfo->dest;
4355
4356 dest->fStream->Put (dest->fBuffer, sizeof (dest->fBuffer));
4357
4358 dest->pub.next_output_byte = dest->fBuffer;
4359 dest->pub.free_in_buffer = sizeof (dest->fBuffer);
4360
4361 return TRUE;
4362
4363 }
4364
4365 /*****************************************************************************/
4366
4367 static void dng_term_destination (j_compress_ptr cinfo)
4368 {
4369
4370 dng_jpeg_stream_dest *dest = (dng_jpeg_stream_dest *) cinfo->dest;
4371
4372 uint32 datacount = sizeof (dest->fBuffer) -
4373 (uint32) dest->pub.free_in_buffer;
4374
4375 if (datacount)
4376 {
4377 dest->fStream->Put (dest->fBuffer, datacount);
4378 }
4379
4380 }
4381
4382 /*****************************************************************************/
4383
4384 static void jpeg_set_adobe_quality (struct jpeg_compress_struct *cinfo,
4385 int32 quality)
4386 {
4387
4388 // If out of range, map to default.
4389
4390 if (quality < 0 || quality > 12)
4391 {
4392 quality = 10;
4393 }
4394
4395 // Adobe turns off chroma downsampling at high quality levels.
4396
4397 bool useChromaDownsampling = (quality <= 6);
4398
4399 // Approximate mapping from Adobe quality levels to LibJPEG levels.
4400
4401 const int kLibJPEGQuality [13] =
4402 {
4403 5, 11, 23, 34, 46, 63, 76, 77, 86, 90, 94, 97, 99
4404 };
4405
4406 quality = kLibJPEGQuality [quality];
4407
4408 jpeg_set_quality (cinfo, quality, TRUE);
4409
4410 // LibJPEG defaults to always using chroma downsampling. Turn if off
4411 // if we need it off to match Adobe.
4412
4413 if (!useChromaDownsampling)
4414 {
4415
4416 cinfo->comp_info [0].h_samp_factor = 1;
4417 cinfo->comp_info [0].h_samp_factor = 1;
4418
4419 }
4420
4421 }
4422
4423 /*****************************************************************************/
4424
4425 #endif // qDNGUseLibJPEG
4426
4427 /*****************************************************************************/
4428
4429 void dng_image_writer::WriteData (dng_host &host,
4430 const dng_ifd &ifd,
4431 dng_stream &stream,
4432 dng_pixel_buffer &buffer,
4433 AutoPtr<dng_memory_block> &compressedBuffer,
4434 bool usingMultipleThreads)
4435 {
4436
4437 (void) usingMultipleThreads;
4438
4439 switch (ifd.fCompression)
4440 {
4441
4442 case ccUncompressed:
4443 {
4444
4445 // Special case support for when we save to 8-bits from
4446 // 16-bit data.
4447
4448 if (ifd.fBitsPerSample [0] == 8 && buffer.fPixelType == ttShort)
4449 {
4450
4451 uint32 count = buffer.fRowStep *
4452 buffer.fArea.H ();
4453
4454 const uint16 *sPtr = (const uint16 *) buffer.fData;
4455
4456 for (uint32 j = 0; j < count; j++)
4457 {
4458
4459 stream.Put_uint8 ((uint8) sPtr [j]);
4460
4461 }
4462
4463 }
4464
4465 else
4466 {
4467
4468 // Swap bytes if required.
4469
4470 if (stream.SwapBytes ())
4471 {
4472
4473 ByteSwapBuffer (host, buffer);
4474
4475 }
4476
4477 // Write the bytes.
4478
4479 stream.Put (buffer.fData, buffer.fRowStep *
4480 buffer.fArea.H () *
4481 buffer.fPixelSize);
4482
4483 }
4484
4485 break;
4486
4487 }
4488
4489 case ccLZW:
4490 case ccDeflate:
4491 {
4492
4493 // Both these compression algorithms are byte based. The floating
4494 // point predictor already does byte ordering, so don't ever swap
4495 // when using it.
4496
4497 if (stream.SwapBytes () && ifd.fPredictor != cpFloatingPoint)
4498 {
4499
4500 ByteSwapBuffer (host,
4501 buffer);
4502
4503 }
4504
4505 // Run the compression algorithm.
4506
4507 uint32 sBytes = buffer.fRowStep *
4508 buffer.fArea.H () *
4509 buffer.fPixelSize;
4510
4511 uint8 *sBuffer = (uint8 *) buffer.fData;
4512
4513 uint32 dBytes = 0;
4514
4515 uint8 *dBuffer = compressedBuffer->Buffer_uint8 ();
4516
4517 if (ifd.fCompression == ccLZW)
4518 {
4519
4520 dng_lzw_compressor lzwCompressor;
4521
4522 lzwCompressor.Compress (sBuffer,
4523 dBuffer,
4524 sBytes,
4525 dBytes);
4526
4527 }
4528
4529 else
4530 {
4531
4532 uLongf dCount = compressedBuffer->LogicalSize ();
4533
4534 int32 level = Z_DEFAULT_COMPRESSION;
4535
4536 if (ifd.fCompressionQuality >= Z_BEST_SPEED &&
4537 ifd.fCompressionQuality <= Z_BEST_COMPRESSION)
4538 {
4539
4540 level = ifd.fCompressionQuality;
4541
4542 }
4543
4544 int zResult = ::compress2 (dBuffer,
4545 &dCount,
4546 sBuffer,
4547 sBytes,
4548 level);
4549
4550 if (zResult != Z_OK)
4551 {
4552
4553 ThrowMemoryFull ();
4554
4555 }
4556
4557 dBytes = (uint32) dCount;
4558
4559 }
4560
4561 if (dBytes > compressedBuffer->LogicalSize ())
4562 {
4563
4564 ThrowOverflow ("Compression output buffer overflow");
4565
4566 }
4567
4568 stream.Put (dBuffer, dBytes);
4569
4570 return;
4571
4572 }
4573
4574 case ccJPEG:
4575 {
4576
4577 dng_pixel_buffer temp (buffer);
4578
4579 if (buffer.fPixelType == ttByte)
4580 {
4581
4582 // The lossless JPEG encoder needs 16-bit data, so if we are
4583 // are saving 8 bit data, we need to pad it out to 16-bits.
4584
4585 temp.fData = compressedBuffer->Buffer ();
4586
4587 temp.fPixelType = ttShort;
4588 temp.fPixelSize = 2;
4589
4590 temp.CopyArea (buffer,
4591 buffer.fArea,
4592 buffer.fPlane,
4593 buffer.fPlanes);
4594
4595 }
4596
4597 DoEncodeLosslessJPEG ((const uint16 *) temp.fData,
4598 temp.fArea.H (),
4599 temp.fArea.W (),
4600 temp.fPlanes,
4601 ifd.fBitsPerSample [0],
4602 temp.fRowStep,
4603 temp.fColStep,
4604 stream);
4605
4606 break;
4607
4608 }
4609
4610 #if qDNGUseLibJPEG
4611
4612 case ccLossyJPEG:
4613 {
4614
4615 struct jpeg_compress_struct cinfo;
4616
4617 // Setup the error manager.
4618
4619 struct jpeg_error_mgr jerr;
4620
4621 cinfo.err = jpeg_std_error (&jerr);
4622
4623 jerr.error_exit = dng_error_exit;
4624 jerr.output_message = dng_output_message;
4625
4626 try
4627 {
4628
4629 // Create the compression context.
4630
4631 jpeg_create_compress (&cinfo);
4632
4633 // Setup the destination manager to write to stream.
4634
4635 dng_jpeg_stream_dest dest;
4636
4637 dest.fStream = &stream;
4638
4639 dest.pub.init_destination = dng_init_destination;
4640 dest.pub.empty_output_buffer = dng_empty_output_buffer;
4641 dest.pub.term_destination = dng_term_destination;
4642
4643 cinfo.dest = &dest.pub;
4644
4645 // Setup basic image info.
4646
4647 cinfo.image_width = buffer.fArea.W ();
4648 cinfo.image_height = buffer.fArea.H ();
4649 cinfo.input_components = buffer.fPlanes;
4650
4651 switch (buffer.fPlanes)
4652 {
4653
4654 case 1:
4655 cinfo.in_color_space = JCS_GRAYSCALE;
4656 break;
4657
4658 case 3:
4659 cinfo.in_color_space = JCS_RGB;
4660 break;
4661
4662 case 4:
4663 cinfo.in_color_space = JCS_CMYK;
4664 break;
4665
4666 default:
4667 ThrowProgramError ();
4668
4669 }
4670
4671 // Setup the compression parameters.
4672
4673 jpeg_set_defaults (&cinfo);
4674
4675 jpeg_set_adobe_quality (&cinfo, ifd.fCompressionQuality);
4676
4677 // Write the JPEG header.
4678
4679 jpeg_start_compress (&cinfo, TRUE);
4680
4681 // Write the scanlines.
4682
4683 for (int32 row = buffer.fArea.t; row < buffer.fArea.b; row++)
4684 {
4685
4686 uint8 *sampArray [1];
4687
4688 sampArray [0] = buffer.DirtyPixel_uint8 (row,
4689 buffer.fArea.l,
4690 0);
4691
4692 jpeg_write_scanlines (&cinfo, sampArray, 1);
4693
4694 }
4695
4696 // Cleanup.
4697
4698 jpeg_finish_compress (&cinfo);
4699
4700 jpeg_destroy_compress (&cinfo);
4701
4702 }
4703
4704 catch (...)
4705 {
4706
4707 jpeg_destroy_compress (&cinfo);
4708
4709 throw;
4710
4711 }
4712
4713 return;
4714
4715 }
4716
4717 #endif // qDNGUseLibJPEG
4718
4719 case ccJXL:
4720 {
4721
4722 dng_jxl_encode_settings settings;
4723
4724 if (ifd.fJXLEncodeSettings)
4725 settings = *ifd.fJXLEncodeSettings;
4726
4727 else if (host.JXLEncodeSettings ())
4728 settings = *host.JXLEncodeSettings ();
4729
4730 else
4731 {
4732 DNG_REPORT ("No JXLEncodeSettings, encoding tile using default settings");
4733 }
4734
4735 #if 0
4736 printf ("jxl encode tile: distance=%0.2f, effort=%d\n",
4737 settings.Distance (),
4738 settings.Effort ());
4739 #endif
4740
4741 // Set concurrency. If we're already using multiple threads (outer
4742 // loop processes a tile per thread), then tell the jxl encoder to
4743 // use a single thread.
4744
4745 settings.SetSingleThread (usingMultipleThreads);
4746
4747 // Get color space info.
4748
4749 dng_jxl_color_space_info colorSpaceInfoLocal;
4750
4751 const dng_jxl_color_space_info *colorSpaceInfoPtr =
4752 &colorSpaceInfoLocal;
4753
4754 // If host specified a custom value, then use that.
4755
4756 if (host.JXLColorSpaceInfo ())
4757 {
4758
4759 colorSpaceInfoPtr = host.JXLColorSpaceInfo ();
4760
4761 }
4762
4763 // Else get it from the IFD.
4764
4765 else if (ifd.fJXLColorEncoding)
4766 {
4767
4768 colorSpaceInfoLocal.fJxlColorEncoding.Reset
4769 (new JxlColorEncoding (*ifd.fJXLColorEncoding));
4770
4771 }
4772
4773 else
4774 {
4775
4776 PreviewColorSpaceToJXLEncoding (ifd.fPreviewInfo.fColorSpace,
4777 ifd.fSamplesPerPixel,
4778 colorSpaceInfoLocal);
4779
4780 }
4781
4782 #if 0
4783 printf ("jxl: strips=%s, tiles=%s, ta=%u, td=%u\n",
4784 ifd.fUsesStrips ? "yes" : "no",
4785 ifd.fUsesTiles ? "yes" : "no",
4786 ifd.TilesAcross (),
4787 ifd.TilesDown ());
4788 #endif
4789
4790 // If we're writing a single-tile preview, then write the JXL
4791 // using the container format (i.e., with boxes) so that readers
4792 // have the option of extracting a full standalone JXL file by
4793 // simply copying the bytes.
4794
4795 if (ifd.TilesAcross () == 1 &&
4796 ifd.TilesDown () == 1 &&
4797 (uint32 (ifd.fPreviewInfo.fColorSpace) <=
4798 uint32 (previewColorSpace_LastValid)))
4799 {
4800
4801 #if 0
4802 printf ("--- writing JXL container\n");
4803 #endif
4804
4805 EncodeJXL_Container (host,
4806 stream,
4807 buffer,
4808 settings,
4809 *colorSpaceInfoPtr,
4810 nullptr,
4811 false,
4812 false,
4813 false,
4814 nullptr);
4815
4816 }
4817
4818 // Otherwise write a bare JXL codestream, which saves a few bytes
4819 // per tile.
4820
4821 else
4822 {
4823
4824 EncodeJXL_Tile (host,
4825 stream,
4826 buffer,
4827 *colorSpaceInfoPtr,
4828 settings);
4829
4830 }
4831
4832 return;
4833
4834 }
4835
4836 default:
4837 {
4838
4839 ThrowProgramError ();
4840
4841 }
4842
4843 }
4844
4845 }
4846
4847 /******************************************************************************/
4848
4849 void dng_image_writer::EncodeJPEGPreview (dng_host &host,
4850 const dng_image &image,
4851 dng_jpeg_preview &preview,
4852 int32 quality)
4853 {
4854
4855 #if qDNGUseLibJPEG
4856
4857 dng_memory_stream stream (host.Allocator ());
4858
4859 struct jpeg_compress_struct cinfo;
4860
4861 // Setup the error manager.
4862
4863 struct jpeg_error_mgr jerr;
4864
4865 cinfo.err = jpeg_std_error (&jerr);
4866
4867 jerr.error_exit = dng_error_exit;
4868 jerr.output_message = dng_output_message;
4869
4870 try
4871 {
4872
4873 // Create the compression context.
4874
4875 jpeg_create_compress (&cinfo);
4876
4877 // Setup the destination manager to write to stream.
4878
4879 dng_jpeg_stream_dest dest;
4880
4881 dest.fStream = &stream;
4882
4883 dest.pub.init_destination = dng_init_destination;
4884 dest.pub.empty_output_buffer = dng_empty_output_buffer;
4885 dest.pub.term_destination = dng_term_destination;
4886
4887 cinfo.dest = &dest.pub;
4888
4889 // Setup basic image info.
4890
4891 cinfo.image_width = image.Bounds ().W ();
4892 cinfo.image_height = image.Bounds ().H ();
4893 cinfo.input_components = image.Planes ();
4894
4895 switch (image.Planes ())
4896 {
4897
4898 case 1:
4899 cinfo.in_color_space = JCS_GRAYSCALE;
4900 break;
4901
4902 case 3:
4903 cinfo.in_color_space = JCS_RGB;
4904 break;
4905
4906 default:
4907 ThrowProgramError ();
4908
4909 }
4910
4911 // Setup the compression parameters.
4912
4913 jpeg_set_defaults (&cinfo);
4914
4915 jpeg_set_adobe_quality (&cinfo, quality);
4916
4917 // Find some preview information based on the compression settings.
4918
4919 preview.SetIFDInfo (host, image);
4920
4921 if (image.Planes () == 3)
4922 {
4923
4924 preview.SetYCbCr (cinfo.comp_info [0].h_samp_factor,
4925 cinfo.comp_info [0].v_samp_factor);
4926
4927 }
4928
4929 // Write the JPEG header.
4930
4931 jpeg_start_compress (&cinfo, TRUE);
4932
4933 // Write the scanlines.
4934
4935 dng_pixel_buffer buffer (image.Bounds (),
4936 0,
4937 image.Planes (),
4938 ttByte,
4939 pcInterleaved,
4940 NULL);
4941
4942 AutoPtr<dng_memory_block> bufferData (host.Allocate (buffer.fRowStep));
4943
4944 buffer.fData = bufferData->Buffer ();
4945
4946 for (uint32 row = 0; row < cinfo.image_height; row++)
4947 {
4948
4949 buffer.fArea.t = row;
4950 buffer.fArea.b = row + 1;
4951
4952 image.Get (buffer);
4953
4954 uint8 *sampArray [1];
4955
4956 sampArray [0] = buffer.DirtyPixel_uint8 (row,
4957 buffer.fArea.l,
4958 0);
4959
4960 jpeg_write_scanlines (&cinfo, sampArray, 1);
4961
4962 }
4963
4964 // Cleanup.
4965
4966 jpeg_finish_compress (&cinfo);
4967
4968 jpeg_destroy_compress (&cinfo);
4969
4970 }
4971
4972 catch (...)
4973 {
4974
4975 jpeg_destroy_compress (&cinfo);
4976
4977 throw;
4978
4979 }
4980
4981 AutoPtr<dng_memory_block> compressedData (stream.AsMemoryBlock (host.Allocator ()));
4982
4983 preview.SetCompressedData (compressedData);
4984
4985 #else
4986
4987 (void) host;
4988 (void) image;
4989 (void) preview;
4990 (void) quality;
4991
4992 ThrowProgramError ("No JPEG encoder");
4993
4994 #endif
4995
4996 }
4997
4998 /*****************************************************************************/
4999
5000 void dng_image_writer::WriteTile (dng_host &host,
5001 const dng_ifd &ifd,
5002 dng_stream &stream,
5003 const dng_image &image,
5004 const dng_rect &tileArea,
5005 uint32 fakeChannels,
5006 AutoPtr<dng_memory_block> &compressedBuffer,
5007 AutoPtr<dng_memory_block> &uncompressedBuffer,
5008 AutoPtr<dng_memory_block> &subTileBlockBuffer,
5009 AutoPtr<dng_memory_block> &tempBuffer,
5010 bool usingMultipleThreads)
5011 {
5012
5013 // Create pixel buffer to hold uncompressed tile.
5014
5015 dng_pixel_buffer buffer (tileArea,
5016 0,
5017 ifd.fSamplesPerPixel,
5018 image.PixelType (),
5019 pcInterleaved,
5020 uncompressedBuffer->Buffer ());
5021
5022 // Is this lossy compression?
5023
5024 bool isLossyCompression = (ifd.fCompression == ccLossyJPEG) ||
5025 (ifd.fCompression == ccJXL &&
5026 (!ifd.fJXLEncodeSettings ||
5027 ifd.fJXLEncodeSettings->Distance () != 0.0f));
5028
5029 // Get the uncompressed data.
5030
5031 image.Get (buffer, isLossyCompression ? dng_image::edge_repeat
5032 : dng_image::edge_zero);
5033
5034 // Deal with sub-tile blocks.
5035
5036 if (ifd.fSubTileBlockRows > 1)
5037 {
5038
5039 ReorderSubTileBlocks (ifd,
5040 buffer,
5041 uncompressedBuffer,
5042 subTileBlockBuffer);
5043
5044 }
5045
5046 // Floating point depth conversion.
5047
5048 if (ifd.fSampleFormat [0] == sfFloatingPoint)
5049 {
5050
5051 if (ifd.fBitsPerSample [0] == 16)
5052 {
5053
5054 uint32 *srcPtr = (uint32 *) buffer.fData;
5055 uint16 *dstPtr = (uint16 *) buffer.fData;
5056
5057 uint32 pixels = tileArea.W () * tileArea.H () * buffer.fPlanes;
5058
5059 for (uint32 j = 0; j < pixels; j++)
5060 {
5061
5062 dstPtr [j] = DNG_FloatToHalf (srcPtr [j]);
5063
5064 }
5065
5066 buffer.fPixelSize = 2;
5067
5068 }
5069
5070 if (ifd.fBitsPerSample [0] == 24)
5071 {
5072
5073 uint32 *srcPtr = (uint32 *) buffer.fData;
5074 uint8 *dstPtr = (uint8 *) buffer.fData;
5075
5076 uint32 pixels = tileArea.W () * tileArea.H () * buffer.fPlanes;
5077
5078 if (stream.BigEndian () || ifd.fPredictor == cpFloatingPoint ||
5079 ifd.fPredictor == cpFloatingPointX2 ||
5080 ifd.fPredictor == cpFloatingPointX4)
5081 {
5082
5083 for (uint32 j = 0; j < pixels; j++)
5084 {
5085
5086 DNG_FloatToFP24 (srcPtr [j], dstPtr);
5087
5088 dstPtr += 3;
5089
5090 }
5091
5092 }
5093
5094 else
5095 {
5096
5097 for (uint32 j = 0; j < pixels; j++)
5098 {
5099
5100 uint8 output [3];
5101
5102 DNG_FloatToFP24 (srcPtr [j], output);
5103
5104 dstPtr [0] = output [2];
5105 dstPtr [1] = output [1];
5106 dstPtr [2] = output [0];
5107
5108 dstPtr += 3;
5109
5110 }
5111
5112 }
5113
5114 buffer.fPixelSize = 3;
5115
5116 }
5117
5118 }
5119
5120 // Run predictor.
5121
5122 EncodePredictor (host,
5123 ifd,
5124 buffer,
5125 tempBuffer);
5126
5127 // Adjust pixel buffer for fake channels.
5128
5129 if (fakeChannels > 1)
5130 {
5131
5132 buffer.fPlanes *= fakeChannels;
5133 buffer.fColStep *= fakeChannels;
5134
5135 buffer.fArea.r = buffer.fArea.l + (buffer.fArea.W () / fakeChannels);
5136
5137 }
5138
5139 // Compress (if required) and write out the data.
5140
5141 WriteData (host,
5142 ifd,
5143 stream,
5144 buffer,
5145 compressedBuffer,
5146 usingMultipleThreads);
5147
5148 }
5149
5150 /*****************************************************************************/
5151
5152 dng_write_tiles_task::dng_write_tiles_task
5153 (dng_image_writer &imageWriter,
5154 dng_host &host,
5155 const dng_ifd &ifd,
5156 dng_basic_tag_set &basic,
5157 dng_stream &stream,
5158 const dng_image &image,
5159 uint32 fakeChannels,
5160 uint32 tilesDown,
5161 uint32 tilesAcross,
5162 uint32 compressedSize,
5163 uint32 uncompressedSize,
5164 bool needDigest)
5165
5166 : dng_area_task ("dng_write_tiles_task")
5167
5168 , fImageWriter (imageWriter)
5169 , fHost (host)
5170 , fIFD (ifd)
5171 , fBasic (basic)
5172 , fStream (stream)
5173 , fImage (image)
5174 , fFakeChannels (fakeChannels)
5175 , fTilesDown (tilesDown)
5176 , fTilesAcross (tilesAcross)
5177 , fCompressedSize (compressedSize)
5178 , fUncompressedSize (uncompressedSize)
5179 , fNextTileIndex (0)
5180 , fMutex ("dng_write_tiles_task")
5181 , fCondition ()
5182 , fTaskFailed (false)
5183 , fWriteTileIndex (0)
5184 , fNeedDigest (needDigest)
5185
5186 {
5187
5188 fMinTaskArea = 16 * 16;
5189 fUnitCell = dng_point (16, 16);
5190 fMaxTileSize = dng_point (16, 16);
5191
5192 }
5193
5194 /*****************************************************************************/
5195
5196 void dng_write_tiles_task::Process (uint32 /* threadIndex */,
5197 const dng_rect & /* tile */,
5198 dng_abort_sniffer *sniffer)
5199 {
5200
5201 try
5202 {
5203
5204 AutoPtr<dng_memory_block> compressedBuffer;
5205 AutoPtr<dng_memory_block> uncompressedBuffer;
5206 AutoPtr<dng_memory_block> subTileBlockBuffer;
5207 AutoPtr<dng_memory_block> tempBuffer;
5208
5209 if (fCompressedSize)
5210 {
5211 compressedBuffer.Reset (fHost.Allocate (fCompressedSize));
5212 }
5213
5214 if (fUncompressedSize)
5215 {
5216 uncompressedBuffer.Reset (fHost.Allocate (fUncompressedSize));
5217 }
5218
5219 if (fIFD.fSubTileBlockRows > 1 && fUncompressedSize)
5220 {
5221 subTileBlockBuffer.Reset (fHost.Allocate (fUncompressedSize));
5222 }
5223
5224 while (true)
5225 {
5226
5227 // Find tile index to compress.
5228
5229 // Note: fNextTileIndex is atomic
5230
5231 uint32 tileIndex = fNextTileIndex++;
5232
5233 if (tileIndex >= fTilesDown * fTilesAcross)
5234 {
5235 return;
5236 }
5237
5238 // Encode the tile. This may be done concurrently.
5239
5240 uint32 tileByteCount = 0;
5241
5242 dng_memory_stream tileStream (fHost.Allocator ());
5243
5244 ProcessTask (tileIndex,
5245 compressedBuffer,
5246 uncompressedBuffer,
5247 subTileBlockBuffer,
5248 tempBuffer,
5249 tileByteCount,
5250 tileStream,
5251 sniffer);
5252
5253 // Compute tile digest if requested.
5254
5255 dng_fingerprint tileDigest;
5256
5257 if (fNeedDigest)
5258 {
5259
5260 tileStream.SetReadPosition (0);
5261
5262 dng_md5_printer_stream md5stream;
5263
5264 tileStream.CopyToStream (md5stream, tileByteCount);
5265
5266 tileDigest = md5stream.Result ();
5267
5268 tileStream.SetReadPosition (0);
5269
5270 }
5271
5272 // Wait until it is our turn to write tile.
5273
5274 {
5275
5276 dng_lock_mutex lock (&fMutex);
5277
5278 while (!fTaskFailed &&
5279 fWriteTileIndex != tileIndex)
5280 {
5281
5282 fCondition.Wait (fMutex);
5283
5284 }
5285
5286 // If the task failed in another thread, that thread already
5287 // threw an exception.
5288
5289 if (fTaskFailed)
5290 return;
5291
5292 }
5293
5294 // Write the encoded tile to the output stream. This must be done
5295 // sequentially in ascending order of tileIndex (enforced by the
5296 // above 'wait').
5297
5298 WriteTask (tileIndex,
5299 tileByteCount,
5300 tileStream,
5301 sniffer);
5302
5303 // Also update the overall digest if requested.
5304
5305 if (fNeedDigest)
5306 {
5307
5308 fOverallPrinter.Process (tileDigest.data,
5309 uint32 (sizeof (tileDigest.data)));
5310
5311 }
5312
5313 // Let other threads know it is safe to write to stream.
5314
5315 {
5316
5317 dng_lock_mutex lock (&fMutex);
5318
5319 // If the task failed in another thread, that thread already
5320 // threw an exception.
5321
5322 if (fTaskFailed)
5323 return;
5324
5325 fWriteTileIndex++;
5326
5327 fCondition.Broadcast ();
5328
5329 }
5330
5331 }
5332
5333 }
5334
5335 catch (...)
5336 {
5337
5338 // If first to fail, wake up any threads waiting on condition.
5339
5340 bool needBroadcast = false;
5341
5342 {
5343
5344 dng_lock_mutex lock (&fMutex);
5345
5346 needBroadcast = !fTaskFailed;
5347 fTaskFailed = true;
5348
5349 }
5350
5351 if (needBroadcast)
5352 fCondition.Broadcast ();
5353
5354 throw;
5355
5356 }
5357
5358 }
5359
5360 /*****************************************************************************/
5361
5362 void dng_write_tiles_task::ProcessTask
5363 (uint32 tileIndex,
5364 AutoPtr<dng_memory_block> &compressedBuffer,
5365 AutoPtr<dng_memory_block> &uncompressedBuffer,
5366 AutoPtr<dng_memory_block> &subTileBlockBuffer,
5367 AutoPtr<dng_memory_block> &tempBuffer,
5368 uint32 &tileByteCount, // output
5369 dng_memory_stream &tileStream, // output
5370 dng_abort_sniffer *sniffer)
5371 {
5372
5373 // This routine may be executed concurrently.
5374
5375 dng_abort_sniffer::SniffForAbort (sniffer);
5376
5377 // Compress tile.
5378
5379 uint32 rowIndex = tileIndex / fTilesAcross;
5380
5381 uint32 colIndex = tileIndex - rowIndex * fTilesAcross;
5382
5383 dng_rect tileArea = fIFD.TileArea (rowIndex, colIndex);
5384
5385 tileStream.SetLittleEndian (fStream.LittleEndian ());
5386
5387 dng_host host (&fHost.Allocator (),
5388 sniffer);
5389
5390 if (fHost.JXLEncodeSettings ())
5391 {
5392 host.SetJXLEncodeSettings (*fHost.JXLEncodeSettings ());
5393 }
5394
5395 if (fHost.JXLColorSpaceInfo ())
5396 {
5397 host.SetJXLColorSpaceInfo (fHost.ShareJXLColorSpaceInfo ());
5398 }
5399
5400 fImageWriter.WriteTile (host,
5401 fIFD,
5402 tileStream,
5403 fImage,
5404 tileArea,
5405 fFakeChannels,
5406 compressedBuffer,
5407 uncompressedBuffer,
5408 subTileBlockBuffer,
5409 tempBuffer,
5410 true);
5411
5412 tileStream.Flush ();
5413
5414 tileByteCount = (uint32) tileStream.Length ();
5415
5416 tileStream.SetReadPosition (0);
5417
5418 }
5419
5420 /*****************************************************************************/
5421
5422 void dng_write_tiles_task::WriteTask (uint32 tileIndex,
5423 uint32 tileByteCount,
5424 dng_memory_stream &tileStream,
5425 dng_abort_sniffer *sniffer)
5426 {
5427
5428 // This task must be executed serially and in sequential (ascending) order
5429 // of tileIndex.
5430
5431 dng_abort_sniffer::SniffForAbort (sniffer);
5432
5433 // Remember this offset.
5434
5435 uint64 tileOffset = fStream.Position ();
5436
5437 fBasic.SetTileOffset (tileIndex, tileOffset);
5438
5439 // Copy tile stream for tile into main stream.
5440
5441 tileStream.CopyToStream (fStream, tileByteCount);
5442
5443 // Update tile count.
5444
5445 fBasic.SetTileByteCount (tileIndex, tileByteCount);
5446
5447 // Keep the tiles on even byte offsets.
5448
5449 if (tileByteCount & 1)
5450 {
5451 fStream.Put_uint8 (0);
5452 }
5453
5454 }
5455
5456 /*****************************************************************************/
5457
5458 const dng_fingerprint & dng_write_tiles_task::ResultDigest () const
5459 {
5460
5461 return fOverallPrinter.Result ();
5462
5463 }
5464
5465 /*****************************************************************************/
5466
5467 void dng_image_writer::DoWriteTiles (dng_host &host,
5468 const dng_ifd &ifd,
5469 dng_basic_tag_set &basic,
5470 dng_stream &stream,
5471 const dng_image &image,
5472 uint32 fakeChannels,
5473 uint32 tilesDown,
5474 uint32 tilesAcross,
5475 uint32 compressedSize,
5476 const dng_safe_uint32 &uncompressedSize,
5477 dng_fingerprint *outDigest)
5478 {
5479
5480 uint32 threadCount = Min_uint32 (tilesDown * tilesAcross,
5481 host.PerformAreaTaskThreads ());
5482
5483 dng_write_tiles_task task (*this,
5484 host,
5485 ifd,
5486 basic,
5487 stream,
5488 image,
5489 fakeChannels,
5490 tilesDown,
5491 tilesAcross,
5492 compressedSize,
5493 uncompressedSize.Get (),
5494 (outDigest != nullptr));
5495
5496 host.PerformAreaTask (task,
5497 dng_rect (0, 0, 16, 16 * threadCount));
5498
5499 if (outDigest)
5500 {
5501
5502 *outDigest = task.ResultDigest ();
5503
5504 #if qDNGValidate && 0
5505 printf ("write digest: %s\n",
5506 outDigest->ToUtf8HexString ().Get ());
5507 #endif
5508
5509 }
5510
5511 }
5512
5513 /*****************************************************************************/
5514
5515 void dng_image_writer::WriteImage (dng_host &host,
5516 const dng_ifd &ifd,
5517 dng_basic_tag_set &basic,
5518 dng_stream &stream,
5519 const dng_image &image,
5520 uint32 fakeChannels,
5521 dng_fingerprint *outDigest)
5522 {
5523
5524 // Deal with images that have row and/or column interleaving.
5525
5526 if (ifd.fRowInterleaveFactor > 1 ||
5527 ifd.fColumnInterleaveFactor > 1)
5528 {
5529
5530 // First, apply interleaving to a temporary image.
5531
5532 AutoPtr<dng_image> tempImage (host.Make_dng_image (image.Bounds (),
5533 image.Planes (),
5534 image.PixelType ()));
5535
5536 Interleave2D (host,
5537 image,
5538 *tempImage,
5539 ifd.fRowInterleaveFactor,
5540 ifd.fColumnInterleaveFactor,
5541 true);
5542
5543 // Then write the interleaved image.
5544
5545 dng_ifd tempIFD (ifd);
5546
5547 tempIFD.fRowInterleaveFactor = 1;
5548 tempIFD.fColumnInterleaveFactor = 1;
5549
5550 WriteImage (host,
5551 tempIFD,
5552 basic,
5553 stream,
5554 *tempImage,
5555 fakeChannels,
5556 outDigest);
5557
5558 return;
5559
5560 }
5561
5562 #if qDNGValidate
5563
5564 char message [256];
5565
5566 AutoPtr<dng_timer> timer;
5567
5568 if (ifd.fCompression == ccJXL && ifd.fJXLEncodeSettings.get ())
5569 {
5570
5571 snprintf (message,
5572 sizeof (message),
5573 "JXL write %u by %u pixels, distance = %.2f, effort = %d",
5574 image.Width (),
5575 image.Height (),
5576 ifd.fJXLEncodeSettings->Distance (),
5577 ifd.fJXLEncodeSettings->Effort ());
5578
5579 timer.Reset (new dng_timer (message));
5580
5581 }
5582
5583 #endif
5584
5585 // Compute basic information.
5586
5587 dng_safe_uint32 bytesPerSample (TagTypeSize (image.PixelType ()));
5588
5589 dng_safe_uint32 bytesPerPixel = bytesPerSample * ifd.fSamplesPerPixel;
5590
5591 dng_safe_uint32 tileRowBytes = bytesPerPixel * ifd.fTileWidth;
5592
5593 // If we can compute the number of bytes needed to store the
5594 // data, we can split the write for each tile into sub-tiles.
5595
5596 uint32 subTileLength = ifd.fTileLength;
5597
5598 if (ifd.TileByteCount (ifd.TileArea (0, 0)) != 0)
5599 {
5600
5601 subTileLength = Pin_uint32 (ifd.fSubTileBlockRows,
5602 kImageBufferSize / tileRowBytes.Get (),
5603 ifd.fTileLength);
5604
5605 // Don't split sub-tiles across subTileBlocks.
5606
5607 subTileLength = subTileLength / ifd.fSubTileBlockRows
5608 * ifd.fSubTileBlockRows;
5609
5610 }
5611
5612 // Find size of uncompressed buffer.
5613
5614 dng_safe_uint32 uncompressedSize = tileRowBytes * subTileLength;
5615
5616 // Find size of compressed buffer, if required.
5617
5618 uint32 compressedSize = CompressedBufferSize (ifd, uncompressedSize.Get ());
5619
5620 // See if we can do this write using multiple threads.
5621
5622 uint32 tilesAcross = ifd.TilesAcross ();
5623 uint32 tilesDown = ifd.TilesDown ();
5624
5625 bool useMultipleThreads = (tilesDown * tilesAcross >= 2) &&
5626 (host.PerformAreaTaskThreads () > 1) &&
5627 (subTileLength == ifd.fTileLength) &&
5628 (ifd.fCompression != ccUncompressed);
5629
5630 if (useMultipleThreads)
5631 {
5632
5633 DoWriteTiles (host,
5634 ifd,
5635 basic,
5636 stream,
5637 image,
5638 fakeChannels,
5639 tilesDown,
5640 tilesAcross,
5641 compressedSize,
5642 uncompressedSize.Get (),
5643 outDigest);
5644
5645 }
5646
5647 else
5648 {
5649
5650 AutoPtr<dng_memory_block> compressedBuffer;
5651 AutoPtr<dng_memory_block> uncompressedBuffer;
5652 AutoPtr<dng_memory_block> subTileBlockBuffer;
5653 AutoPtr<dng_memory_block> tempBuffer;
5654
5655 if (compressedSize)
5656 {
5657 compressedBuffer.Reset (host.Allocate (compressedSize));
5658 }
5659
5660 if (uncompressedSize.Get ())
5661 {
5662 uncompressedBuffer.Reset (host.Allocate (uncompressedSize.Get ()));
5663 }
5664
5665 if (ifd.fSubTileBlockRows > 1 && uncompressedSize.Get ())
5666 {
5667 subTileBlockBuffer.Reset (host.Allocate (uncompressedSize.Get ()));
5668 }
5669
5670 dng_md5_printer overallPrinter;
5671
5672 const bool needDigest = (outDigest != nullptr);
5673
5674 // Write out each tile.
5675
5676 uint32 tileIndex = 0;
5677
5678 for (uint32 rowIndex = 0; rowIndex < tilesDown; rowIndex++)
5679 {
5680
5681 for (uint32 colIndex = 0; colIndex < tilesAcross; colIndex++)
5682 {
5683
5684 // Remember this offset.
5685
5686 uint64 tileOffset = stream.Position ();
5687
5688 basic.SetTileOffset (tileIndex, tileOffset);
5689
5690 // Split tile into sub-tiles if possible.
5691
5692 dng_rect tileArea = ifd.TileArea (rowIndex, colIndex);
5693
5694 uint32 subTileCount = (tileArea.H () + subTileLength - 1) /
5695 subTileLength;
5696
5697 // If we need a digest, then write the tile to a local stream so
5698 // that we can compute a fingerprint on it before copying the
5699 // data to the main stream.
5700
5701 dng_memory_stream tileStream (host.Allocator ());
5702
5703 auto &subStream = needDigest ? tileStream : stream;
5704
5705 for (uint32 subIndex = 0; subIndex < subTileCount; subIndex++)
5706 {
5707
5708 host.SniffForAbort ();
5709
5710 dng_rect subArea (tileArea);
5711
5712 subArea.t = tileArea.t + subIndex * subTileLength;
5713
5714 subArea.b = Min_int32 (subArea.t + subTileLength,
5715 tileArea.b);
5716
5717 // Write the sub-tile.
5718
5719 WriteTile (host,
5720 ifd,
5721 subStream,
5722 image,
5723 subArea,
5724 fakeChannels,
5725 compressedBuffer,
5726 uncompressedBuffer,
5727 subTileBlockBuffer,
5728 tempBuffer,
5729 useMultipleThreads);
5730
5731 }
5732
5733 uint64 tileByteCount;
5734
5735 if (needDigest)
5736 {
5737
5738 // Get the tile byte count.
5739
5740 tileStream.Flush ();
5741
5742 tileByteCount = tileStream.Length ();
5743
5744 // Compute the tile digest.
5745
5746 tileStream.SetReadPosition (0);
5747
5748 dng_md5_printer_stream md5stream;
5749
5750 tileStream.CopyToStream (md5stream, tileByteCount);
5751
5752 dng_fingerprint tileDigest = md5stream.Result ();
5753
5754 // Update the overall digest.
5755
5756 overallPrinter.Process (tileDigest.data,
5757 uint32 (sizeof (tileDigest.data)));
5758
5759 // Copy the tile data to the main stream.
5760
5761 tileStream.SetReadPosition (0);
5762
5763 tileStream.CopyToStream (stream, tileByteCount);
5764
5765 }
5766
5767 else
5768 {
5769
5770 // Update tile count.
5771
5772 tileByteCount = stream.Position () - tileOffset;
5773
5774 }
5775
5776 basic.SetTileByteCount (tileIndex, tileByteCount);
5777
5778 tileIndex++;
5779
5780 // Keep the tiles on even byte offsets.
5781
5782 if (tileByteCount & 1)
5783 {
5784 stream.Put_uint8 (0);
5785 }
5786
5787 } // tiles across (cols)
5788
5789 } // tiles down (rows)
5790
5791 // Optionally store the image digest.
5792
5793 if (outDigest)
5794 {
5795
5796 *outDigest = overallPrinter.Result ();
5797
5798 #if qDNGValidate && 0
5799 printf ("single-thread write digest: %s\n",
5800 outDigest->ToUtf8HexString ().Get ());
5801 #endif
5802
5803 }
5804
5805 } // concurrent vs single-thread
5806
5807 }
5808
5809 /*****************************************************************************/
5810
5811 #if qDNGUseXMP
5812
5813 /*****************************************************************************/
5814
5815 static void CopyString (const dng_xmp &oldXMP,
5816 dng_xmp &newXMP,
5817 const char *ns,
5818 const char *path,
5819 dng_string *exif = NULL)
5820 {
5821
5822 dng_string s;
5823
5824 if (oldXMP.GetString (ns, path, s))
5825 {
5826
5827 if (s.NotEmpty ())
5828 {
5829
5830 newXMP.SetString (ns, path, s);
5831
5832 if (exif)
5833 {
5834
5835 *exif = s;
5836
5837 }
5838
5839 }
5840
5841 }
5842
5843 }
5844
5845 /*****************************************************************************/
5846
5847 static void CopyStringList (const dng_xmp &oldXMP,
5848 dng_xmp &newXMP,
5849 const char *ns,
5850 const char *path,
5851 bool isBag)
5852 {
5853
5854 dng_string_list list;
5855
5856 if (oldXMP.GetStringList (ns, path, list))
5857 {
5858
5859 if (list.Count ())
5860 {
5861
5862 newXMP.SetStringList (ns, path, list, isBag);
5863
5864 }
5865
5866 }
5867
5868 }
5869
5870 /*****************************************************************************/
5871
5872 static void CopyAltLangDefault (const dng_xmp &oldXMP,
5873 dng_xmp &newXMP,
5874 const char *ns,
5875 const char *path,
5876 dng_string *exif = NULL)
5877 {
5878
5879 dng_string s;
5880
5881 if (oldXMP.GetAltLangDefault (ns, path, s))
5882 {
5883
5884 if (s.NotEmpty ())
5885 {
5886
5887 newXMP.SetAltLangDefault (ns, path, s);
5888
5889 if (exif)
5890 {
5891
5892 *exif = s;
5893
5894 }
5895
5896 }
5897
5898 }
5899
5900 }
5901
5902 /*****************************************************************************/
5903
5904 static void CopyStructField (const dng_xmp &oldXMP,
5905 dng_xmp &newXMP,
5906 const char *ns,
5907 const char *path,
5908 const char *field)
5909 {
5910
5911 dng_string s;
5912
5913 if (oldXMP.GetStructField (ns, path, ns, field, s))
5914 {
5915
5916 if (s.NotEmpty ())
5917 {
5918
5919 newXMP.SetStructField (ns, path, ns, field, s);
5920
5921 }
5922
5923 }
5924
5925 }
5926
5927 /*****************************************************************************/
5928
5929 static void CopyBoolean (const dng_xmp &oldXMP,
5930 dng_xmp &newXMP,
5931 const char *ns,
5932 const char *path)
5933 {
5934
5935 bool b;
5936
5937 if (oldXMP.GetBoolean (ns, path, b))
5938 {
5939
5940 newXMP.SetBoolean (ns, path, b);
5941
5942 }
5943
5944 }
5945
5946 /*****************************************************************************/
5947
5948 #endif // qDNGUseXMP
5949
5950 /*****************************************************************************/
5951
5952 void dng_image_writer::CleanUpMetadata (dng_host &host,
5953 dng_metadata &metadata,
5954 dng_metadata_subset metadataSubset,
5955 const char *dstMIME,
5956 const char *software)
5957 {
5958
5959 #if qDNGUseXMP
5960
5961 if (metadata.GetXMP () && metadata.GetExif ())
5962 {
5963
5964 dng_xmp &newXMP (*metadata.GetXMP ());
5965 dng_exif &newEXIF (*metadata.GetExif ());
5966
5967 // Update software tag.
5968
5969 if (software)
5970 {
5971
5972 newEXIF.fSoftware.Set (software);
5973
5974 newXMP.Set (XMP_NS_XAP,
5975 "CreatorTool",
5976 software);
5977
5978 }
5979
5980 #if qDNGXMPDocOps
5981
5982 newXMP.DocOpsPrepareForSave (metadata.SourceMIME ().Get (),
5983 dstMIME);
5984
5985 #else
5986
5987 metadata.UpdateDateTimeToNow ();
5988
5989 #endif
5990
5991 // Update EXIF version to at least 2.3.1 so all the exif tags
5992 // can be written.
5993
5994 if (!newEXIF.AtLeastVersion0231 ())
5995 {
5996
5997 newEXIF.SetVersion0231 ();
5998
5999 newXMP.Set (XMP_NS_EXIF, "ExifVersion", "0231");
6000
6001 }
6002
6003 // Require that XMP be the only source for saved GPS data.
6004
6005 {
6006
6007 dng_exif blankExif;
6008
6009 newEXIF.CopyGPSFrom (blankExif);
6010
6011 }
6012
6013 // Resync EXIF, remove EXIF tags from XMP.
6014
6015 newXMP.SyncExif (newEXIF,
6016 metadata.GetOriginalExif (),
6017 false,
6018 true);
6019
6020 // Deal with ImageIngesterPro bug. This program is adding lots of
6021 // empty metadata strings into the XMP, which is screwing up Adobe CS4.
6022 // We are saving a new file, so this is a chance to clean up this mess.
6023
6024 newXMP.RemoveEmptyStringsAndArrays (XMP_NS_DC);
6025 newXMP.RemoveEmptyStringsAndArrays (XMP_NS_XAP);
6026 newXMP.RemoveEmptyStringsAndArrays (XMP_NS_PHOTOSHOP);
6027 newXMP.RemoveEmptyStringsAndArrays (XMP_NS_IPTC);
6028 newXMP.RemoveEmptyStringsAndArrays (XMP_NS_XAP_RIGHTS);
6029 newXMP.RemoveEmptyStringsAndArrays ("http://ns.iview-multimedia.com/mediapro/1.0/");
6030
6031 // Process metadata subset.
6032
6033 if (metadataSubset != dng_metadata_subset::kMask_All)
6034 {
6035
6036 // Take a snapshot of the complete metadata.
6037
6038 dng_xmp oldXMP (newXMP );
6039 dng_exif oldEXIF (newEXIF);
6040
6041 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Other))
6042 {
6043
6044 // For these options, we start from nothing, and only fill in the
6045 // fields that we absolutely need.
6046
6047 newXMP.RemoveProperties (NULL);
6048
6049 newEXIF.SetEmpty ();
6050
6051 metadata.ClearMakerNote ();
6052
6053 // Exif version is always required.
6054
6055 newEXIF.fExifVersion = oldEXIF.fExifVersion;
6056
6057 #if qDNGXMPDocOps
6058
6059 // Include basic DocOps fields, but not the full history.
6060
6061 CopyString (oldXMP,
6062 newXMP,
6063 XMP_NS_MM,
6064 "OriginalDocumentID");
6065
6066 CopyString (oldXMP,
6067 newXMP,
6068 XMP_NS_MM,
6069 "DocumentID");
6070
6071 CopyString (oldXMP,
6072 newXMP,
6073 XMP_NS_MM,
6074 "InstanceID");
6075
6076 CopyString (oldXMP,
6077 newXMP,
6078 XMP_NS_XAP,
6079 "MetadataDate");
6080
6081 #endif
6082
6083 // Restore HDR metadata.
6084
6085 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_HDR_META);
6086 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_HDRGM);
6087 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_APPLE_HDRGM);
6088
6089 // Restore Camera Exif info.
6090
6091 if (metadataSubset.Includes (dng_metadata_subset::kMask_Exif))
6092 {
6093
6094 newEXIF = oldEXIF;
6095
6096 // But don't retore the GPS part of the exif block.
6097
6098 dng_exif blankExif;
6099
6100 newEXIF.CopyGPSFrom (blankExif);
6101
6102 // Restore the EXIF information in the XMP.
6103
6104 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_EXIF);
6105 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_EXIFEX);
6106 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_AUX);
6107
6108 }
6109
6110 // Restore EXIF date-related fields.
6111
6112 if (metadataSubset.Includes (dng_metadata_subset::kMask_ExifDate))
6113 {
6114
6115 newEXIF.CopyDateFrom (oldEXIF);
6116
6117 }
6118
6119 // Restore location info.
6120
6121 if (metadataSubset.Includes (dng_metadata_subset::kMask_Location))
6122 {
6123
6124 // Restore GPS location info.
6125
6126 newEXIF.CopyGPSFrom (oldEXIF);
6127
6128 // Restore XMP & IPTC location info.
6129
6130 CopyString (oldXMP,
6131 newXMP,
6132 XMP_NS_PHOTOSHOP,
6133 "City");
6134
6135 CopyString (oldXMP,
6136 newXMP,
6137 XMP_NS_PHOTOSHOP,
6138 "State");
6139
6140 CopyString (oldXMP,
6141 newXMP,
6142 XMP_NS_PHOTOSHOP,
6143 "Country");
6144
6145 CopyString (oldXMP,
6146 newXMP,
6147 XMP_NS_IPTC,
6148 "Location");
6149
6150 CopyString (oldXMP,
6151 newXMP,
6152 XMP_NS_IPTC,
6153 "CountryCode");
6154
6155 newXMP.DuplicateSubtree (oldXMP,
6156 XMP_NS_IPTC_EXT,
6157 "LocationCreated");
6158
6159 newXMP.DuplicateSubtree (oldXMP,
6160 XMP_NS_IPTC_EXT,
6161 "LocationShown");
6162
6163 }
6164
6165 // Move Camera Raw settings namespace over.
6166
6167 if (metadataSubset.Includes (dng_metadata_subset::kMask_CameraRaw))
6168 {
6169
6170 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_CRS);
6171
6172 }
6173
6174 // Move copyright related fields over.
6175
6176 if (metadataSubset.Includes (dng_metadata_subset::kMask_Copyright))
6177 {
6178
6179 CopyAltLangDefault (oldXMP,
6180 newXMP,
6181 XMP_NS_DC,
6182 "rights",
6183 &newEXIF.fCopyright);
6184
6185 CopyAltLangDefault (oldXMP,
6186 newXMP,
6187 XMP_NS_XAP_RIGHTS,
6188 "UsageTerms");
6189
6190 CopyString (oldXMP,
6191 newXMP,
6192 XMP_NS_XAP_RIGHTS,
6193 "WebStatement");
6194
6195 CopyBoolean (oldXMP,
6196 newXMP,
6197 XMP_NS_XAP_RIGHTS,
6198 "Marked");
6199
6200 }
6201
6202 // Move contact info fields over.
6203
6204 if (metadataSubset.Includes (dng_metadata_subset::kMask_Contact))
6205 {
6206
6207 // Note: Save for Web is not including the dc:creator list, but it
6208 // is part of the IPTC contract info metadata panel, so I
6209 // think it should be copied as part of the contact info.
6210
6211 CopyStringList (oldXMP,
6212 newXMP,
6213 XMP_NS_DC,
6214 "creator",
6215 false);
6216
6217 // The first string dc:creator list is mirrored to the
6218 // the exif artist tag, so copy that also.
6219
6220 newEXIF.fArtist = oldEXIF.fArtist;
6221
6222 // Copy other contact fields.
6223
6224 CopyString (oldXMP,
6225 newXMP,
6226 XMP_NS_PHOTOSHOP,
6227 "AuthorsPosition");
6228
6229 CopyStructField (oldXMP,
6230 newXMP,
6231 XMP_NS_IPTC,
6232 "CreatorContactInfo",
6233 "CiEmailWork");
6234
6235 CopyStructField (oldXMP,
6236 newXMP,
6237 XMP_NS_IPTC,
6238 "CreatorContactInfo",
6239 "CiAdrExtadr");
6240
6241 CopyStructField (oldXMP,
6242 newXMP,
6243 XMP_NS_IPTC,
6244 "CreatorContactInfo",
6245 "CiAdrCity");
6246
6247 CopyStructField (oldXMP,
6248 newXMP,
6249 XMP_NS_IPTC,
6250 "CreatorContactInfo",
6251 "CiAdrRegion");
6252
6253 CopyStructField (oldXMP,
6254 newXMP,
6255 XMP_NS_IPTC,
6256 "CreatorContactInfo",
6257 "CiAdrPcode");
6258
6259 CopyStructField (oldXMP,
6260 newXMP,
6261 XMP_NS_IPTC,
6262 "CreatorContactInfo",
6263 "CiAdrCtry");
6264
6265 CopyStructField (oldXMP,
6266 newXMP,
6267 XMP_NS_IPTC,
6268 "CreatorContactInfo",
6269 "CiTelWork");
6270
6271 CopyStructField (oldXMP,
6272 newXMP,
6273 XMP_NS_IPTC,
6274 "CreatorContactInfo",
6275 "CiUrlWork");
6276
6277 }
6278
6279 // Restore keywords.
6280
6281 if (metadataSubset.Includes (dng_metadata_subset::kMask_Keywords))
6282 {
6283
6284 CopyStringList (oldXMP,
6285 newXMP,
6286 XMP_NS_DC,
6287 "subject",
6288 true);
6289
6290 CopyStringList (oldXMP,
6291 newXMP,
6292 XMP_NS_LR,
6293 "hierarchicalSubject",
6294 true);
6295
6296 }
6297
6298 // Restore rating.
6299
6300 if (metadataSubset.Includes (dng_metadata_subset::kMask_Rating))
6301 {
6302
6303 CopyString (oldXMP,
6304 newXMP,
6305 XMP_NS_XAP,
6306 "Rating");
6307
6308 }
6309
6310 // Restore label.
6311
6312 if (metadataSubset.Includes (dng_metadata_subset::kMask_Label))
6313 {
6314
6315 CopyString (oldXMP,
6316 newXMP,
6317 XMP_NS_XAP,
6318 "Label");
6319
6320 }
6321
6322 // Restore caption.
6323
6324 if (metadataSubset.Includes (dng_metadata_subset::kMask_Caption))
6325 {
6326
6327 CopyAltLangDefault (oldXMP,
6328 newXMP,
6329 XMP_NS_DC,
6330 "description");
6331
6332 newEXIF.fImageDescription = oldEXIF.fImageDescription;
6333
6334 }
6335
6336 // Restore title.
6337
6338 if (metadataSubset.Includes (dng_metadata_subset::kMask_Title))
6339 {
6340
6341 CopyAltLangDefault (oldXMP,
6342 newXMP,
6343 XMP_NS_DC,
6344 "title");
6345
6346 }
6347
6348 // Restore regions.
6349
6350 if (metadataSubset.Includes (dng_metadata_subset::kMask_Regions))
6351 {
6352
6353 newXMP.DuplicateNameSpace (oldXMP, XMP_NS_REGIONS);
6354
6355 }
6356
6357 }
6358
6359 else
6360 {
6361
6362 // These options start with complete metadata and remove
6363 // the metadata that we explicitly do not want to include.
6364
6365 // Remove Camera Raw info.
6366
6367 if (metadataSubset.Excludes (dng_metadata_subset::kMask_CameraRaw))
6368 {
6369
6370 newXMP.RemoveProperties (XMP_NS_CRS);
6371 newXMP.RemoveProperties (XMP_NS_CRSS);
6372 newXMP.RemoveProperties (XMP_NS_CRX);
6373
6374 // Remove DocOps history, since it contains processing history.
6375
6376 newXMP.Remove (XMP_NS_MM, "History");
6377
6378 }
6379
6380 // Remove Camera Exif info.
6381
6382 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Exif))
6383 {
6384
6385 // This removes most of the EXIF info, so just copy the fields
6386 // we are not deleting.
6387
6388 newEXIF.SetEmpty ();
6389
6390 newEXIF.fImageDescription = oldEXIF.fImageDescription; // Note: Differs from SFW
6391 newEXIF.fSoftware = oldEXIF.fSoftware;
6392 newEXIF.fArtist = oldEXIF.fArtist;
6393 newEXIF.fCopyright = oldEXIF.fCopyright;
6394 newEXIF.fCopyright2 = oldEXIF.fCopyright2;
6395 newEXIF.fDateTime = oldEXIF.fDateTime;
6396 newEXIF.fDateTimeOriginal = oldEXIF.fDateTimeOriginal;
6397 newEXIF.fDateTimeDigitized = oldEXIF.fDateTimeDigitized;
6398 newEXIF.fExifVersion = oldEXIF.fExifVersion;
6399 newEXIF.fImageUniqueID = oldEXIF.fImageUniqueID;
6400
6401 newEXIF.CopyGPSFrom (oldEXIF);
6402
6403 // Remove exif info from XMP.
6404
6405 newXMP.RemoveProperties (XMP_NS_EXIF);
6406 newXMP.RemoveProperties (XMP_NS_EXIFEX);
6407 newXMP.RemoveProperties (XMP_NS_AUX);
6408
6409 // Remove Panorama info.
6410
6411 newXMP.RemoveProperties (XMP_NS_PANO);
6412 newXMP.RemoveProperties (XMP_NS_GPANO);
6413
6414 // MakerNote contains camera info.
6415
6416 metadata.ClearMakerNote ();
6417
6418 // Remove DocOps history, since it contains the original
6419 // camera format.
6420
6421 newXMP.Remove (XMP_NS_MM, "History");
6422
6423 }
6424
6425 }
6426
6427 // Remove keywords.
6428
6429 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Keywords))
6430 {
6431
6432 newXMP.Remove (XMP_NS_DC, "subject");
6433
6434 newXMP.Remove (XMP_NS_LR, "hierarchicalSubject");
6435
6436 }
6437
6438 // Remove location info.
6439
6440 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Location))
6441 {
6442
6443 // Remove GPS fields.
6444
6445 dng_exif blankExif;
6446
6447 newEXIF.CopyGPSFrom (blankExif);
6448
6449 // Remove MakerNote just in case, because we don't know
6450 // all of what is in it.
6451
6452 metadata.ClearMakerNote ();
6453
6454 // Remove XMP & IPTC location fields.
6455
6456 newXMP.Remove (XMP_NS_PHOTOSHOP, "City");
6457 newXMP.Remove (XMP_NS_PHOTOSHOP, "State");
6458 newXMP.Remove (XMP_NS_PHOTOSHOP, "Country");
6459 newXMP.Remove (XMP_NS_IPTC, "Location");
6460 newXMP.Remove (XMP_NS_IPTC, "CountryCode");
6461 newXMP.Remove (XMP_NS_IPTC_EXT, "LocationCreated");
6462 newXMP.Remove (XMP_NS_IPTC_EXT, "LocationShown");
6463
6464 }
6465
6466 // Remove contact info.
6467
6468 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Contact))
6469 {
6470
6471 newXMP.Remove (XMP_NS_DC, "creator");
6472
6473 newEXIF.fArtist.Clear ();
6474
6475 newXMP.Remove (XMP_NS_PHOTOSHOP, "AuthorsPosition");
6476
6477 newXMP.Remove (XMP_NS_IPTC, "CreatorContactInfo");
6478
6479 // Leave XMP_NS_DC:Title.
6480
6481 }
6482
6483 // Remove copyright.
6484
6485 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Copyright))
6486 {
6487
6488 newXMP.Remove (XMP_NS_DC, "rights");
6489
6490 newXMP.Remove (XMP_NS_XAP_RIGHTS, "UsageTerms");
6491 newXMP.Remove (XMP_NS_XAP_RIGHTS, "WebStatement");
6492 newXMP.Remove (XMP_NS_XAP_RIGHTS, "Marked");
6493
6494 newEXIF.fCopyright .Clear ();
6495 newEXIF.fCopyright2.Clear ();
6496
6497 }
6498
6499 // Remove rating.
6500
6501 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Rating))
6502 {
6503
6504 newXMP.Remove (XMP_NS_XAP, "Rating");
6505
6506 }
6507
6508 // Remove label.
6509
6510 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Label))
6511 {
6512
6513 newXMP.Remove (XMP_NS_XAP, "Label");
6514
6515 }
6516
6517 // Remove caption.
6518
6519 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Caption))
6520 {
6521
6522 newXMP.Remove (XMP_NS_DC, "description");
6523
6524 newEXIF.fImageDescription.Clear ();
6525
6526 }
6527
6528 // Remove title.
6529
6530 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Title))
6531 {
6532
6533 newXMP.Remove (XMP_NS_DC, "title");
6534
6535 }
6536
6537 // Remove regions.
6538
6539 if (metadataSubset.Excludes (dng_metadata_subset::kMask_Regions))
6540 {
6541
6542 newXMP.RemoveProperties (XMP_NS_REGIONS);
6543
6544 }
6545
6546 }
6547
6548 // Rebuild the legacy IPTC block, if needed.
6549
6550 bool isTIFF = (strcmp (dstMIME, "image/tiff") == 0);
6551 bool isDNG = (strcmp (dstMIME, "image/dng" ) == 0);
6552
6553 if (!isDNG)
6554 {
6555
6556 metadata.RebuildIPTC (host.Allocator (),
6557 isTIFF);
6558
6559 }
6560
6561 else
6562 {
6563
6564 metadata.ClearIPTC ();
6565
6566 }
6567
6568 // Clear format related XMP.
6569
6570 newXMP.ClearOrientation ();
6571
6572 newXMP.ClearImageInfo ();
6573
6574 newXMP.RemoveProperties (XMP_NS_DNG);
6575
6576 // Clear default camera raw settings if not writing to DNG.
6577
6578 if (!isDNG)
6579 {
6580
6581 newXMP.RemoveProperties (XMP_NS_CRD);
6582 newXMP.RemoveProperties (XMP_NS_CRLCP);
6583
6584 }
6585
6586 // All the formats we care about already keep the IPTC digest
6587 // elsewhere, do we don't need to write it to the XMP.
6588
6589 newXMP.ClearIPTCDigest ();
6590
6591 // Make sure that sidecar specific tags never get written to files.
6592
6593 newXMP.Remove (XMP_NS_PHOTOSHOP, "SidecarForExtension");
6594 newXMP.Remove (XMP_NS_PHOTOSHOP, "EmbeddedXMPDigest");
6595
6596 }
6597
6598 #endif // qDNGUseXMP
6599
6600 }
6601
6602
6603 /*****************************************************************************/
6604
6605 void dng_image_writer::UpdateExifColorSpaceTag (dng_metadata &metadata,
6606 const void *profileData,
6607 const uint32 profileSize)
6608 {
6609
6610 if (!metadata.GetExif ())
6611 {
6612 return;
6613 }
6614
6615 dng_exif &exif = *metadata.GetExif ();
6616
6617 if (profileData && profileSize)
6618 {
6619
6620 uint32 tagValue = 0xFFFF;
6621
6622 // Is the color profile sRGB IEC61966-2.1?
6623
6624 uint32 sRGB_size = 0;
6625 const uint8 *sRGB_data = 0;
6626
6627 if (dng_space_sRGB::Get ().ICCProfile (sRGB_size,
6628 sRGB_data))
6629 {
6630
6631 if ((sRGB_size == profileSize) &&
6632 !memcmp (profileData,
6633 (const void *) sRGB_data,
6634 (size_t) sRGB_size))
6635 {
6636
6637 // Yes.
6638
6639 tagValue = 1;
6640
6641 }
6642
6643 }
6644
6645 exif.fColorSpace = tagValue;
6646
6647 }
6648
6649 }
6650
6651 /*****************************************************************************/
6652
6653 void dng_image_writer::WriteTIFF (dng_host &host,
6654 dng_stream &stream,
6655 const dng_image &image,
6656 uint32 photometricInterpretation,
6657 uint32 compression,
6658 const dng_metadata *metadata,
6659 const dng_color_space *space,
6660 const dng_resolution *resolution,
6661 const dng_jpeg_preview *thumbnail,
6662 const dng_memory_block *imageResources,
6663 dng_metadata_subset metadataSubset,
6664 bool hasTransparency,
6665 bool allowBigTIFF,
6666 const dng_image *gainMapImage,
6667 const bool useHalfFloat)
6668 {
6669
6670 const void *profileData = NULL;
6671 uint32 profileSize = 0;
6672
6673 const uint8 *data = NULL;
6674 uint32 size = 0;
6675
6676 if (space && space->ICCProfile (size, data))
6677 {
6678
6679 profileData = data;
6680 profileSize = size;
6681
6682 }
6683
6684 WriteTIFFWithProfile (host,
6685 stream,
6686 image,
6687 photometricInterpretation,
6688 compression,
6689 metadata,
6690 profileData,
6691 profileSize,
6692 resolution,
6693 thumbnail,
6694 imageResources,
6695 metadataSubset,
6696 hasTransparency,
6697 allowBigTIFF,
6698 gainMapImage,
6699 useHalfFloat);
6700
6701 }
6702
6703 /*****************************************************************************/
6704
6705 static void SetupIFDfromCompressedImage (dng_ifd &info,
6706 const dng_lossy_compressed_image &compressedImage)
6707 {
6708
6709 info.fCompression = compressedImage.fCompressionCode;
6710
6711 info.fTileWidth = compressedImage.fTileSize.h;
6712 info.fTileLength = compressedImage.fTileSize.v;
6713
6714 info.fUsesStrips = compressedImage.fUsesStrips;
6715 info.fUsesTiles = !compressedImage.fUsesStrips;
6716
6717 for (uint32 j = 1; j < info.fSamplesPerPixel; j++)
6718 {
6719 info.fBitsPerSample [j] = compressedImage.fBitsPerSample;
6720 }
6721
6722 info.fRowInterleaveFactor = compressedImage.fRowInterleaveFactor;
6723 info.fColumnInterleaveFactor = compressedImage.fColumnInterleaveFactor;
6724
6725 info.fJXLDistance = compressedImage.JXLDistance ();
6726 info.fJXLEffort = compressedImage.JXLEffort ();
6727 info.fJXLDecodeSpeed = compressedImage.JXLDecodeSpeed ();
6728
6729 }
6730
6731 /*****************************************************************************/
6732
6733 static dng_ifd * MakeGainMapIFD (const dng_image &image,
6734 const dng_lossy_compressed_image *lossyCompressed,
6735 const uint32 compression)
6736 {
6737
6738 DNG_REQUIRE (image.Planes () == 1 ||
6739 image.Planes () == 3,
6740 "Invalid image plane count for MakeGainMapIFD");
6741
6742 AutoPtr<dng_ifd> result (new dng_ifd);
6743
6744 auto &ifd = *result;
6745
6746 ifd.fNewSubFileType = sfGainMap;
6747
6748 ifd.fImageWidth = image.Bounds ().W ();
6749 ifd.fImageLength = image.Bounds ().H ();
6750
6751 ifd.fSamplesPerPixel = image.Planes ();
6752
6753 ifd.fBitsPerSample [0] = TagTypeSize (image.PixelType ()) * 8;
6754
6755 for (uint32 j = 1; j < ifd.fSamplesPerPixel; j++)
6756 {
6757 ifd.fBitsPerSample [j] = ifd.fBitsPerSample [0];
6758 }
6759
6760 ifd.fPhotometricInterpretation = piGainMap;
6761
6762 ifd.fExtraSamplesCount = 0;
6763
6764 if (lossyCompressed)
6765 {
6766
6767 SetupIFDfromCompressedImage (ifd,
6768 *lossyCompressed);
6769
6770 }
6771
6772 else
6773 {
6774
6775 ifd.fCompression = compression;
6776
6777 if (ifd.fCompression == ccUncompressed)
6778 {
6779
6780 ifd.SetSingleStrip ();
6781
6782 }
6783
6784 else
6785 {
6786
6787 ifd.FindStripSize (128 * 1024);
6788
6789 // Deflate/ZIP.
6790
6791 if (ifd.fCompression == ccDeflate)
6792 {
6793
6794 if (image.PixelType () == ttFloat)
6795 {
6796 ifd.fPredictor = cpFloatingPoint;
6797 }
6798
6799 else
6800 {
6801 ifd.fPredictor = cpHorizontalDifference;
6802 }
6803
6804 }
6805
6806 }
6807
6808 }
6809
6810 return result.Release ();
6811
6812 }
6813
6814 /*****************************************************************************/
6815
6816 void dng_image_writer::WriteTIFFWithProfile (dng_host &host,
6817 dng_stream &stream,
6818 const dng_image &image,
6819 uint32 photometricInterpretation,
6820 uint32 compression,
6821 const dng_metadata *constMetadata,
6822 const void *profileData,
6823 uint32 profileSize,
6824 const dng_resolution *resolution,
6825 const dng_jpeg_preview *thumbnail,
6826 const dng_memory_block *imageResources,
6827 dng_metadata_subset metadataSubset,
6828 bool hasTransparency,
6829 bool allowBigTIFF,
6830 const dng_image *gainMapImage,
6831 const bool useHalfFloat)
6832 {
6833
6834 // Force writing all TIFF files in BigTIFF format.
6835
6836 #define qForceWriteBigTIFF 0
6837
6838 // Force writing stress test BigTIFF files with all file offsets 64-bit.
6839
6840 #define qStressTestBigTIFF 0
6841
6842 #if qStressTestBigTIFF
6843 const uint64 kStressTestBytes = 0x100000000ULL;
6844 #endif
6845
6846 AutoPtr<dng_metadata> metadata;
6847
6848 if (constMetadata)
6849 {
6850
6851 metadata.Reset (constMetadata->Clone (host.Allocator ()));
6852
6853 CleanUpMetadata (host,
6854 *metadata,
6855 metadataSubset,
6856 "image/tiff");
6857
6858 UpdateExifColorSpaceTag (*metadata,
6859 profileData,
6860 profileSize);
6861
6862 }
6863
6864 dng_ifd ifd;
6865
6866 ifd.fNewSubFileType = sfMainImage;
6867
6868 ifd.fImageWidth = image.Bounds ().W ();
6869 ifd.fImageLength = image.Bounds ().H ();
6870
6871 ifd.fSamplesPerPixel = image.Planes ();
6872
6873 if ((image.PixelType () == ttFloat) && useHalfFloat)
6874 ifd.fBitsPerSample [0] = 16;
6875
6876 else
6877 ifd.fBitsPerSample [0] = TagTypeSize (image.PixelType ()) * 8;
6878
6879 for (uint32 j = 1; j < ifd.fSamplesPerPixel; j++)
6880 {
6881 ifd.fBitsPerSample [j] = ifd.fBitsPerSample [0];
6882 }
6883
6884 ifd.fPhotometricInterpretation = photometricInterpretation;
6885
6886 ifd.fCompression = compression;
6887
6888 if (ifd.fCompression == ccUncompressed)
6889 {
6890
6891 ifd.SetSingleStrip ();
6892
6893 }
6894
6895 else
6896 {
6897
6898 if (ifd.fCompression == ccJXL)
6899 {
6900
6901 ifd.FindTileSize (2048 * 2048);
6902
6903 }
6904
6905 else
6906 {
6907
6908 ifd.FindStripSize (128 * 1024);
6909
6910 }
6911
6912 if (ifd.fCompression != ccJPEG &&
6913 ifd.fCompression != ccJXL)
6914 {
6915
6916 if (image.PixelType () == ttFloat)
6917 {
6918 ifd.fPredictor = cpFloatingPoint;
6919 }
6920
6921 else
6922 {
6923 ifd.fPredictor = cpHorizontalDifference;
6924 }
6925
6926 }
6927
6928 }
6929
6930 uint32 extraSamples = 0;
6931
6932 switch (photometricInterpretation)
6933 {
6934
6935 case piBlackIsZero:
6936 {
6937 extraSamples = image.Planes () - 1;
6938 break;
6939 }
6940
6941 case piRGB:
6942 case piCIELab:
6943 case piICCLab:
6944 {
6945 extraSamples = image.Planes () - 3;
6946 break;
6947 }
6948
6949 case piCMYK:
6950 {
6951 extraSamples = image.Planes () - 4;
6952 break;
6953 }
6954
6955 default:
6956 break;
6957
6958 }
6959
6960 ifd.fExtraSamplesCount = extraSamples;
6961
6962 if (hasTransparency && extraSamples)
6963 {
6964 ifd.fExtraSamples [0] = esAssociatedAlpha;
6965 }
6966
6967 if (image.PixelType () == ttFloat)
6968 {
6969
6970 for (uint32 j = 0; j < ifd.fSamplesPerPixel; j++)
6971 {
6972 ifd.fSampleFormat [j] = sfFloatingPoint;
6973 }
6974
6975 }
6976
6977 dng_tiff_directory mainIFD;
6978
6979 dng_basic_tag_set basic (mainIFD, ifd);
6980
6981 // Gain map.
6982
6983 dng_tiff_directory gainMapIFD;
6984
6985 AutoPtr<dng_basic_tag_set> gainMapTagSet;
6986
6987 AutoPtr<dng_ifd> gainMapImageIFD;
6988
6989 const bool hasGainMap = (gainMapImage != nullptr);
6990
6991 if (hasGainMap)
6992 {
6993
6994 uint32 gainMapCompression = compression;
6995
6996 if (gainMapImage->PixelType () == ttFloat &&
6997 gainMapCompression != ccDeflate)
6998 {
6999 gainMapCompression = ccUncompressed;
7000 }
7001
7002 gainMapImageIFD.Reset (MakeGainMapIFD (*gainMapImage,
7003 nullptr,
7004 gainMapCompression));
7005
7006 gainMapTagSet.Reset (new dng_basic_tag_set (gainMapIFD,
7007 *gainMapImageIFD));
7008
7009 }
7010
7011 // Resolution.
7012
7013 dng_resolution res;
7014
7015 if (resolution)
7016 {
7017 res = *resolution;
7018 }
7019
7020 tag_urational tagXResolution (tcXResolution, res.fXResolution);
7021 tag_urational tagYResolution (tcYResolution, res.fYResolution);
7022
7023 tag_uint16 tagResolutionUnit (tcResolutionUnit, res.fResolutionUnit);
7024
7025 if (resolution)
7026 {
7027 mainIFD.Add (&tagXResolution );
7028 mainIFD.Add (&tagYResolution );
7029 mainIFD.Add (&tagResolutionUnit);
7030 }
7031
7032 // ICC Profile.
7033
7034 tag_icc_profile iccProfileTag (profileData, profileSize);
7035
7036 if (iccProfileTag.Count ())
7037 {
7038 mainIFD.Add (&iccProfileTag);
7039 }
7040
7041 // XMP metadata.
7042
7043 #if qDNGUseXMP
7044
7045 tag_xmp tagXMP (metadata.Get () ? metadata->GetXMP () : NULL);
7046
7047 if (tagXMP.Count ())
7048 {
7049 mainIFD.Add (&tagXMP);
7050 }
7051
7052 #endif
7053
7054 // IPTC metadata.
7055
7056 tag_iptc tagIPTC (metadata.Get () ? metadata->IPTCData () : NULL,
7057 metadata.Get () ? metadata->IPTCLength () : 0);
7058
7059 if (tagIPTC.Count ())
7060 {
7061 mainIFD.Add (&tagIPTC);
7062 }
7063
7064 // Adobe data (thumbnail and IPTC digest)
7065
7066 AutoPtr<dng_memory_block> adobeData (BuildAdobeData (host,
7067 metadata.Get (),
7068 thumbnail,
7069 imageResources));
7070
7071 tag_uint8_ptr tagAdobe (tcAdobeData,
7072 adobeData->Buffer_uint8 (),
7073 adobeData->LogicalSize ());
7074
7075 if (tagAdobe.Count ())
7076 {
7077 mainIFD.Add (&tagAdobe);
7078 }
7079
7080 // Exif metadata.
7081
7082 const dng_exif emptyExif;
7083
7084 const dng_exif *metaExifPtr = metadata.Get () ? metadata->GetExif () : nullptr;
7085
7086 const dng_exif &exifRef = metaExifPtr ? *metaExifPtr : emptyExif;
7087
7088 exif_tag_set exifSet (mainIFD,
7089 exifRef,
7090 metadata.Get () ? metadata->IsMakerNoteSafe () : false,
7091 metadata.Get () ? metadata->MakerNoteData () : NULL,
7092 metadata.Get () ? metadata->MakerNoteLength () : 0,
7093 false);
7094
7095 // SubIFDs.
7096
7097 uint32 subFileCount = 0;
7098
7099 if (hasGainMap)
7100 subFileCount++;
7101
7102 // Add a link to the subIFDs.
7103
7104 tag_big_uints tagSubFile (tcSubIFDs,
7105 subFileCount);
7106
7107 if (subFileCount)
7108 mainIFD.Add (&tagSubFile);
7109
7110 // Find header size as 32-bit TIFF
7111
7112 uint64 headerSize32 = 8 +
7113 mainIFD.Size () +
7114 exifSet.Size () +
7115 (hasGainMap ? gainMapIFD.Size () : 0);
7116
7117 // Find header size as 64-bit TIFF
7118
7119 mainIFD.SetBigTIFF (true);
7120 exifSet.SetBigTIFF (true);
7121
7122 if (hasGainMap)
7123 gainMapIFD.SetBigTIFF (true);
7124
7125 uint64 headerSize64 = 16 +
7126 mainIFD.Size () +
7127 exifSet.Size () +
7128 (hasGainMap ? gainMapIFD.Size () : 0);
7129
7130 // Find maximum size of non-header size.
7131
7132 uint64 maxNonHeaderSize =
7133 (ifd.MaxImageDataByteCount () +
7134 (hasGainMap ? gainMapImageIFD->MaxImageDataByteCount () : 0));
7135
7136 // Maximum target size of 32-bit TIFF files that allows some slop for
7137 // future metadata edits.
7138
7139 const uint64 kMaxTargetNonBigTIFFSize = 0xFFFFFFFF - 16 * 1024 * 1024;
7140
7141 // Don't reserve extra space if we know we are not going to use it.
7142
7143 if (headerSize32 + maxNonHeaderSize < kMaxTargetNonBigTIFFSize)
7144 {
7145 allowBigTIFF = false;
7146 }
7147
7148 #if qForceWriteBigTIFF || qStressTestBigTIFF
7149
7150 allowBigTIFF = true;
7151
7152 #if qCRStressTestBigTIFF
7153 headerSize64 += kStressTestBytes;
7154 #endif
7155
7156 #endif
7157
7158 // Reserve enough space for 64-bit header.
7159
7160 uint64 headerSize = allowBigTIFF ? headerSize64
7161 : headerSize32;
7162
7163 stream.SetWritePosition (headerSize);
7164
7165 // Write the main image data.
7166
7167 WriteImage (host,
7168 ifd,
7169 basic,
7170 stream,
7171 image);
7172
7173 // Write the gain map image.
7174
7175 if (gainMapImage)
7176 {
7177
7178 WriteImage (host,
7179 *gainMapImageIFD,
7180 *gainMapTagSet,
7181 stream,
7182 *gainMapImage);
7183
7184 }
7185
7186 // If we are not allowed to write BigTIFF, and the file
7187 // is over 4GB limit, throw an error.
7188
7189 if (!allowBigTIFF)
7190 {
7191
7192 if (stream.Position () > 0xFFFFFFFF)
7193 {
7194 ThrowImageTooBigTIFF ();
7195 }
7196
7197 }
7198
7199 // Trim the file to this length.
7200
7201 stream.SetLength (stream.Position ());
7202
7203 // Decide if we should write 32 or 64 bit header.
7204
7205 bool isBigTIFF = allowBigTIFF && (stream.Length () > kMaxTargetNonBigTIFFSize);
7206
7207 #if qForceWriteBigTIFF || qStressTestBigTIFF
7208 isBigTIFF = allowBigTIFF;
7209 #endif
7210
7211 mainIFD.SetBigTIFF (isBigTIFF);
7212 exifSet.SetBigTIFF (isBigTIFF);
7213
7214 if (hasGainMap)
7215 gainMapIFD.SetBigTIFF (isBigTIFF);
7216
7217 // Write header.
7218
7219 stream.SetWritePosition (0);
7220
7221 stream.Put_uint16 (stream.BigEndian () ? byteOrderMM : byteOrderII);
7222
7223 if (isBigTIFF)
7224 {
7225
7226 stream.Put_uint16 (magicBigTIFF);
7227
7228 stream.Put_uint16 (8);
7229 stream.Put_uint16 (0);
7230
7231 #if qStressTestBigTIFF
7232 stream.Put_uint64 (16 + kStressTestBytes);
7233 stream.PutZeros (kStressTestBytes);
7234 #else
7235 stream.Put_uint64 (16);
7236 #endif
7237
7238 }
7239
7240 else
7241 {
7242
7243 stream.Put_uint16 (magicTIFF);
7244
7245 stream.Put_uint32 (8);
7246
7247 }
7248
7249 // Write IFDs.
7250
7251 uint64 offsetMainIFD = stream.Position ();
7252
7253 uint64 offsetExifData = offsetMainIFD + mainIFD.Size ();
7254
7255 uint64 offsetGainMapIFD = offsetExifData + exifSet.Size ();
7256
7257 exifSet.Locate (offsetExifData);
7258
7259 if (hasGainMap)
7260 tagSubFile.Set (0, offsetGainMapIFD);
7261
7262 mainIFD.Put (stream);
7263
7264 exifSet.Put (stream);
7265
7266 if (hasGainMap)
7267 gainMapIFD.Put (stream);
7268
7269 if (headerSize > stream.Position ())
7270 {
7271
7272 stream.PutZeros (headerSize - stream.Position ());
7273
7274 }
7275
7276 stream.Flush ();
7277
7278 }
7279
7280 /*****************************************************************************/
7281
7282 void dng_image_writer::WriteDNG (dng_host &host,
7283 dng_stream &stream,
7284 dng_negative &negative,
7285 const dng_preview_list *previewList,
7286 uint32 maxBackwardVersion,
7287 bool uncompressed,
7288 bool allowBigTIFF,
7289 const dng_image *gainMapImage,
7290 const dng_lossy_compressed_image *gainMapLossyCompressed)
7291 {
7292
7293 WriteDNGWithMetadata (host,
7294 stream,
7295 negative,
7296 negative.Metadata (),
7297 previewList,
7298 maxBackwardVersion,
7299 uncompressed,
7300 allowBigTIFF,
7301 gainMapImage,
7302 gainMapLossyCompressed);
7303
7304 }
7305
7306 /*****************************************************************************/
7307
7308 static bool HasDNGOpcode_1_6 (const dng_negative &negative,
7309 bool includeOptional)
7310 {
7311
7312 const uint32 version = dngVersion_1_6_0_0;
7313
7314 return (negative.OpcodeList1 ().MinVersion (includeOptional) >= version ||
7315 negative.OpcodeList2 ().MinVersion (includeOptional) >= version ||
7316 negative.OpcodeList3 ().MinVersion (includeOptional) >= version);
7317
7318 }
7319
7320 /*****************************************************************************/
7321
7322 #if qDNGDebug
7323
7324 class dng_verify_size_estimate
7325 {
7326
7327 private:
7328
7329 dng_stream &fStream;
7330
7331 uint64 fStart;
7332
7333 uint64 fEstimate;
7334
7335 const char *fMessage;
7336
7337 public:
7338
7339 dng_verify_size_estimate (dng_stream &stream,
7340 uint64 estimate,
7341 const char *message)
7342
7343 : fStream (stream)
7344 , fStart (stream.Position ())
7345 , fEstimate (estimate)
7346 , fMessage (message)
7347
7348 {
7349
7350 }
7351
7352 ~dng_verify_size_estimate ()
7353 {
7354
7355 uint64 actual = fStream.Position () - fStart;
7356
7357 char message [2048];
7358
7359 snprintf (message,
7360 2048,
7361 "%s: actual size = %llu, estimated size = %llu",
7362 fMessage,
7363 (unsigned long long) actual,
7364 (unsigned long long) fEstimate);
7365
7366 DNG_ASSERT (actual <= fEstimate, message);
7367
7368 #if 0
7369 fprintf (stderr, "%s\n", message);
7370 #endif
7371
7372 }
7373
7374 };
7375
7376 #define DNG_VERIFY_SIZE_ESTIMATE(stream,estimate,message) \
7377 dng_verify_size_estimate verify (stream, estimate, message);
7378
7379 #else
7380
7381 #define DNG_VERIFY_SIZE_ESTIMATE(stream,estimate,message) \
7382 (void) estimate;
7383
7384 #endif
7385
7386 /*****************************************************************************/
7387
7388 static void SetEncodeSettingsForIFD (const dng_image &image,
7389 const bool uncompressed,
7390 const uint32 maxBackwardVersion,
7391 dng_ifd &info,
7392 const dng_lossy_compressed_image *compressedImage = nullptr)
7393 {
7394
7395 const bool isFloat = (image.PixelType () == ttFloat);
7396
7397 // Set sample format for floating-point data.
7398
7399 if (isFloat)
7400 {
7401
7402 for (uint32 i = 0; i < info.fSamplesPerPixel; i++)
7403 info.fSampleFormat [i] = sfFloatingPoint;
7404
7405 }
7406
7407 // If we already have a lossy compressed version of image, use that.
7408
7409 if (compressedImage)
7410 {
7411
7412 SetupIFDfromCompressedImage (info, *compressedImage);
7413
7414 return;
7415
7416 }
7417
7418 // Pick compression method.
7419
7420 if (uncompressed)
7421 {
7422
7423 info.fCompression = ccUncompressed;
7424
7425 }
7426
7427 else if (isFloat)
7428 {
7429
7430 info.fCompression = ccDeflate;
7431
7432 }
7433
7434 else if (image.PixelType () == ttLong)
7435
7436 {
7437
7438 if (maxBackwardVersion >= dngVersion_1_4_0_0)
7439 info.fCompression = ccDeflate;
7440
7441 else
7442 info.fCompression = ccUncompressed;
7443
7444 }
7445
7446 else
7447 {
7448
7449 // Lossless JPEG.
7450
7451 info.fCompression = ccJPEG;
7452
7453 }
7454
7455 // Uncompressed.
7456
7457 if (info.fCompression == ccUncompressed)
7458 {
7459
7460 info.fPredictor = cpNullPredictor;
7461
7462 info.SetSingleStrip ();
7463
7464 }
7465
7466 // Deflate.
7467
7468 else if (info.fCompression == ccDeflate)
7469 {
7470
7471 info.fPredictor = isFloat ? cpFloatingPoint
7472 : cpHorizontalDifference;
7473
7474 info.FindTileSize (512 * 1024);
7475
7476 }
7477
7478 // Everything else, including lossy and lossless JPEG.
7479
7480 else
7481 {
7482
7483 info.FindTileSize (128 * 1024);
7484
7485 }
7486
7487 }
7488
7489 /*****************************************************************************/
7490
7491 void dng_image_writer::WriteDNGWithMetadata (dng_host &host,
7492 dng_stream &stream,
7493 const dng_negative &negative,
7494 const dng_metadata &constMetadata,
7495 const dng_preview_list *previewList,
7496 const uint32 maxBackwardVersion,
7497 const bool uncompressed,
7498 bool allowBigTIFF,
7499 const dng_image *gainMapImage,
7500 const dng_lossy_compressed_image *gainMapLossyCompressed)
7501 {
7502
7503 // Force writing all DNG files in 64-bit format.
7504
7505 #define qForceWriteBigDNG 0
7506
7507 // Force writing stress test 64-bit DNG files with all file offsets 64-bit.
7508
7509 #define qStressTestBigDNG 0
7510
7511 #if qStressTestBigDNG
7512 const uint64 kStressTestBytes = 0x100000000ULL;
7513 #endif
7514
7515 // Clean up metadata per MWG recommendations.
7516
7517 AutoPtr<dng_metadata> metadata (constMetadata.Clone (host.Allocator ()));
7518
7519 CleanUpMetadata (host,
7520 *metadata,
7521 kMetadataSubset_All,
7522 "image/dng");
7523
7524 // Was the original file lossy compressed with JPEG or some other method?
7525
7526 const dng_lossy_compressed_image *rawLossyCompressedImage =
7527 negative.RawLossyCompressedImage ();
7528
7529 // If not, then if there was a raw lossy compressed digest,
7530 // we need to compute the image digest.
7531
7532 if (!rawLossyCompressedImage && negative.RawLossyCompressedImageDigest ().IsValid ())
7533 {
7534
7535 negative.ClearRawLossyCompressedImageDigest ();
7536
7537 negative.ClearRawImageDigest ();
7538
7539 }
7540
7541 // See if we need to discard the raw lossy compressed image.
7542
7543 if (rawLossyCompressedImage)
7544 {
7545
7546 if (uncompressed ||
7547 maxBackwardVersion < MinBackwardVersionForCompression
7548 (rawLossyCompressedImage->fCompressionCode) ||
7549 (rawLossyCompressedImage->fColumnInterleaveFactor != 1 &&
7550 maxBackwardVersion < dngVersion_1_7_1_0))
7551 {
7552
7553 rawLossyCompressedImage = nullptr;
7554
7555 negative.ClearRawLossyCompressedImageDigest ();
7556
7557 negative.ClearRawImageDigest ();
7558
7559 }
7560
7561 }
7562
7563 // Is this a floating point image that we are saving?
7564
7565 const bool isFloatingPoint =
7566 ((negative.RawImage ().PixelType () == ttFloat) ||
7567 (negative.RawImage ().PixelType () == ttHalfFloat));
7568
7569 // Should we save a compressed 32-bit integer file?
7570
7571 const bool isCompressed32BitInteger = (negative.RawImage ().PixelType () == ttLong) &&
7572 (maxBackwardVersion >= dngVersion_1_4_0_0) &&
7573 (!uncompressed);
7574
7575 // Get a copy of the mosaic info.
7576
7577 dng_mosaic_info mosaicInfo;
7578
7579 if (negative.GetMosaicInfo ())
7580 {
7581 mosaicInfo = *(negative.GetMosaicInfo ());
7582 }
7583
7584 // Figure out the compression to use. Most of the time this is lossless
7585 // JPEG.
7586
7587 uint32 compression = uncompressed ? ccUncompressed : ccJPEG;
7588
7589 if (!uncompressed)
7590 {
7591
7592 // If we have some lossy compressed data, just use that.
7593
7594 if (rawLossyCompressedImage)
7595 compression = rawLossyCompressedImage->fCompressionCode;
7596
7597 // For floating point, we only support ZIP.
7598
7599 else if (isFloatingPoint)
7600 compression = ccDeflate;
7601
7602 // For 32-bit integer images, we only support ZIP and uncompressed.
7603
7604 else if (negative.RawImage ().PixelType () == ttLong)
7605 compression = isCompressed32BitInteger ? ccDeflate : ccUncompressed;
7606
7607 // Fall back to Lossless JPEG.
7608
7609 else
7610 compression = ccJPEG;
7611
7612 }
7613
7614 // Are we saving the original size tags?
7615
7616 bool saveOriginalDefaultFinalSize = false;
7617 bool saveOriginalBestQualityFinalSize = false;
7618 bool saveOriginalDefaultCropSize = false;
7619
7620 {
7621
7622 // See if we are saving a proxy image.
7623
7624 dng_point defaultFinalSize (negative.DefaultFinalHeight (),
7625 negative.DefaultFinalWidth ());
7626
7627 saveOriginalDefaultFinalSize = (negative.OriginalDefaultFinalSize () !=
7628 defaultFinalSize);
7629
7630 if (saveOriginalDefaultFinalSize)
7631 {
7632
7633 // If the save OriginalDefaultFinalSize tag, this changes the defaults
7634 // for the OriginalBestQualityFinalSize and OriginalDefaultCropSize tags.
7635
7636 saveOriginalBestQualityFinalSize = (negative.OriginalBestQualityFinalSize () !=
7637 negative.OriginalDefaultFinalSize ());
7638
7639 saveOriginalDefaultCropSize = (negative.OriginalDefaultCropSizeV () !=
7640 dng_urational (negative.OriginalDefaultFinalSize ().v, 1)) ||
7641 (negative.OriginalDefaultCropSizeH () !=
7642 dng_urational (negative.OriginalDefaultFinalSize ().h, 1));
7643
7644 }
7645
7646 else
7647 {
7648
7649 // Else these two tags default to the normal non-proxy size image values.
7650
7651 dng_point bestQualityFinalSize (negative.BestQualityFinalHeight (),
7652 negative.BestQualityFinalWidth ());
7653
7654 saveOriginalBestQualityFinalSize = (negative.OriginalBestQualityFinalSize () !=
7655 bestQualityFinalSize);
7656
7657 saveOriginalDefaultCropSize = (negative.OriginalDefaultCropSizeV () !=
7658 negative.DefaultCropSizeV ()) ||
7659 (negative.OriginalDefaultCropSizeH () !=
7660 negative.DefaultCropSizeH ());
7661
7662 }
7663
7664 }
7665
7666 // Does this image have a transparency mask?
7667
7668 bool hasTransparencyMask = (negative.RawTransparencyMask () != NULL);
7669
7670 const dng_lossy_compressed_image *rawLossyCompressedTransparencyMask =
7671 negative.RawLossyCompressedTransparencyMask ();
7672
7673 if (rawLossyCompressedTransparencyMask &&
7674 (maxBackwardVersion <
7675 MinBackwardVersionForCompression (rawLossyCompressedTransparencyMask->fCompressionCode)))
7676 {
7677 rawLossyCompressedTransparencyMask = nullptr;
7678 }
7679
7680 // Does the image have depth mask?
7681
7682 bool hasDepthMap = (negative.RawDepthMap () != NULL);
7683
7684 // Should we save the enhanced stage 3 image?
7685
7686 bool hasEnhancedImage = (&negative.RawImage () != negative.Stage3Image ()) &&
7687 negative.EnhanceParams ().NotEmpty ();
7688
7689 // Profile and other color related tags. Do this up front so that we can
7690 // determine how the set of profiles influences the DNG version and
7691 // backward version tags.
7692
7693 AutoPtr<profile_tag_set> profileSet;
7694
7695 AutoPtr<color_tag_set> colorSet;
7696
7697 std::vector<uint32> extraProfileIndex;
7698
7699 dng_camera_profile mainProfile;
7700
7701 bool hasProfileWith_1_6_Features = false;
7702 bool hasProfileWith_1_7_Features = false;
7703
7704 // Create the main IFD.
7705
7706 dng_tiff_directory mainIFD;
7707
7708 if (!negative.IsMonochrome ())
7709 {
7710
7711 (void) negative.GetProfileToEmbed (constMetadata, mainProfile);
7712
7713 if (mainProfile.Uses_1_6_Features ())
7714 {
7715 hasProfileWith_1_6_Features = true;
7716 }
7717
7718 if (mainProfile.Uses_1_7_Features ())
7719 {
7720 hasProfileWith_1_7_Features = true;
7721 }
7722
7723 profileSet.Reset (new profile_tag_set (host,
7724 mainIFD,
7725 mainProfile));
7726
7727 colorSet.Reset (new color_tag_set (mainIFD,
7728 negative));
7729
7730 // Build list of profile indices to include in extra profiles tag.
7731
7732 uint32 profileCount = negative.ProfileCount ();
7733
7734 for (uint32 index = 0; index < profileCount; index++)
7735 {
7736
7737 const dng_camera_profile &profile (negative.ProfileByIndex (index));
7738
7739 if (profile.WasReadFromDNG () &&
7740 !profile.Name ().Matches (mainProfile.Name ().Get ()))
7741 {
7742
7743 extraProfileIndex.push_back (index);
7744
7745 if (profile.Uses_1_6_Features ())
7746 {
7747 hasProfileWith_1_6_Features = true;
7748 }
7749
7750 if (profile.Uses_1_7_Features ())
7751 {
7752 hasProfileWith_1_7_Features = true;
7753 }
7754
7755 }
7756
7757 }
7758
7759 }
7760
7761 // Does the negative have a valid ImageSequenceInfo tag?
7762
7763 const bool hasImageSequenceInfo = metadata->ImageSequenceInfo ().IsValid ();
7764
7765 // Does the negative has a valid ImageStats tag?
7766
7767 const bool hasImageStats =
7768 ((metadata->ImageStats ().TagCount () > 0) &&
7769 metadata->ImageStats ().IsValidForPlaneCount (negative.ColorChannels ()));
7770
7771 // Does the negative have a valid ProfileGainTableMap2 tag?
7772
7773 const bool hasProfileGainTableMap2 =
7774 (negative.HasProfileGainTableMap () &&
7775 negative.ProfileGainTableMap ().RequiresVersion2 ());
7776
7777 // Does the negative use the HDR output-referred colorimetric reference?
7778
7779 const bool hasHDRColorimetricRef =
7780 (negative.ColorimetricReference () == crOutputReferredHDR);
7781
7782 // Embedded big table tags.
7783
7784 big_table_tag_set bigTableTagSet (host,
7785 mainIFD,
7786 metadata->BigTableDictionary (),
7787 metadata->BigTableGroupIndex ());
7788
7789 // Gain map.
7790
7791 dng_tiff_directory gainMapIFD;
7792
7793 AutoPtr<dng_basic_tag_set> gainMapTagSet;
7794
7795 AutoPtr<dng_ifd> gainMapImageIFD;
7796
7797 const bool hasGainMap = (gainMapImage != nullptr);
7798
7799 if (hasGainMap)
7800 {
7801
7802 uint32 gainMapCompression = (gainMapImage->PixelType () == ttFloat)
7803 ? ccDeflate
7804 : ccJPEG;
7805
7806 gainMapImageIFD.Reset (MakeGainMapIFD (*gainMapImage,
7807 gainMapLossyCompressed,
7808 gainMapCompression));
7809
7810 gainMapTagSet.Reset (new dng_basic_tag_set (gainMapIFD,
7811 *gainMapImageIFD));
7812
7813 }
7814
7815 // Figure out what main version to use.
7816
7817 uint32 dngVersion = dngVersion_1_4_0_0;
7818 uint32 dngBackwardVersion = dngVersion_1_1_0_0;
7819
7820 // Check DNG 1.7 feature usage.
7821
7822 bool has_1_7_Features = false;
7823
7824 if (compression == ccJXL)
7825 {
7826
7827 has_1_7_Features = true;
7828
7829 }
7830
7831 else if (hasTransparencyMask &&
7832 rawLossyCompressedTransparencyMask &&
7833 rawLossyCompressedTransparencyMask->fCompressionCode == ccJXL)
7834 {
7835
7836 has_1_7_Features = true;
7837
7838 }
7839
7840 else if (hasEnhancedImage &&
7841 negative.EnhancedLossyCompressedImage () &&
7842 negative.EnhancedLossyCompressedImage ()->fCompressionCode == ccJXL)
7843 {
7844
7845 has_1_7_Features = true;
7846
7847 }
7848
7849 else if (hasDepthMap &&
7850 negative.RawLossyCompressedDepthMap () &&
7851 negative.RawLossyCompressedDepthMap ()->fCompressionCode == ccJXL)
7852 {
7853
7854 has_1_7_Features = true;
7855
7856 }
7857
7858 else if (negative.HasSemanticMask ())
7859 {
7860
7861 for (uint32 j = 0; j < negative.NumSemanticMasks (); j++)
7862 {
7863
7864 const auto &rawMask = negative.RawSemanticMask (j);
7865
7866 if (rawMask.fLossyCompressed.get () &&
7867 rawMask.fLossyCompressed->fCompressionCode == ccJXL)
7868 {
7869 has_1_7_Features = true;
7870 }
7871
7872 }
7873
7874 }
7875
7876 if (previewList && !has_1_7_Features)
7877 {
7878
7879 for (uint32 j = 0; j < previewList->Count (); j++)
7880 {
7881
7882 dng_tiff_directory tempDirectory;
7883
7884 AutoPtr<dng_basic_tag_set> tempBasic (previewList->Preview (j).AddTagSet (host,
7885 tempDirectory));
7886
7887 if (tempBasic.Get () && tempBasic->Compression () == ccJXL)
7888 {
7889 has_1_7_Features = true;
7890 break;
7891 }
7892
7893 }
7894
7895 }
7896
7897 // Check other DNG 1.7 feature usage.
7898
7899 if (has_1_7_Features ||
7900 hasImageStats ||
7901 hasImageSequenceInfo ||
7902 hasHDRColorimetricRef ||
7903 hasProfileGainTableMap2 ||
7904 hasProfileWith_1_7_Features ||
7905 hasGainMap )
7906 {
7907
7908 dngVersion = Max_uint32 (dngVersion, dngVersion_1_7_0_0);
7909
7910 }
7911
7912 // Check DNG 1.6 feature usage.
7913
7914 const bool hasRGBTables =
7915 (negative.ProfileCount () > 0 &&
7916 negative.ProfileByIndex (0).HasMaskedRGBTables ());
7917
7918 if (HasDNGOpcode_1_6 (negative, false) || // don't include optional opcodes
7919 hasProfileWith_1_6_Features ||
7920 negative.HasSemanticMask () ||
7921 negative.HasProfileGainTableMap () ||
7922 hasRGBTables)
7923 {
7924
7925 dngVersion = Max_uint32 (dngVersion, dngVersion_1_6_0_0);
7926
7927 }
7928
7929 // Check DNG 1.5 feature usage.
7930
7931 if (hasDepthMap || hasEnhancedImage)
7932 {
7933
7934 dngVersion = Max_uint32 (dngVersion, dngVersion_1_5_0_0);
7935
7936 }
7937
7938 #if defined(qTestRowInterleave) || defined(qTestSubTileBlockRows) || defined(qTestSubTileBlockCols)
7939 dngBackwardVersion = Max_uint32 (dngBackwardVersion, dngVersion_1_2_0_0);
7940 #endif
7941
7942 #if defined(qTestColumnInterleave)
7943 dngBackwardVersion = Max_uint32 (dngBackwardVersion, dngVersion_1_7_1_0);
7944 #endif
7945
7946 dngBackwardVersion = Max_uint32 (dngBackwardVersion,
7947 negative.OpcodeList1 ().MinVersion (false));
7948
7949 dngBackwardVersion = Max_uint32 (dngBackwardVersion,
7950 negative.OpcodeList2 ().MinVersion (false));
7951
7952 dngBackwardVersion = Max_uint32 (dngBackwardVersion,
7953 negative.OpcodeList3 ().MinVersion (false));
7954
7955 if (negative.GetMosaicInfo () &&
7956 negative.GetMosaicInfo ()->fCFALayout >= 6)
7957 {
7958 dngBackwardVersion = Max_uint32 (dngBackwardVersion, dngVersion_1_3_0_0);
7959 }
7960
7961 if (isFloatingPoint || hasTransparencyMask || isCompressed32BitInteger)
7962 {
7963 dngBackwardVersion = Max_uint32 (dngBackwardVersion, dngVersion_1_4_0_0);
7964 }
7965
7966 if (rawLossyCompressedImage)
7967 {
7968
7969 dngBackwardVersion =
7970 Max_uint32 (dngBackwardVersion,
7971 MinBackwardVersionForCompression
7972 (rawLossyCompressedImage->fCompressionCode));
7973
7974 if (rawLossyCompressedImage->fColumnInterleaveFactor != 1)
7975 {
7976 dngBackwardVersion = Max_uint32 (dngBackwardVersion, dngVersion_1_7_1_0);
7977 }
7978
7979 }
7980
7981 if (rawLossyCompressedTransparencyMask)
7982 {
7983 dngBackwardVersion =
7984 Max_uint32 (dngBackwardVersion,
7985 MinBackwardVersionForCompression
7986 (rawLossyCompressedTransparencyMask->fCompressionCode));
7987 }
7988
7989 // The dngVersion must be at least the dngBackwardVersion.
7990
7991 dngVersion = Max_uint32 (dngVersion, dngBackwardVersion);
7992
7993 // Our computed dngBackwardVersion should never be higher than the maxBackwardVersion.
7994
7995 DNG_REQUIRE (dngBackwardVersion <= maxBackwardVersion,
7996 "dngBackwardVersion too high");
7997
7998 // Find best thumbnail from preview list, if any.
7999
8000 const dng_preview *thumbnail = NULL;
8001
8002 if (previewList)
8003 {
8004
8005 uint32 thumbArea = 0;
8006
8007 for (uint32 j = 0; j < previewList->Count (); j++)
8008 {
8009
8010 const dng_preview &preview (previewList->Preview (j));
8011
8012 if ((preview.NewSubFileType () == sfPreviewImage) &&
8013 (preview.PhotometricInterpretation () == piBlackIsZero ||
8014 preview.PhotometricInterpretation () == piRGB ||
8015 preview.PhotometricInterpretation () == piYCbCr))
8016 {
8017
8018 uint32 thisArea = preview.ImageWidth () *
8019 preview.ImageLength ();
8020
8021 if (!thumbnail || thisArea < thumbArea)
8022 {
8023
8024 thumbnail = &preview;
8025
8026 thumbArea = thisArea;
8027
8028 }
8029
8030 }
8031
8032 }
8033
8034 }
8035
8036 // Create the IFD for the raw data. If there is no thumnail, this is
8037 // just a reference the main IFD. Otherwise allocate a new one.
8038
8039 AutoPtr<dng_tiff_directory> rawIFD_IfNotMain;
8040
8041 if (thumbnail)
8042 {
8043 rawIFD_IfNotMain.Reset (new dng_tiff_directory);
8044 }
8045
8046 dng_tiff_directory &rawIFD (thumbnail ? *rawIFD_IfNotMain : mainIFD);
8047
8048 // Include DNG version tags.
8049
8050 uint8 dngVersionData [4];
8051
8052 dngVersionData [0] = (uint8) (dngVersion >> 24);
8053 dngVersionData [1] = (uint8) (dngVersion >> 16);
8054 dngVersionData [2] = (uint8) (dngVersion >> 8);
8055 dngVersionData [3] = (uint8) (dngVersion );
8056
8057 tag_uint8_ptr tagDNGVersion (tcDNGVersion, dngVersionData, 4);
8058
8059 mainIFD.Add (&tagDNGVersion);
8060
8061 uint8 dngBackwardVersionData [4];
8062
8063 dngBackwardVersionData [0] = (uint8) (dngBackwardVersion >> 24);
8064 dngBackwardVersionData [1] = (uint8) (dngBackwardVersion >> 16);
8065 dngBackwardVersionData [2] = (uint8) (dngBackwardVersion >> 8);
8066 dngBackwardVersionData [3] = (uint8) (dngBackwardVersion );
8067
8068 tag_uint8_ptr tagDNGBackwardVersion (tcDNGBackwardVersion, dngBackwardVersionData, 4);
8069
8070 mainIFD.Add (&tagDNGBackwardVersion);
8071
8072 // The main IFD contains the thumbnail, if there is a thumbnail.
8073
8074 AutoPtr<dng_basic_tag_set> thmBasic;
8075
8076 if (thumbnail)
8077 {
8078 thmBasic.Reset (thumbnail->AddTagSet (host, mainIFD));
8079 }
8080
8081 // Get the raw image we are writing.
8082
8083 const dng_image &rawImage (negative.RawImage ());
8084
8085 // Create a dng_ifd record for the raw image.
8086
8087 dng_ifd info;
8088
8089 info.fImageWidth = rawImage.Width ();
8090 info.fImageLength = rawImage.Height ();
8091
8092 info.fSamplesPerPixel = rawImage.Planes ();
8093
8094 info.fPhotometricInterpretation = mosaicInfo.IsColorFilterArray () ? piCFA
8095 : piLinearRaw;
8096
8097 info.fCompression = compression;
8098
8099 if (isFloatingPoint && (compression == ccDeflate))
8100 {
8101
8102 info.fPredictor = cpFloatingPoint;
8103
8104 if (mosaicInfo.IsColorFilterArray ())
8105 {
8106
8107 if (mosaicInfo.fCFAPatternSize.h == 2)
8108 {
8109 info.fPredictor = cpFloatingPointX2;
8110 }
8111
8112 else if (mosaicInfo.fCFAPatternSize.h == 4)
8113 {
8114 info.fPredictor = cpFloatingPointX4;
8115 }
8116
8117 }
8118
8119 }
8120
8121 if (isCompressed32BitInteger)
8122 {
8123
8124 info.fPredictor = cpHorizontalDifference;
8125
8126 if (mosaicInfo.IsColorFilterArray ())
8127 {
8128
8129 if (mosaicInfo.fCFAPatternSize.h == 2)
8130 {
8131 info.fPredictor = cpHorizontalDifferenceX2;
8132 }
8133
8134 else if (mosaicInfo.fCFAPatternSize.h == 4)
8135 {
8136 info.fPredictor = cpHorizontalDifferenceX4;
8137 }
8138
8139 }
8140
8141 }
8142
8143 uint32 rawPixelType = rawImage.PixelType ();
8144
8145 if (rawPixelType == ttShort)
8146 {
8147
8148 // See if we are using a linearization table with <= 256 entries, in which
8149 // case the useful data will all fit within 8-bits.
8150
8151 const dng_linearization_info *rangeInfo = negative.GetLinearizationInfo ();
8152
8153 if (rangeInfo)
8154 {
8155
8156 if (rangeInfo->fLinearizationTable.Get ())
8157 {
8158
8159 uint32 entries = rangeInfo->fLinearizationTable->LogicalSize () >> 1;
8160
8161 if (entries <= 256)
8162 {
8163
8164 rawPixelType = ttByte;
8165
8166 }
8167
8168 }
8169
8170 }
8171
8172 }
8173
8174 switch (rawPixelType)
8175 {
8176
8177 case ttByte:
8178 {
8179 info.fBitsPerSample [0] = 8;
8180 break;
8181 }
8182
8183 case ttShort:
8184 {
8185 info.fBitsPerSample [0] = 16;
8186 break;
8187 }
8188
8189 case ttLong:
8190 {
8191 info.fBitsPerSample [0] = 32;
8192 break;
8193 }
8194
8195 case ttFloat:
8196 {
8197
8198 if (negative.RawFloatBitDepth () == 16)
8199 {
8200 info.fBitsPerSample [0] = 16;
8201 }
8202
8203 else if (negative.RawFloatBitDepth () == 24)
8204 {
8205 info.fBitsPerSample [0] = 24;
8206 }
8207
8208 else
8209 {
8210 info.fBitsPerSample [0] = 32;
8211 }
8212
8213 for (uint32 j = 0; j < info.fSamplesPerPixel; j++)
8214 {
8215 info.fSampleFormat [j] = sfFloatingPoint;
8216 }
8217
8218 break;
8219
8220 }
8221
8222 default:
8223 {
8224 ThrowProgramError ();
8225 }
8226
8227 }
8228
8229 // For lossless JPEG compression, we often lie about the
8230 // actual channel count to get the predictors to work across
8231 // same color mosaic pixels.
8232
8233 uint32 fakeChannels = 1;
8234
8235 if (info.fCompression == ccJPEG)
8236 {
8237
8238 if (mosaicInfo.IsColorFilterArray ())
8239 {
8240
8241 if (mosaicInfo.fCFAPatternSize.h == 4)
8242 {
8243 fakeChannels = 4;
8244 }
8245
8246 else if (mosaicInfo.fCFAPatternSize.h == 2)
8247 {
8248 fakeChannels = 2;
8249 }
8250
8251 // However, lossless JEPG is limited to four channels,
8252 // so compromise might be required.
8253
8254 while (fakeChannels * info.fSamplesPerPixel > 4 &&
8255 fakeChannels > 1)
8256 {
8257
8258 fakeChannels >>= 1;
8259
8260 }
8261
8262 }
8263
8264 }
8265
8266 // Figure out tile sizes.
8267
8268 if (rawLossyCompressedImage)
8269 {
8270
8271 SetupIFDfromCompressedImage (info, *rawLossyCompressedImage);
8272
8273 }
8274
8275 else if (info.fCompression == ccJPEG)
8276 {
8277
8278 info.FindTileSize (128 * 1024);
8279
8280 }
8281
8282 else if (info.fCompression == ccDeflate)
8283 {
8284
8285 info.FindTileSize (512 * 1024);
8286
8287 }
8288
8289 else if (info.fCompression == ccJXL)
8290 {
8291
8292 ThrowProgramError ("No JXL compressed image");
8293
8294 }
8295
8296 else if (info.fCompression == ccLossyJPEG)
8297 {
8298
8299 ThrowProgramError ("No JPEG compressed image");
8300
8301 }
8302
8303 // Don't use tiles for uncompressed images.
8304
8305 else
8306 {
8307
8308 info.SetSingleStrip ();
8309
8310 }
8311
8312 #ifdef qTestRowInterleave
8313 info.fRowInterleaveFactor = qTestRowInterleave;
8314 fakeChannels = 1;
8315 #endif
8316
8317 #ifdef qTestColumnInterleave
8318 info.fColumnInterleaveFactor = qTestColumnInterleave;
8319 fakeChannels = 1;
8320 #endif
8321
8322 #if defined(qTestSubTileBlockRows) && defined(qTestSubTileBlockCols)
8323
8324 info.fSubTileBlockRows = qTestSubTileBlockRows;
8325 info.fSubTileBlockCols = qTestSubTileBlockCols;
8326
8327 if (fakeChannels == 2)
8328 fakeChannels = 4;
8329
8330 #endif
8331
8332 // Basic information.
8333
8334 dng_basic_tag_set rawBasic (rawIFD, info);
8335
8336 // TODO(erichan): For lossy compressed images, perhaps call a virtual
8337 // method to add special tags if needed.
8338
8339 // JPEG tables, if any.
8340
8341 tag_data_ptr tagJPEGTables (tcJPEGTables,
8342 ttUndefined,
8343 0,
8344 NULL);
8345
8346 if (rawLossyCompressedImage && rawLossyCompressedImage->JPEGTables ())
8347 {
8348
8349 tagJPEGTables.SetData (rawLossyCompressedImage->JPEGTables ()->Buffer ());
8350
8351 tagJPEGTables.SetCount (rawLossyCompressedImage->JPEGTables ()->LogicalSize ());
8352
8353 rawIFD.Add (&tagJPEGTables);
8354
8355 }
8356
8357 // DefaultScale tag.
8358
8359 dng_urational defaultScaleData [2];
8360
8361 defaultScaleData [0] = negative.RawDefaultScaleH ().IsValid () ?
8362 negative.RawDefaultScaleH () :
8363 negative.DefaultScaleH ();
8364
8365 defaultScaleData [1] = negative.RawDefaultScaleV ().IsValid () ?
8366 negative.RawDefaultScaleV () :
8367 negative.DefaultScaleV ();
8368
8369 tag_urational_ptr tagDefaultScale (tcDefaultScale,
8370 defaultScaleData,
8371 2);
8372
8373 rawIFD.Add (&tagDefaultScale);
8374
8375 // Best quality scale tag.
8376
8377 tag_urational tagBestQualityScale (tcBestQualityScale,
8378 negative.RawBestQualityScale ().IsValid () ?
8379 negative.RawBestQualityScale () :
8380 negative.BestQualityScale ());
8381
8382 rawIFD.Add (&tagBestQualityScale);
8383
8384 // DefaultCropOrigin tag.
8385
8386 dng_urational defaultCropOriginData [2];
8387
8388 defaultCropOriginData [0] = negative.RawDefaultCropOriginH ().IsValid () ?
8389 negative.RawDefaultCropOriginH () :
8390 negative.DefaultCropOriginH ();
8391
8392 defaultCropOriginData [1] = negative.RawDefaultCropOriginV ().IsValid () ?
8393 negative.RawDefaultCropOriginV () :
8394 negative.DefaultCropOriginV ();
8395
8396 tag_urational_ptr tagDefaultCropOrigin (tcDefaultCropOrigin,
8397 defaultCropOriginData,
8398 2);
8399
8400 rawIFD.Add (&tagDefaultCropOrigin);
8401
8402 // DefaultCropSize tag.
8403
8404 dng_urational defaultCropSizeData [2];
8405
8406 defaultCropSizeData [0] = negative.RawDefaultCropSizeH ().IsValid () ?
8407 negative.RawDefaultCropSizeH () :
8408 negative.DefaultCropSizeH ();
8409
8410 defaultCropSizeData [1] = negative.RawDefaultCropSizeV ().IsValid () ?
8411 negative.RawDefaultCropSizeV () :
8412 negative.DefaultCropSizeV ();
8413
8414 tag_urational_ptr tagDefaultCropSize (tcDefaultCropSize,
8415 defaultCropSizeData,
8416 2);
8417
8418 rawIFD.Add (&tagDefaultCropSize);
8419
8420 // DefaultUserCrop tag.
8421
8422 dng_urational defaultUserCropData [4];
8423
8424 defaultUserCropData [0] = negative.DefaultUserCropT ();
8425 defaultUserCropData [1] = negative.DefaultUserCropL ();
8426 defaultUserCropData [2] = negative.DefaultUserCropB ();
8427 defaultUserCropData [3] = negative.DefaultUserCropR ();
8428
8429 tag_urational_ptr tagDefaultUserCrop (tcDefaultUserCrop,
8430 defaultUserCropData,
8431 4);
8432
8433 if (negative.HasDefaultUserCrop ())
8434 {
8435
8436 rawIFD.Add (&tagDefaultUserCrop);
8437
8438 }
8439
8440 // Range mapping tag set.
8441
8442 range_tag_set rangeSet (rawIFD, negative);
8443
8444 // Mosaic pattern information.
8445
8446 mosaic_tag_set mosaicSet (rawIFD, mosaicInfo);
8447
8448 // Chroma blur radius.
8449
8450 tag_urational tagChromaBlurRadius (tcChromaBlurRadius,
8451 negative.ChromaBlurRadius ());
8452
8453 if (negative.ChromaBlurRadius ().IsValid ())
8454 {
8455
8456 rawIFD.Add (&tagChromaBlurRadius);
8457
8458 }
8459
8460 // Anti-alias filter strength.
8461
8462 tag_urational tagAntiAliasStrength (tcAntiAliasStrength,
8463 negative.AntiAliasStrength ());
8464
8465 if (negative.AntiAliasStrength ().IsValid ())
8466 {
8467
8468 rawIFD.Add (&tagAntiAliasStrength);
8469
8470 }
8471
8472 // Extra camera profiles tag.
8473
8474 uint32 extraProfileCount = (uint32) extraProfileIndex.size ();
8475
8476 tag_big_uints extraProfileTag (tcExtraCameraProfiles,
8477 extraProfileCount);
8478
8479 if (extraProfileCount)
8480 {
8481
8482 mainIFD.Add (&extraProfileTag);
8483
8484 }
8485
8486 // Other tags.
8487
8488 tag_uint16 tagOrientation (tcOrientation,
8489 (uint16) negative.ComputeOrientation (constMetadata).GetTIFF ());
8490
8491 mainIFD.Add (&tagOrientation);
8492
8493 tag_srational tagBaselineExposure (tcBaselineExposure,
8494 negative.BaselineExposureR ());
8495
8496 mainIFD.Add (&tagBaselineExposure);
8497
8498 tag_urational tagBaselineNoise (tcBaselineNoise,
8499 negative.BaselineNoiseR ());
8500
8501 mainIFD.Add (&tagBaselineNoise);
8502
8503 dng_urational rawNoiseReductionApplied = hasEnhancedImage ?
8504 negative.RawNoiseReductionApplied () :
8505 negative.NoiseReductionApplied ();
8506
8507 tag_urational tagNoiseReductionAppliedMainIFD (tcNoiseReductionApplied,
8508 rawNoiseReductionApplied);
8509
8510 tag_urational tagNoiseReductionAppliedRawIFD (tcNoiseReductionApplied,
8511 rawNoiseReductionApplied);
8512
8513 if (rawNoiseReductionApplied.IsValid ())
8514 {
8515
8516 rawIFD.Add (&tagNoiseReductionAppliedRawIFD);
8517
8518 // Kludge: DNG spec says that the NoiseReductionApplied tag should be
8519 // in the Raw IFD, not main IFD. However, we also write a copy of this tag to
8520 // main IFD to deal with legacy DNG readers that try to read the tag
8521 // from the main IFD.
8522
8523 if ((&rawIFD) != (&mainIFD))
8524 {
8525
8526 mainIFD.Add (&tagNoiseReductionAppliedMainIFD);
8527
8528 }
8529
8530 }
8531
8532 dng_noise_profile rawNoiseProfile = hasEnhancedImage ?
8533 negative.RawNoiseProfile () :
8534 negative.NoiseProfile ();
8535
8536 tag_dng_noise_profile tagNoiseProfileMainIFD (rawNoiseProfile);
8537 tag_dng_noise_profile tagNoiseProfileRawIFD (rawNoiseProfile);
8538
8539 if (rawNoiseProfile.IsValidForNegative (negative))
8540 {
8541
8542 rawIFD.Add (&tagNoiseProfileRawIFD);
8543
8544 // Kludge: DNG spec says that NoiseProfile tag should be in the Raw
8545 // IFD, not main IFD. However, we also write a copy of this tag to
8546 // main IFD to deal with legacy DNG readers that try to read the tag
8547 // from the main IFD.
8548
8549 if ((&rawIFD) != (&mainIFD))
8550 {
8551
8552 mainIFD.Add (&tagNoiseProfileMainIFD);
8553
8554 }
8555
8556 }
8557
8558 tag_urational tagBaselineSharpness (tcBaselineSharpness,
8559 negative.RawBaselineSharpness ().IsValid () && hasEnhancedImage ?
8560 negative.RawBaselineSharpness () :
8561 negative.BaselineSharpnessR ());
8562
8563 mainIFD.Add (&tagBaselineSharpness);
8564
8565 tag_string tagUniqueName (tcUniqueCameraModel,
8566 negative.ModelName (),
8567 true);
8568
8569 mainIFD.Add (&tagUniqueName);
8570
8571 tag_string tagLocalName (tcLocalizedCameraModel,
8572 negative.LocalName (),
8573 false);
8574
8575 if (negative.LocalName ().NotEmpty ())
8576 {
8577
8578 mainIFD.Add (&tagLocalName);
8579
8580 }
8581
8582 tag_urational tagShadowScale (tcShadowScale,
8583 negative.ShadowScaleR ());
8584
8585 mainIFD.Add (&tagShadowScale);
8586
8587 tag_uint16 tagColorimetricReference (tcColorimetricReference,
8588 (uint16) negative.ColorimetricReference ());
8589
8590 if (negative.IsOutputReferred ())
8591 {
8592
8593 mainIFD.Add (&tagColorimetricReference);
8594
8595 }
8596
8597 const bool useNewDigest = (maxBackwardVersion >= dngVersion_1_4_0_0);
8598
8599 dng_fingerprint mainImageRawImageDigest;
8600
8601 if (rawLossyCompressedImage)
8602 {
8603
8604 negative.FindRawLossyCompressedImageDigest (host);
8605
8606 mainImageRawImageDigest = negative.RawLossyCompressedImageDigest ();
8607
8608 }
8609
8610 else if (rawLossyCompressedTransparencyMask)
8611 {
8612
8613 // For the edge case of a lossy compressed transparency mask, and a lossless
8614 // raw image, the raw image digest will not safely round trip, so don't write it.
8615
8616 }
8617
8618 else
8619 {
8620
8621 if (useNewDigest)
8622 {
8623 negative.FindNewRawImageDigest (host);
8624 mainImageRawImageDigest = negative.NewRawImageDigest ();
8625 }
8626
8627 else
8628 {
8629 negative.FindRawImageDigest (host);
8630 mainImageRawImageDigest = negative.RawImageDigest ();
8631 }
8632
8633 }
8634
8635 tag_uint8_ptr tagRawImageDigest (useNewDigest ? tcNewRawImageDigest : tcRawImageDigest,
8636 mainImageRawImageDigest.data,
8637 16);
8638
8639 if (mainImageRawImageDigest.IsValid ())
8640 {
8641
8642 mainIFD.Add (&tagRawImageDigest);
8643
8644 }
8645
8646 negative.FindRawDataUniqueID (host);
8647
8648 // Make a local copy of the raw data unique ID.
8649
8650 const auto rawDataUniqueID = negative.RawDataUniqueID ();
8651
8652 tag_uint8_ptr tagRawDataUniqueID (tcRawDataUniqueID,
8653 rawDataUniqueID.data,
8654 16);
8655
8656 if (rawDataUniqueID.IsValid ())
8657 {
8658
8659 mainIFD.Add (&tagRawDataUniqueID);
8660
8661 }
8662
8663 tag_string tagOriginalRawFileName (tcOriginalRawFileName,
8664 negative.OriginalRawFileName (),
8665 false);
8666
8667 if (negative.HasOriginalRawFileName ())
8668 {
8669
8670 mainIFD.Add (&tagOriginalRawFileName);
8671
8672 }
8673
8674 negative.FindOriginalRawFileDigest ();
8675
8676 tag_data_ptr tagOriginalRawFileData (tcOriginalRawFileData,
8677 ttUndefined,
8678 negative.OriginalRawFileDataLength (),
8679 negative.OriginalRawFileData ());
8680
8681 tag_uint8_ptr tagOriginalRawFileDigest (tcOriginalRawFileDigest,
8682 negative.OriginalRawFileDigest ().data,
8683 16);
8684
8685 if (negative.OriginalRawFileData ())
8686 {
8687
8688 mainIFD.Add (&tagOriginalRawFileData);
8689
8690 mainIFD.Add (&tagOriginalRawFileDigest);
8691
8692 }
8693
8694 // XMP metadata.
8695
8696 #if qDNGUseXMP
8697
8698 tag_xmp tagXMP (metadata->GetXMP ());
8699
8700 if (tagXMP.Count ())
8701 {
8702
8703 mainIFD.Add (&tagXMP);
8704
8705 }
8706
8707 #endif
8708
8709 // Exif tags.
8710
8711 exif_tag_set exifSet (mainIFD,
8712 *metadata->GetExif (),
8713 metadata->IsMakerNoteSafe (),
8714 metadata->MakerNoteData (),
8715 metadata->MakerNoteLength (),
8716 true);
8717
8718 // Private data.
8719
8720 tag_uint8_ptr tagPrivateData (tcDNGPrivateData,
8721 negative.PrivateData (),
8722 negative.PrivateLength ());
8723
8724 if (negative.PrivateLength ())
8725 {
8726
8727 mainIFD.Add (&tagPrivateData);
8728
8729 }
8730
8731 // Proxy size tags.
8732
8733 uint32 originalDefaultFinalSizeData [2];
8734
8735 originalDefaultFinalSizeData [0] = negative.OriginalDefaultFinalSize ().h;
8736 originalDefaultFinalSizeData [1] = negative.OriginalDefaultFinalSize ().v;
8737
8738 tag_uint32_ptr tagOriginalDefaultFinalSize (tcOriginalDefaultFinalSize,
8739 originalDefaultFinalSizeData,
8740 2);
8741
8742 if (saveOriginalDefaultFinalSize)
8743 {
8744
8745 mainIFD.Add (&tagOriginalDefaultFinalSize);
8746
8747 }
8748
8749 uint32 originalBestQualityFinalSizeData [2];
8750
8751 originalBestQualityFinalSizeData [0] = negative.OriginalBestQualityFinalSize ().h;
8752 originalBestQualityFinalSizeData [1] = negative.OriginalBestQualityFinalSize ().v;
8753
8754 tag_uint32_ptr tagOriginalBestQualityFinalSize (tcOriginalBestQualityFinalSize,
8755 originalBestQualityFinalSizeData,
8756 2);
8757
8758 if (saveOriginalBestQualityFinalSize)
8759 {
8760
8761 mainIFD.Add (&tagOriginalBestQualityFinalSize);
8762
8763 }
8764
8765 dng_urational originalDefaultCropSizeData [2];
8766
8767 originalDefaultCropSizeData [0] = negative.OriginalDefaultCropSizeH ();
8768 originalDefaultCropSizeData [1] = negative.OriginalDefaultCropSizeV ();
8769
8770 tag_urational_ptr tagOriginalDefaultCropSize (tcOriginalDefaultCropSize,
8771 originalDefaultCropSizeData,
8772 2);
8773
8774 if (saveOriginalDefaultCropSize)
8775 {
8776
8777 mainIFD.Add (&tagOriginalDefaultCropSize);
8778
8779 }
8780
8781 // Opcode list 1.
8782
8783 AutoPtr<dng_memory_block> opcodeList1Data (negative.OpcodeList1 ().Spool (host));
8784
8785 tag_data_ptr tagOpcodeList1 (tcOpcodeList1,
8786 ttUndefined,
8787 opcodeList1Data.Get () ? opcodeList1Data->LogicalSize () : 0,
8788 opcodeList1Data.Get () ? opcodeList1Data->Buffer () : NULL);
8789
8790 if (opcodeList1Data.Get ())
8791 {
8792
8793 rawIFD.Add (&tagOpcodeList1);
8794
8795 }
8796
8797 // Opcode list 2.
8798
8799 AutoPtr<dng_memory_block> opcodeList2Data (negative.OpcodeList2 ().Spool (host));
8800
8801 tag_data_ptr tagOpcodeList2 (tcOpcodeList2,
8802 ttUndefined,
8803 opcodeList2Data.Get () ? opcodeList2Data->LogicalSize () : 0,
8804 opcodeList2Data.Get () ? opcodeList2Data->Buffer () : NULL);
8805
8806 if (opcodeList2Data.Get ())
8807 {
8808
8809 rawIFD.Add (&tagOpcodeList2);
8810
8811 }
8812
8813 // Opcode list 3.
8814
8815 AutoPtr<dng_memory_block> opcodeList3Data (negative.OpcodeList3 ().Spool (host));
8816
8817 tag_data_ptr tagOpcodeList3 (tcOpcodeList3,
8818 ttUndefined,
8819 opcodeList3Data.Get () ? opcodeList3Data->LogicalSize () : 0,
8820 opcodeList3Data.Get () ? opcodeList3Data->Buffer () : NULL);
8821
8822 if (opcodeList3Data.Get ())
8823 {
8824
8825 rawIFD.Add (&tagOpcodeList3);
8826
8827 }
8828
8829 // ProfileGainTableMap.
8830
8831 AutoPtr<dng_memory_block> profileGainTableMapBlock;
8832
8833 uint16 tagCodeForPGTM = tcProfileGainTableMap;
8834
8835 if (negative.HasProfileGainTableMap () &&
8836
8837 // If the main profile already has the PGTM attached, let the profile
8838 // logic take care of writing the PGTM. Otherwise we would end up
8839 // writing two identical PGTM tags into IFD 0.
8840
8841 (negative.ShareProfileGainTableMap () !=
8842 mainProfile.ShareProfileGainTableMap ()))
8843 {
8844
8845 dng_memory_stream tempStream (host.Allocator (),
8846 host.Sniffer ());
8847
8848 const auto &gainTableMap = negative.ProfileGainTableMap ();
8849
8850 gainTableMap.PutStream (tempStream);
8851
8852 profileGainTableMapBlock.Reset
8853 (tempStream.AsMemoryBlock (host.Allocator ()));
8854
8855 if (gainTableMap.RequiresVersion2 ())
8856 tagCodeForPGTM = tcProfileGainTableMap2;
8857
8858 }
8859
8860 tag_data_ptr tagProfileGainTableMapBlock
8861 (tagCodeForPGTM,
8862 ttUndefined,
8863 profileGainTableMapBlock.Get () ? profileGainTableMapBlock->LogicalSize () : 0,
8864 profileGainTableMapBlock.Get () ? profileGainTableMapBlock->Buffer () : NULL);
8865
8866 if (profileGainTableMapBlock.Get ())
8867 {
8868
8869 if (tagCodeForPGTM == tcProfileGainTableMap2)
8870 mainIFD.Add (&tagProfileGainTableMapBlock);
8871
8872 else
8873 rawIFD.Add (&tagProfileGainTableMapBlock);
8874
8875 }
8876
8877 // ImageSequenceInfo.
8878
8879 AutoPtr<tiff_tag> tagImageSequenceInfo;
8880
8881 if (metadata->ImageSequenceInfo ().IsValid ())
8882 {
8883
8884 tagImageSequenceInfo.Reset
8885 (metadata->ImageSequenceInfo ().MakeTag (host.Allocator ()));
8886
8887 mainIFD.Add (tagImageSequenceInfo.Get ());
8888
8889 }
8890
8891 // ImageStats.
8892
8893 AutoPtr<tiff_tag> tagImageStats;
8894
8895 {
8896
8897 const auto &stats = metadata->ImageStats ();
8898
8899 if (stats.IsValidForPlaneCount (negative.ColorChannels ()) &&
8900 (stats.TagCount () > 0))
8901 {
8902
8903 tagImageStats.Reset (stats.MakeTag (host.Allocator ()));
8904
8905 rawIFD.Add (tagImageStats.Get ());
8906
8907 }
8908
8909 }
8910
8911 // Transparency mask, if any.
8912
8913 AutoPtr<dng_ifd> maskInfo;
8914
8915 AutoPtr<dng_tiff_directory> maskIFD;
8916
8917 AutoPtr<dng_basic_tag_set> maskBasic;
8918
8919 if (hasTransparencyMask)
8920 {
8921
8922 // Create mask IFD.
8923
8924 maskInfo.Reset (new dng_ifd);
8925
8926 maskInfo->fNewSubFileType = sfTransparencyMask;
8927
8928 maskInfo->fImageWidth = negative.RawTransparencyMask ()->Bounds ().W ();
8929 maskInfo->fImageLength = negative.RawTransparencyMask ()->Bounds ().H ();
8930
8931 maskInfo->fSamplesPerPixel = 1;
8932
8933 maskInfo->fBitsPerSample [0] = negative.RawTransparencyMaskBitDepth ();
8934
8935 maskInfo->fPhotometricInterpretation = piTransparencyMask;
8936
8937 SetEncodeSettingsForIFD (*negative.RawTransparencyMask (),
8938 uncompressed,
8939 maxBackwardVersion,
8940 *maskInfo,
8941 rawLossyCompressedTransparencyMask);
8942
8943 // Create mask tiff directory.
8944
8945 maskIFD.Reset (new dng_tiff_directory);
8946
8947 // Add mask basic tag set.
8948
8949 maskBasic.Reset (new dng_basic_tag_set (*maskIFD, *maskInfo));
8950
8951 }
8952
8953 AutoPtr<dng_ifd> depthInfo;
8954
8955 AutoPtr<dng_tiff_directory> depthIFD;
8956
8957 AutoPtr<dng_basic_tag_set> depthBasic;
8958
8959 tag_uint16 tagDepthFormat (tcDepthFormat,
8960 (uint16) negative.DepthFormat ());
8961
8962 tag_urational tagDepthNear (tcDepthNear,
8963 negative.DepthNear ());
8964
8965 tag_urational tagDepthFar (tcDepthFar,
8966 negative.DepthFar ());
8967
8968 tag_uint16 tagDepthUnits (tcDepthUnits,
8969 (uint16) negative.DepthUnits ());
8970
8971 tag_uint16 tagDepthMeasureType (tcDepthMeasureType,
8972 (uint16) negative.DepthMeasureType ());
8973
8974 if (hasDepthMap)
8975 {
8976
8977 // Create depth IFD.
8978
8979 depthInfo.Reset (new dng_ifd);
8980
8981 depthInfo->fNewSubFileType = sfDepthMap;
8982
8983 depthInfo->fImageWidth = negative.RawDepthMap ()->Bounds ().W ();
8984 depthInfo->fImageLength = negative.RawDepthMap ()->Bounds ().H ();
8985
8986 depthInfo->fSamplesPerPixel = 1;
8987
8988 depthInfo->fBitsPerSample [0] = negative.RawDepthMap ()->PixelSize () * 8;
8989
8990 depthInfo->fPhotometricInterpretation = piDepth;
8991
8992 SetEncodeSettingsForIFD (*negative.RawDepthMap (),
8993 uncompressed,
8994 maxBackwardVersion,
8995 *depthInfo,
8996 negative.RawLossyCompressedDepthMap ());
8997
8998 // Create mask tiff directory.
8999
9000 depthIFD.Reset (new dng_tiff_directory);
9001
9002 // Add mask basic tag set.
9003
9004 depthBasic.Reset (new dng_basic_tag_set (*depthIFD, *depthInfo));
9005
9006 // Depth metadata.
9007
9008 mainIFD.Add (&tagDepthFormat);
9009 mainIFD.Add (&tagDepthNear);
9010 mainIFD.Add (&tagDepthFar);
9011 mainIFD.Add (&tagDepthUnits);
9012 mainIFD.Add (&tagDepthMeasureType);
9013
9014 }
9015
9016 // Enhanced stage 3 image.
9017
9018 AutoPtr<dng_ifd> enhancedInfo;
9019
9020 AutoPtr<dng_tiff_directory> enhancedIFD;
9021
9022 AutoPtr<dng_basic_tag_set> enhancedBasic;
9023
9024 tag_string enhanceParams (tcEnhanceParams,
9025 negative.EnhanceParams (),
9026 false);
9027
9028 tag_urational enhanceBaselineSharpness (tcBaselineSharpness,
9029 negative.BaselineSharpnessR ());
9030
9031 tag_urational enhanceNoiseReductionApplied (tcNoiseReductionApplied,
9032 negative.NoiseReductionApplied ());
9033
9034 tag_dng_noise_profile enhanceNoiseProfile (negative.NoiseProfile ());
9035
9036 uint16 enhanceBlackLevelData [kMaxColorPlanes];
9037
9038 tag_uint16_ptr enhanceBlackLevel (tcBlackLevel,
9039 enhanceBlackLevelData);
9040
9041 dng_urational enhanceDefaultScaleData [2];
9042
9043 enhanceDefaultScaleData [0] = negative.DefaultScaleH ();
9044 enhanceDefaultScaleData [1] = negative.DefaultScaleV ();
9045
9046 tag_urational_ptr enhanceDefaultScale (tcDefaultScale,
9047 enhanceDefaultScaleData,
9048 2);
9049
9050 tag_urational enhanceBestQualityScale (tcBestQualityScale,
9051 negative.BestQualityScale ());
9052
9053 dng_urational enhanceDefaultCropOriginData [2];
9054
9055 enhanceDefaultCropOriginData [0] = negative.DefaultCropOriginH ();
9056 enhanceDefaultCropOriginData [1] = negative.DefaultCropOriginV ();
9057
9058 tag_urational_ptr enhanceDefaultCropOrigin (tcDefaultCropOrigin,
9059 enhanceDefaultCropOriginData,
9060 2);
9061
9062 dng_urational enhanceDefaultCropSizeData [2];
9063
9064 enhanceDefaultCropSizeData [0] = negative.DefaultCropSizeH ();
9065 enhanceDefaultCropSizeData [1] = negative.DefaultCropSizeV ();
9066
9067 tag_urational_ptr enhanceDefaultCropSize (tcDefaultCropSize,
9068 enhanceDefaultCropSizeData,
9069 2);
9070
9071 if (hasEnhancedImage)
9072 {
9073
9074 // Create enhanced IFD.
9075
9076 enhancedInfo.Reset (new dng_ifd);
9077
9078 enhancedInfo->fNewSubFileType = sfEnhancedImage;
9079
9080 enhancedInfo->fImageWidth = negative.Stage3Image ()->Bounds ().W ();
9081 enhancedInfo->fImageLength = negative.Stage3Image ()->Bounds ().H ();
9082
9083 enhancedInfo->fSamplesPerPixel = negative.Stage3Image ()->Planes ();
9084
9085 const bool isEnhancedFloat =
9086 (negative.Stage3Image ()->PixelType () == ttFloat);
9087
9088 for (uint32 plane = 0; plane < enhancedInfo->fSamplesPerPixel; plane++)
9089 {
9090
9091 if (isEnhancedFloat)
9092 enhancedInfo->fBitsPerSample [plane] = 16;
9093
9094 else
9095 enhancedInfo->fBitsPerSample [plane] =
9096 negative.Stage3Image ()->PixelSize () * 8;
9097
9098 }
9099
9100 enhancedInfo->fPhotometricInterpretation = piLinearRaw;
9101
9102 SetEncodeSettingsForIFD (*negative.Stage3Image (),
9103 uncompressed,
9104 maxBackwardVersion,
9105 *enhancedInfo,
9106 negative.EnhancedLossyCompressedImage ());
9107
9108 // Create enhanced tiff directory.
9109
9110 enhancedIFD.Reset (new dng_tiff_directory);
9111
9112 // Add enhanced basic tag set.
9113
9114 enhancedBasic.Reset (new dng_basic_tag_set (*enhancedIFD, *enhancedInfo));
9115
9116 // Add EnhanceParams tag.
9117
9118 enhancedIFD->Add (&enhanceParams);
9119
9120 // Record the enhanced baseline sharpness tag, if different.
9121
9122 if (negative.RawBaselineSharpness () != negative.BaselineSharpnessR ())
9123 {
9124
9125 enhancedIFD->Add (&enhanceBaselineSharpness);
9126
9127 }
9128
9129 // Record the enhanced noise reduction applied, if different.
9130
9131 if (negative.RawNoiseReductionApplied () != negative.NoiseReductionApplied ())
9132 {
9133
9134 enhancedIFD->Add (&enhanceNoiseReductionApplied);
9135
9136 }
9137
9138 // Record the enhanced noise profile, if different.
9139
9140 if (negative.RawNoiseProfile () != negative.NoiseProfile ())
9141 {
9142
9143 enhancedIFD->Add (&enhanceNoiseProfile);
9144
9145 }
9146
9147 // Record stage3 black level.
9148
9149 if (negative.Stage3BlackLevel ())
9150 {
9151
9152 for (uint32 plane = 0; plane < enhancedInfo->fSamplesPerPixel; plane++)
9153 {
9154
9155 enhanceBlackLevelData [plane] = negative.Stage3BlackLevel ();
9156
9157 }
9158
9159 enhanceBlackLevel.SetCount (enhancedInfo->fSamplesPerPixel);
9160
9161 enhancedIFD->Add (&enhanceBlackLevel);
9162
9163 }
9164
9165 // Record the default scale, if different.
9166
9167 if (negative.RawDefaultScaleH () != negative.DefaultScaleH () ||
9168 negative.RawDefaultScaleV () != negative.DefaultScaleV ())
9169 {
9170
9171 enhancedIFD->Add (&enhanceDefaultScale);
9172
9173 }
9174
9175 // Record the best quality scale, if different.
9176
9177 if (negative.RawBestQualityScale () != negative.BestQualityScale ())
9178 {
9179
9180 enhancedIFD->Add (&enhanceBestQualityScale);
9181
9182 }
9183
9184 // Record the default crop, if different.
9185
9186 if (negative.RawDefaultCropSizeH () != negative.DefaultCropSizeH () ||
9187 negative.RawDefaultCropSizeV () != negative.DefaultCropSizeV () ||
9188 negative.RawDefaultCropOriginH () != negative.DefaultCropOriginH () ||
9189 negative.RawDefaultCropOriginV () != negative.DefaultCropOriginV ())
9190 {
9191
9192 enhancedIFD->Add (&enhanceDefaultCropSize);
9193
9194 enhancedIFD->Add (&enhanceDefaultCropOrigin);
9195
9196 }
9197
9198 }
9199
9200 // Semantic masks.
9201
9202 std::vector<std::unique_ptr<dng_ifd> > semanticMaskInfo;
9203 std::vector<std::unique_ptr<dng_tiff_directory> > semanticMaskIFD;
9204 std::vector<std::unique_ptr<dng_basic_tag_set> > semanticMaskBasic;
9205 std::vector<std::unique_ptr<tag_string> > semanticNameTags;
9206 std::vector<std::unique_ptr<tag_string> > semanticInstanceIDTags;
9207 std::vector<std::unique_ptr<tag_data_ptr> > semanticXMPTags;
9208 std::vector<std::unique_ptr<tag_uint32_ptr> > semanticMaskSubAreaTags;
9209
9210 uint32 semanticMaskCount = 0;
9211
9212 if (negative.HasSemanticMask ())
9213 {
9214
9215 semanticMaskCount = negative.NumSemanticMasks ();
9216
9217 semanticMaskInfo .resize (semanticMaskCount);
9218 semanticMaskIFD .resize (semanticMaskCount);
9219 semanticMaskBasic .resize (semanticMaskCount);
9220 semanticNameTags .resize (semanticMaskCount);
9221 semanticInstanceIDTags .resize (semanticMaskCount);
9222 semanticXMPTags .resize (semanticMaskCount);
9223 semanticMaskSubAreaTags.resize (semanticMaskCount);
9224
9225 for (uint32 j = 0; j < semanticMaskCount; j++)
9226 {
9227
9228 semanticMaskInfo [j].reset (new dng_ifd);
9229
9230 auto &smInfo = *semanticMaskInfo [j];
9231
9232 smInfo.fNewSubFileType = sfSemanticMask;
9233
9234 const auto &rawMask = negative.RawSemanticMask (j);
9235
9236 smInfo.fImageWidth = rawMask.fMask->Width ();
9237 smInfo.fImageLength = rawMask.fMask->Height ();
9238
9239 smInfo.fSamplesPerPixel = 1;
9240
9241 smInfo.fBitsPerSample [0] = rawMask.fMask->PixelSize () * 8;
9242
9243 smInfo.fPhotometricInterpretation = piPhotometricMask;
9244
9245 SetEncodeSettingsForIFD (*rawMask.fMask,
9246 uncompressed,
9247 maxBackwardVersion,
9248 smInfo,
9249 rawMask.fLossyCompressed.get ());
9250
9251 // Create mask tiff directory.
9252
9253 semanticMaskIFD [j].reset (new dng_tiff_directory);
9254
9255 // Add mask basic tag set.
9256
9257 semanticMaskBasic [j].reset
9258 (new dng_basic_tag_set (*semanticMaskIFD [j],
9259 smInfo));
9260
9261 // Create semantic name, if present.
9262
9263 if (rawMask.fName.NotEmpty ())
9264 {
9265
9266 semanticNameTags [j].reset (new tag_string (tcSemanticName,
9267 rawMask.fName,
9268 false));
9269
9270 // Add this tag to the IFD.
9271
9272 semanticMaskIFD [j]->Add (semanticNameTags [j].get ());
9273
9274 }
9275
9276 // Create semantic instance ID, if present.
9277
9278 if (rawMask.fInstanceID.NotEmpty ())
9279 {
9280
9281 semanticInstanceIDTags [j].reset (new tag_string (tcSemanticInstanceID,
9282 rawMask.fInstanceID,
9283 false));
9284
9285 // Add this tag to the IFD.
9286
9287 semanticMaskIFD [j]->Add (semanticInstanceIDTags [j].get ());
9288
9289 }
9290
9291 // Create XMP block, if present.
9292
9293 if (rawMask.fXMP)
9294 {
9295
9296 semanticXMPTags [j].reset (new tag_data_ptr (tcXMP,
9297 ttUndefined,
9298 rawMask.fXMP->LogicalSize (),
9299 rawMask.fXMP->Buffer ()));
9300
9301 semanticMaskIFD [j]->Add (semanticXMPTags [j].get ());
9302
9303 }
9304
9305 // Include MaskSubArea tag, if valid.
9306
9307 if (rawMask.IsMaskSubAreaValid ())
9308 {
9309
9310 semanticMaskSubAreaTags [j].reset
9311 (new tag_uint32_ptr (tcMaskSubArea,
9312 &rawMask.fMaskSubArea [0],
9313 4));
9314
9315 // Add this tag to the IFD.
9316
9317 semanticMaskIFD [j]->Add (semanticMaskSubAreaTags [j].get ());
9318
9319 }
9320
9321 }
9322
9323 }
9324
9325 // Add other subfiles.
9326
9327 uint32 subFileCount = thumbnail ? 1 : 0;
9328
9329 if (hasTransparencyMask)
9330 {
9331 subFileCount++;
9332 }
9333
9334 if (hasDepthMap)
9335 {
9336 subFileCount++;
9337 }
9338
9339 if (hasEnhancedImage)
9340 {
9341 subFileCount++;
9342 }
9343
9344 if (hasGainMap)
9345 {
9346 subFileCount++;
9347 }
9348
9349 subFileCount += semanticMaskCount;
9350
9351 // Add previews.
9352
9353 uint32 previewCount = previewList ? previewList->Count () : 0;
9354
9355 std::vector<std::unique_ptr<dng_tiff_directory>> previewIFD (previewCount);
9356
9357 std::vector<std::unique_ptr<dng_basic_tag_set>> previewBasic (previewCount);
9358
9359 for (uint32 j = 0; j < previewCount; j++)
9360 {
9361
9362 if (thumbnail != &previewList->Preview (j))
9363 {
9364
9365 previewIFD [j] . reset (new dng_tiff_directory);
9366
9367 previewBasic [j] . reset (previewList->Preview (j).AddTagSet (host,
9368 *previewIFD [j]));
9369
9370 subFileCount++;
9371
9372 }
9373
9374 }
9375
9376 // And a link to the subIFDs.
9377
9378 tag_big_uints tagSubFile (tcSubIFDs,
9379 subFileCount);
9380
9381 if (subFileCount)
9382 {
9383
9384 mainIFD.Add (&tagSubFile);
9385
9386 }
9387
9388 // Maximum target size of 32-bit DNG files that allows lots of slop for
9389 // future metadata edits.
9390
9391 const uint64 kMaxTarget32BitDNGSize = 0xFFFFFFFF - 256 * 1024 * 1024;
9392
9393 // Figure out if to use 64-bit version using a multiple pass algorithm.
9394
9395 bool isBigTIFF = false;
9396
9397 uint64 headerSize32 = 0;
9398
9399 uint64 maxNonHeaderSize = 0;
9400
9401 #if qForceWriteBigDNG || qStressTestBigDNG
9402 allowBigTIFF = true;
9403 #endif
9404
9405 for (uint32 pass = 1; pass <= 3; pass++)
9406 {
9407
9408 // Pass 1: Measure header size if 32-bit.
9409
9410 if (pass == 1)
9411 {
9412 isBigTIFF = false;
9413 }
9414
9415 // Pass 2: Make a guess and write non-header data.
9416
9417 else if (pass == 2)
9418 {
9419
9420 #if qForceWriteBigDNG
9421
9422 isBigTIFF = true;
9423
9424 #else
9425
9426 if (allowBigTIFF)
9427 {
9428 isBigTIFF = (headerSize32 + maxNonHeaderSize > kMaxTarget32BitDNGSize);
9429 }
9430
9431 #endif
9432
9433 }
9434
9435 // Pass 3: Use actual file length to decide.
9436
9437 else
9438 {
9439
9440 #if !qForceWriteBigDNG
9441
9442 if (stream.Length () <= kMaxTarget32BitDNGSize)
9443 {
9444 isBigTIFF = false;
9445 }
9446
9447 else if (stream.Length () > 0xFFFFFFFF)
9448 {
9449 DNG_REQUIRE (isBigTIFF, "Bad maxNonHeaderSize estimate");
9450 }
9451
9452 #endif
9453
9454 }
9455
9456 // Skip past the header and IFDs for now.
9457
9458 uint64 currentOffset = isBigTIFF ? 16 : 8;
9459
9460 #if qStressTestBigDNG
9461 currentOffset += kStressTestBytes;
9462 #endif
9463
9464 uint64 mainIFDOffset = currentOffset;
9465
9466 mainIFD.SetBigTIFF (isBigTIFF);
9467
9468 currentOffset += mainIFD.Size ();
9469
9470 exifSet.SetBigTIFF (isBigTIFF);
9471
9472 exifSet.Locate (currentOffset);
9473
9474 currentOffset += exifSet.Size ();
9475
9476 uint32 subFileIndex = 0;
9477
9478 if (thumbnail)
9479 {
9480
9481 rawIFD.SetBigTIFF (isBigTIFF);
9482
9483 tagSubFile.Set (subFileIndex++, currentOffset);
9484
9485 currentOffset += rawIFD.Size ();
9486
9487 }
9488
9489 if (hasTransparencyMask)
9490 {
9491
9492 maskIFD->SetBigTIFF (isBigTIFF);
9493
9494 tagSubFile.Set (subFileIndex++, currentOffset);
9495
9496 currentOffset += maskIFD->Size ();
9497
9498 }
9499
9500 if (hasDepthMap)
9501 {
9502
9503 depthIFD->SetBigTIFF (isBigTIFF);
9504
9505 tagSubFile.Set (subFileIndex++, currentOffset);
9506
9507 currentOffset += depthIFD->Size ();
9508
9509 }
9510
9511 if (hasEnhancedImage)
9512 {
9513
9514 enhancedIFD->SetBigTIFF (isBigTIFF);
9515
9516 tagSubFile.Set (subFileIndex++, currentOffset);
9517
9518 currentOffset += enhancedIFD->Size ();
9519
9520 }
9521
9522 if (hasGainMap)
9523 {
9524
9525 gainMapIFD.SetBigTIFF (isBigTIFF);
9526
9527 tagSubFile.Set (subFileIndex++, currentOffset);
9528
9529 currentOffset += gainMapIFD.Size ();
9530
9531 }
9532
9533 for (uint32 j = 0; j < semanticMaskCount; j++)
9534 {
9535
9536 semanticMaskIFD [j]->SetBigTIFF (isBigTIFF);
9537
9538 tagSubFile.Set (subFileIndex++, currentOffset);
9539
9540 currentOffset += semanticMaskIFD [j]->Size ();
9541
9542 }
9543
9544 for (uint32 j = 0; j < previewCount; j++)
9545 {
9546
9547 if (thumbnail != &previewList->Preview (j))
9548 {
9549
9550 previewIFD [j]->SetBigTIFF (isBigTIFF);
9551
9552 tagSubFile.Set (subFileIndex++, currentOffset);
9553
9554 currentOffset += previewIFD [j]->Size ();
9555
9556 }
9557
9558 }
9559
9560 // Write out the header in pass 3.
9561
9562 if (pass == 3)
9563 {
9564
9565 stream.SetWritePosition (0);
9566
9567 stream.Put_uint16 (stream.BigEndian () ? byteOrderMM : byteOrderII);
9568
9569 stream.Put_uint16 (isBigTIFF ? magicBigTIFF : magicTIFF);
9570
9571 if (isBigTIFF)
9572 {
9573 stream.Put_uint16 (8);
9574 stream.Put_uint16 (0);
9575 stream.Put_uint64 (mainIFDOffset);
9576 }
9577 else
9578 {
9579 stream.Put_uint32 ((uint32) mainIFDOffset);
9580 }
9581
9582 #if qStressTestBigDNG
9583 stream.PutZeros (kStressTestBytes);
9584 #endif
9585
9586 // Write the IFDs.
9587
9588 mainIFD.Put (stream);
9589
9590 exifSet.Put (stream);
9591
9592 if (thumbnail)
9593 {
9594
9595 rawIFD.Put (stream);
9596
9597 }
9598
9599 if (hasTransparencyMask)
9600 {
9601
9602 maskIFD->Put (stream);
9603
9604 }
9605
9606 if (hasDepthMap)
9607 {
9608
9609 depthIFD->Put (stream);
9610
9611 }
9612
9613 if (hasEnhancedImage)
9614 {
9615
9616 enhancedIFD->Put (stream);
9617
9618 }
9619
9620 if (hasGainMap)
9621 {
9622
9623 gainMapIFD.Put (stream);
9624
9625 }
9626
9627 for (uint32 j = 0; j < semanticMaskCount; j++)
9628 {
9629
9630 semanticMaskIFD [j]->Put (stream);
9631
9632 }
9633
9634 for (uint32 j = 0; j < previewCount; j++)
9635 {
9636
9637 if (thumbnail != &previewList->Preview (j))
9638 {
9639
9640 previewIFD [j]->Put (stream);
9641
9642 }
9643
9644 }
9645
9646 DNG_REQUIRE (currentOffset == stream.Position (),
9647 "Header size logic error");
9648
9649 break; // All done.
9650
9651 } // pass 3
9652
9653 if (pass == 1)
9654 {
9655
9656 // We figured out the 32-bit header size in pass 1.
9657
9658 headerSize32 = currentOffset;
9659
9660 }
9661
9662 else
9663 {
9664
9665 // Just zero out the header for now and skip to the non-header.
9666
9667 stream.PutZeros (currentOffset);
9668
9669 }
9670
9671 // Write the extra profiles.
9672
9673 if (extraProfileCount)
9674 {
9675
9676 for (uint32 j = 0; j < extraProfileCount; j++)
9677 {
9678
9679 uint32 index = extraProfileIndex [j];
9680
9681 const dng_camera_profile &profile (negative.ProfileByIndex (index));
9682
9683 tiff_dng_extended_color_profile extraWriter (profile, false);
9684
9685 uint64 estimatedSize = extraWriter.DataSize ();
9686
9687 if (pass == 1)
9688 {
9689
9690 maxNonHeaderSize += estimatedSize;
9691
9692 }
9693
9694 else
9695 {
9696
9697 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Extra profile data");
9698
9699 extraProfileTag.Set (j, stream.Position ());
9700
9701 extraWriter.Put (host, stream);
9702
9703 }
9704
9705 }
9706
9707 }
9708
9709 // Write the thumbnail data.
9710
9711 if (thumbnail)
9712 {
9713
9714 uint64 estimatedSize = thumbnail->MaxImageDataByteCount ();
9715
9716 if (pass == 1)
9717 {
9718
9719 maxNonHeaderSize += estimatedSize;
9720
9721 }
9722
9723 else
9724 {
9725
9726 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Thumbnail data");
9727
9728 thumbnail->WriteData (host,
9729 *this,
9730 *thmBasic,
9731 stream);
9732
9733 }
9734
9735 }
9736
9737 // Write the preview data.
9738
9739 for (uint32 j = 0; j < previewCount; j++)
9740 {
9741
9742 if (thumbnail != &previewList->Preview (j))
9743 {
9744
9745 uint64 estimatedSize = previewList->Preview (j).MaxImageDataByteCount ();
9746
9747 if (pass == 1)
9748 {
9749
9750 maxNonHeaderSize += estimatedSize;
9751
9752 }
9753
9754 else
9755 {
9756
9757 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Preview data");
9758
9759 previewList->Preview (j).WriteData (host,
9760 *this,
9761 *previewBasic [j],
9762 stream);
9763
9764 }
9765
9766 }
9767
9768 }
9769
9770 // Write the raw data.
9771
9772 if (rawLossyCompressedImage)
9773 {
9774
9775 const auto &img = *rawLossyCompressedImage;
9776
9777 if (pass == 1)
9778 {
9779
9780 maxNonHeaderSize += img.NonHeaderSize ();
9781
9782 }
9783
9784 else
9785 {
9786
9787 img.WriteData (stream, rawBasic);
9788
9789 }
9790
9791 }
9792
9793 else
9794 {
9795
9796 uint64 estimatedSize = info.MaxImageDataByteCount ();
9797
9798 if (pass == 1)
9799 {
9800
9801 maxNonHeaderSize += estimatedSize;
9802
9803 }
9804
9805 else
9806 {
9807
9808 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Raw image data");
9809
9810 #if qDNGValidate
9811 dng_timer timer ("Write raw image time");
9812 #endif
9813
9814 WriteImage (host,
9815 info,
9816 rawBasic,
9817 stream,
9818 rawImage,
9819 fakeChannels,
9820 nullptr);
9821
9822 }
9823
9824 }
9825
9826 // Write transparency mask image.
9827
9828 if (hasTransparencyMask)
9829 {
9830
9831 // Do we have a lossy compressed version?
9832
9833 if (rawLossyCompressedTransparencyMask)
9834 {
9835
9836 const auto &img = *rawLossyCompressedTransparencyMask;
9837
9838 if (pass == 1)
9839 {
9840
9841 maxNonHeaderSize += img.NonHeaderSize ();
9842
9843 }
9844
9845 else
9846 {
9847
9848 img.WriteData (stream, *maskBasic);
9849
9850 }
9851
9852 }
9853
9854 else
9855 {
9856
9857 uint64 estimatedSize = maskInfo->MaxImageDataByteCount ();
9858
9859 if (pass == 1)
9860 {
9861
9862 maxNonHeaderSize += estimatedSize;
9863
9864 }
9865
9866 else
9867 {
9868
9869 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Transparency mask data");
9870
9871 #if qDNGValidate
9872 dng_timer timer ("Write transparency mask time");
9873 #endif
9874
9875 WriteImage (host,
9876 *maskInfo,
9877 *maskBasic,
9878 stream,
9879 *negative.RawTransparencyMask ());
9880
9881 }
9882
9883 }
9884
9885 }
9886
9887 // Write depth map image.
9888
9889 if (hasDepthMap)
9890 {
9891
9892 // Do we have a lossy compressed version?
9893
9894 if (negative.RawLossyCompressedDepthMap ())
9895 {
9896
9897 const auto &img = *(negative.RawLossyCompressedDepthMap ());
9898
9899 if (pass == 1)
9900 {
9901
9902 maxNonHeaderSize += img.NonHeaderSize ();
9903
9904 }
9905
9906 else
9907 {
9908
9909 img.WriteData (stream, *depthBasic);
9910
9911 }
9912
9913 }
9914
9915 else
9916 {
9917
9918 uint64 estimatedSize = depthInfo->MaxImageDataByteCount ();
9919
9920 if (pass == 1)
9921 {
9922
9923 maxNonHeaderSize += estimatedSize;
9924
9925 }
9926
9927 else
9928 {
9929
9930 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Depth map data");
9931
9932 #if qDNGValidate
9933 dng_timer timer ("Write depth map time");
9934 #endif
9935
9936 WriteImage (host,
9937 *depthInfo,
9938 *depthBasic,
9939 stream,
9940 *negative.RawDepthMap ());
9941
9942 }
9943
9944 }
9945
9946 }
9947
9948 // Write enhanced image.
9949
9950 if (hasEnhancedImage)
9951 {
9952
9953 // Do we have a lossy compressed version?
9954
9955 if (negative.EnhancedLossyCompressedImage ())
9956 {
9957
9958 const auto &img = *(negative.EnhancedLossyCompressedImage ());
9959
9960 if (pass == 1)
9961 {
9962
9963 maxNonHeaderSize += img.NonHeaderSize ();
9964
9965 }
9966
9967 else
9968 {
9969
9970 img.WriteData (stream, *enhancedBasic);
9971
9972 }
9973
9974 }
9975
9976 else
9977 {
9978
9979 uint64 estimatedSize = enhancedInfo->MaxImageDataByteCount ();
9980
9981 if (pass == 1)
9982 {
9983
9984 maxNonHeaderSize += estimatedSize;
9985
9986 }
9987
9988 else
9989 {
9990
9991 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Enhanced image data");
9992
9993 #if qDNGValidate
9994 dng_timer timer ("Write enhanced image time");
9995 #endif
9996
9997 WriteImage (host,
9998 *enhancedInfo,
9999 *enhancedBasic,
10000 stream,
10001 *negative.Stage3Image ());
10002
10003 }
10004
10005 }
10006
10007 }
10008
10009 // Write gain map.
10010
10011 if (hasGainMap)
10012 {
10013
10014 // Do we have a lossy compressed version?
10015
10016 if (gainMapLossyCompressed)
10017 {
10018
10019 const auto &img = *gainMapLossyCompressed;
10020
10021 if (pass == 1)
10022 {
10023
10024 maxNonHeaderSize += img.NonHeaderSize ();
10025
10026 }
10027
10028 else
10029 {
10030
10031 img.WriteData (stream, *gainMapTagSet);
10032
10033 }
10034
10035 }
10036
10037 else
10038 {
10039
10040 uint64 estimatedSize = gainMapImageIFD->MaxImageDataByteCount ();
10041
10042 if (pass == 1)
10043 {
10044
10045 maxNonHeaderSize += estimatedSize;
10046
10047 }
10048
10049 else
10050 {
10051
10052 DNG_VERIFY_SIZE_ESTIMATE (stream,
10053 estimatedSize,
10054 "Gain map image data");
10055
10056 #if qDNGValidate
10057 dng_timer timer ("Write gain map image time");
10058 #endif
10059
10060 WriteImage (host,
10061 *gainMapImageIFD,
10062 *gainMapTagSet,
10063 stream,
10064 *gainMapImage);
10065
10066 }
10067
10068 }
10069
10070 }
10071
10072 // Write semantic mask images.
10073
10074 for (uint32 j = 0; j < semanticMaskCount; j++)
10075 {
10076
10077 const auto &semanticMask = negative.RawSemanticMask (j);
10078
10079 // Do we have a lossy compressed version?
10080
10081 if (semanticMask.fLossyCompressed.get ())
10082 {
10083
10084 const auto &img = *(semanticMask.fLossyCompressed);
10085
10086 if (pass == 1)
10087 {
10088
10089 maxNonHeaderSize += img.NonHeaderSize ();
10090
10091 }
10092
10093 else
10094 {
10095
10096 img.WriteData (stream, *semanticMaskBasic [j]);
10097
10098 }
10099
10100 }
10101
10102 else
10103 {
10104
10105 uint64 estimatedSize = semanticMaskInfo [j]->MaxImageDataByteCount ();
10106
10107 if (pass == 1)
10108 {
10109
10110 maxNonHeaderSize += estimatedSize;
10111
10112 }
10113
10114 else
10115 {
10116
10117 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Semantic mask data");
10118
10119 WriteImage (host,
10120 *semanticMaskInfo [j],
10121 *semanticMaskBasic [j],
10122 stream,
10123 *semanticMask.fMask);
10124
10125 }
10126
10127 }
10128
10129 }
10130
10131 // Write the big table data.
10132
10133 {
10134
10135 uint64 estimatedSize = bigTableTagSet.DataSize ();
10136
10137 if (pass == 1)
10138 {
10139
10140 maxNonHeaderSize += estimatedSize;
10141
10142 }
10143
10144 else
10145 {
10146
10147 DNG_VERIFY_SIZE_ESTIMATE (stream, estimatedSize, "Big table data");
10148
10149 bigTableTagSet.WriteData (stream);
10150
10151 }
10152
10153 }
10154
10155 // Trim the file to this length.
10156
10157 if (pass == 2)
10158 {
10159
10160 stream.SetLength (stream.Position ());
10161
10162 }
10163
10164 // 32-bit DNG has a 4G size limit.
10165
10166 if (pass == 2 && !isBigTIFF)
10167 {
10168
10169 if (stream.Length () > 0xFFFFFFFF)
10170 {
10171
10172 if (allowBigTIFF)
10173 {
10174
10175 // We screwed up our maxNonHeaderSize estimate. Set to
10176 // the exact value and redo pass 2.
10177
10178 DNG_REPORT ("Really bad maxNonHeaderSize estimate");
10179
10180 maxNonHeaderSize = stream.Length () - headerSize32;
10181
10182 stream.SetWritePosition (0);
10183
10184 stream.SetLength (0);
10185
10186 pass--; // Redo pass 2
10187
10188 }
10189
10190 else
10191 {
10192
10193 ThrowImageTooBigDNG ();
10194
10195 }
10196
10197 }
10198
10199 }
10200
10201 }
10202
10203 stream.Flush ();
10204
10205 }
10206
10207 /*****************************************************************************/