Debian Codegraph @

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

raw
1 /*****************************************************************************/
2 // Copyright 2006-2023 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_utils.h"
10
11 #include "dng_area_task.h"
12 #include "dng_assertions.h"
13 #include "dng_bottlenecks.h"
14 #include "dng_flags.h"
15 #include "dng_globals.h"
16 #include "dng_host.h"
17 #include "dng_image.h"
18 #include "dng_image_writer.h"
19 #include "dng_memory_stream.h"
20 #include "dng_mutex.h"
21 #include "dng_point.h"
22 #include "dng_rect.h"
23 #include "dng_simd_type.h"
24 #include "dng_tag_codes.h"
25 #include "dng_tag_values.h"
26 #include "dng_tile_iterator.h"
27
28 #if qMacOS
29 #include <CoreServices/CoreServices.h>
30 #endif
31
32 #if qiPhone || qMacOS
33 // these provide timers
34 #include <mach/mach.h>
35 #include <mach/mach_time.h>
36 #endif
37
38 #if qiPhone || qLinux
39 #include <signal.h> // for raise
40 #endif
41
42 #if qWinOS
43 #include <windows.h>
44 #else
45 #include <sys/time.h>
46 #include <stdarg.h> // for va_start/va_end
47 #endif
48
49 #if defined(__EMSCRIPTEN__)
50 #include "emscripten.h"
51 #endif
52
53 #include <atomic>
54
55 /*****************************************************************************/
56
57 #if qDNGDebug
58
59 /*****************************************************************************/
60
61 #if qMacOS
62 #if qARM
63 #define DNG_DEBUG_BREAK do { } while (0)
64 #else
65 #define DNG_DEBUG_BREAK __asm__ volatile ("int3")
66 #endif
67 #elif qiPhone
68 #if qiPhoneSimulator
69 // simulator is either on Intel or arm64
70 #if qARM
71 #define DNG_DEBUG_BREAK do { } while (0)
72 #else
73 #define DNG_DEBUG_BREAK __asm__ volatile ("int3")
74 #endif
75 #else
76 // You'll be one level deeper in __kill. Works on Linux, Android too.
77 #define DNG_DEBUG_BREAK raise(SIGTRAP)
78 #endif
79 #elif qWinOS
80 // DebugBreak has to be emulated on WinRT
81 #define DNG_DEBUG_BREAK DebugBreak()
82 #elif qAndroid
83 #define DNG_DEBUG_BREAK raise(SIGTRAP)
84 #elif qLinux
85 #define DNG_DEBUG_BREAK raise(SIGTRAP)
86 #else
87 #define DNG_DEBUG_BREAK
88 #endif
89
90 /*****************************************************************************/
91
92 #endif // qDNGDebug
93
94 /*****************************************************************************/
95
96 #if qWinOS
97
98 void dng_outputdebugstring (const char *s,
99 const char *nl)
100 {
101
102 static const bool sDebuggerPresent (IsDebuggerPresent () != 0);
103
104 if (sDebuggerPresent)
105 {
106 OutputDebugStringA (s);
107 if (nl && nl [0])
108 {
109 OutputDebugStringA (nl);
110 }
111 }
112
113 }
114
115 #endif
116
117 /*****************************************************************************/
118
119 #if defined(__EMSCRIPTEN__)
120
121 void dng_emscripten_log (int emLogType,
122 const char *s)
123 {
124
125 #if qDNGDebug
126 emLogType |= EM_LOG_CONSOLE;
127 #endif
128
129 emscripten_log (emLogType,"%s", s);
130
131 }
132
133 #endif
134
135 /*****************************************************************************/
136
137 void dng_show_message (const char *s)
138 {
139 // only append a newline if there isn't already one
140 const char* nl = "\n";
141 if (s[0] && (s[strlen(s)-1] == '\n'))
142 nl = "";
143
144 #if qDNGPrintMessages
145
146 // display the message
147 if (gPrintAsserts)
148 fprintf (stderr, "%s%s", s, nl);
149
150 #elif qiPhone || qAndroid || qLinux || qWeb
151
152 if (gPrintAsserts)
153 fprintf (stderr, "%s%s", s, nl);
154
155 #if qDNGDebug
156
157 // iOS doesn't print a message to the console like DebugStr and MessageBox do, so we have to do both
158 // You'll have to advance the program counter manually past this statement
159 if (gBreakOnAsserts)
160 DNG_DEBUG_BREAK;
161
162 #endif // qDNGDebug
163
164 #elif qMacOS
165
166 if (gBreakOnAsserts)
167 {
168 // truncate the to 255 chars
169 char ss [256];
170
171 uint32 len = (uint32) strlen (s);
172 if (len > 255)
173 len = 255;
174 strncpy (&(ss [1]), s, len );
175 ss [0] = (unsigned char) len;
176
177 DebugStr ((unsigned char *) ss);
178 }
179 else if (gPrintAsserts)
180 {
181 // For macOS have non-breaking assert emit to stdout
182 // rather than stderr so that message will appear
183 // in the Xcode console window.
184 //fprintf(stderr, "%s%s", s, nl);
185 fprintf (stdout, "%s%s", s, nl);
186 }
187
188 #elif qWinOS
189
190 // display a dialog
191 // This is not thread safe. Multiple message boxes can be launched.
192 // Should also be launched in its own thread so main msg queue isn't thrown off.
193 if (gBreakOnAsserts)
194 {
195 MessageBoxA (NULL, (LPSTR) s, NULL, MB_OK);
196 }
197 else if (gPrintAsserts)
198 {
199 fprintf (stderr, "%s%s", s, nl);
200
201 // Emit assert message to MSVS Output window when debugging.
202 dng_outputdebugstring (s, nl);
203 }
204
205 #endif
206
207 }
208
209 /*****************************************************************************/
210
211 void dng_show_message_f (const char *fmt, ... )
212 {
213
214 char buffer [2048];
215
216 va_list ap;
217 va_start (ap, fmt);
218
219 vsnprintf (buffer, sizeof (buffer), fmt, ap);
220
221 va_end (ap);
222
223 dng_show_message (buffer);
224
225 }
226
227 /*****************************************************************************/
228
229 uint32 ComputeBufferSize (uint32 pixelType,
230 const dng_point &tileSize,
231 uint32 numPlanes,
232 PaddingType paddingType)
233 {
234
235 // Convert tile size to uint32.
236
237 if (tileSize.h < 0 || tileSize.v < 0)
238 {
239 ThrowMemoryFull ("Negative tile size");
240 }
241
242 const uint32 tileSizeH = static_cast<uint32> (tileSize.h);
243 const uint32 tileSizeV = static_cast<uint32> (tileSize.v);
244
245 const uint32 pixelSize = TagTypeSize (pixelType);
246
247 // Add padding to width if necessary.
248
249 uint32 paddedWidth = tileSizeH;
250
251 if (paddingType == padSIMDBytes)
252 {
253
254 if (!RoundUpForPixelSize (paddedWidth,
255 pixelSize,
256 &paddedWidth))
257 {
258 ThrowOverflow ("Arithmetic overflow computing buffer size");
259 }
260
261 }
262
263 // Compute buffer size.
264
265 uint32 bufferSize;
266
267 if (!SafeUint32Mult (paddedWidth, tileSizeV, &bufferSize) ||
268 !SafeUint32Mult (bufferSize, pixelSize, &bufferSize) ||
269 !SafeUint32Mult (bufferSize, numPlanes, &bufferSize))
270 {
271 ThrowOverflow ("Arithmetic overflow computing buffer size");
272 }
273
274 return bufferSize;
275
276 }
277
278 /*****************************************************************************/
279
280 real64 TickTimeInSeconds ()
281 {
282
283 #if qWinOS
284
285 // One might think it prudent to cache the frequency here, however
286 // low-power CPU modes can, and do, change the value returned.
287 // Thus the frequencey needs to be retrieved each time.
288
289 // Note that the frequency changing can cause the return
290 // result to jump backwards, which is why the TickCountInSeconds
291 // (below) also exists.
292
293 // Just plug in laptop when doing timings to minimize this.
294 // QPC/QPH is a slow call compared to rtdsc.
295 // but QPC/QPF is not tied to speed step, it's the northbridge timer.
296 // caching the invFrequency also avoids a costly divide
297
298 static real64 freqMultiplier = 0.0;
299
300 if (freqMultiplier == 0.0)
301 {
302
303 LARGE_INTEGER freq;
304
305 QueryPerformanceFrequency (&freq);
306
307 freqMultiplier = 1.0 / (real64) freq.QuadPart;
308
309 }
310
311 LARGE_INTEGER cycles;
312
313 QueryPerformanceCounter (&cycles);
314
315 return (real64) cycles.QuadPart * freqMultiplier;
316
317 #elif qiPhone || qMacOS
318
319 // cache frequency of high-perf timer
320 static real64 freqMultiplier = 0.0;
321 if (freqMultiplier == 0.0)
322 {
323
324 mach_timebase_info_data_t freq;
325 mach_timebase_info(&freq);
326
327 // converts from nanos to micros
328 // numer = 125, denom = 3 * 1000
329 freqMultiplier = ((real64)freq.numer / (real64)freq.denom) * 1.0e-9;
330
331 }
332
333 return mach_absolute_time() * freqMultiplier;
334
335 #elif qAndroid || qLinux || qWeb
336
337 //this is a fast timer to nanos
338 struct timespec now;
339 clock_gettime(CLOCK_MONOTONIC, &now);
340 return now.tv_sec + (real64)now.tv_nsec * 1.0e-9;
341
342 #else
343
344 // Perhaps a better call exists. (e.g. avoid adjtime effects)
345
346 struct timeval tv;
347
348 gettimeofday (&tv, NULL);
349
350 return tv.tv_sec + (real64)tv.tv_usec * 1.0e-6;
351
352 #endif
353
354 }
355
356 /*****************************************************************************/
357
358 real64 TickCountInSeconds ()
359 {
360
361 return TickTimeInSeconds ();
362
363 }
364
365 /*****************************************************************************/
366
367 static std::atomic_int sTimerLevel (0);
368
369 /*****************************************************************************/
370
371 void DNGIncrementTimerLevel ()
372 {
373
374 // This isn't thread coherent, multiple threads can create/destroy cr_timer
375 // causing the tabbing to be invalid. Imagecore disables this.
376
377 if (!gImagecore)
378 {
379
380 sTimerLevel++;
381
382 }
383
384 }
385
386 /*****************************************************************************/
387
388 int32 DNGDecrementTimerLevel ()
389 {
390
391 if (gImagecore)
392 {
393
394 return 0;
395
396 }
397
398 else
399 {
400
401 return (int32) (--sTimerLevel);
402
403 }
404
405 }
406
407 /*****************************************************************************/
408
409 dng_timer::dng_timer (const char *message)
410
411 : fMessage (message )
412 , fStartTime (TickTimeInSeconds ())
413
414 {
415
416 DNGIncrementTimerLevel ();
417
418 }
419
420 /*****************************************************************************/
421
422 dng_timer::~dng_timer ()
423 {
424
425 uint32 level = Pin_int32 (0, DNGDecrementTimerLevel (), 10);
426
427 if (!gDNGShowTimers)
428 return;
429
430 real64 totalTime = TickTimeInSeconds () - fStartTime;
431
432 #if defined(qCRLogging) && qCRLogging && defined(cr_logi)
433
434 if (gImagecore)
435 {
436 // Imagecore force includes cr_log and overrides DNG to go to its logging under a mutex.
437 // don't use indenting or fprintf to stderr, want these buffered
438 cr_logi("timer", "%s: %0.3f sec\n", fMessage, totalTime);
439 return;
440 }
441
442 #endif
443
444 fprintf (stderr, "%*s%s: %0.3f sec\n", level*2, "", fMessage, totalTime);
445
446 }
447
448 /*****************************************************************************/
449
450 real64 MaxSquaredDistancePointToRect (const dng_point_real64 &point,
451 const dng_rect_real64 &rect)
452 {
453
454 real64 distSqr = DistanceSquared (point,
455 rect.TL ());
456
457 distSqr = Max_real64 (distSqr,
458 DistanceSquared (point,
459 rect.BL ()));
460
461 distSqr = Max_real64 (distSqr,
462 DistanceSquared (point,
463 rect.BR ()));
464
465 distSqr = Max_real64 (distSqr,
466 DistanceSquared (point,
467 rect.TR ()));
468
469 return distSqr;
470
471 }
472
473 /*****************************************************************************/
474
475 real64 MaxDistancePointToRect (const dng_point_real64 &point,
476 const dng_rect_real64 &rect)
477 {
478
479 return sqrt (MaxSquaredDistancePointToRect (point,
480 rect));
481
482 }
483
484 /*****************************************************************************/
485
486 dng_dither::dng_dither ()
487
488 : fNoiseBuffer ()
489
490 {
491
492 const uint32 kSeed = 1;
493
494 fNoiseBuffer.Allocate (kRNGSize2D * sizeof (uint16));
495
496 uint16 *buffer = fNoiseBuffer.Buffer_uint16 ();
497
498 uint32 seed = kSeed;
499
500 for (uint32 i = 0; i < kRNGSize2D; i++)
501 {
502
503 // The correct math for 16 to 8-bit dither would be:
504 //
505 // y = (x * 255 + r) / 65535; (0 <= r <= 65534)
506 //
507 // The bottlnecks are using a faster approximation of
508 // this math (using a power of two for the division):
509 //
510 // y = (x * 255 + r) / 65536; (255 <= r <= 65535)
511 //
512 // To insure that all exact 8 bit values in 16 bit space
513 // round trip exactly to the same 8-bit, we need to limit
514 // r values to the range 255 to 65535.
515 //
516 // This results in the dither effect being slightly
517 // imperfect, but correct round-tripping of 8-bit values
518 // is far more important.
519
520 uint16 value;
521
522 do
523 {
524
525 seed = DNG_Random (seed);
526
527 value = (uint16) seed;
528
529 }
530 while (value < 255);
531
532 buffer [i] = value;
533
534 }
535
536 }
537
538 /******************************************************************************/
539
540 const dng_dither & dng_dither::Get ()
541 {
542
543 static dng_dither dither;
544
545 return dither;
546
547 }
548
549 /*****************************************************************************/
550
551 void HistogramArea (dng_host & /* host */,
552 const dng_image &image,
553 const dng_rect &area,
554 uint32 *hist,
555 uint32 maxValue,
556 uint32 plane)
557 {
558
559 DNG_ASSERT (image.PixelType () == ttShort, "Unsupported pixel type");
560
561 DoZeroBytes (hist, (maxValue + 1) * (uint32) sizeof (uint32));
562
563 dng_rect tile;
564
565 dng_tile_iterator iter (image, area);
566
567 while (iter.GetOneTile (tile))
568 {
569
570 dng_const_tile_buffer buffer (image, tile);
571
572 const void *sPtr = buffer.ConstPixel (tile.t,
573 tile.l,
574 plane);
575
576 uint32 count0 = 1;
577 uint32 count1 = tile.H ();
578 uint32 count2 = tile.W ();
579
580 int32 step0 = 0;
581 int32 step1 = buffer.fRowStep;
582 int32 step2 = buffer.fColStep;
583
584 OptimizeOrder (sPtr,
585 buffer.fPixelSize,
586 count0,
587 count1,
588 count2,
589 step0,
590 step1,
591 step2);
592
593 DNG_ASSERT (count0 == 1, "OptimizeOrder logic error");
594
595 const uint16 *s1 = (const uint16 *) sPtr;
596
597 for (uint32 row = 0; row < count1; row++)
598 {
599
600 if (maxValue == 0x0FFFF && step2 == 1)
601 {
602
603 for (uint32 col = 0; col < count2; col++)
604 {
605
606 uint32 x = s1 [col];
607
608 hist [x] ++;
609
610 }
611
612 }
613
614 else
615 {
616
617 const uint16 *s2 = s1;
618
619 for (uint32 col = 0; col < count2; col++)
620 {
621
622 uint32 x = s2 [0];
623
624 if (x <= maxValue)
625 {
626
627 hist [x] ++;
628
629 }
630
631 s2 += step2;
632
633 }
634
635 }
636
637 s1 += step1;
638
639 }
640
641 }
642
643 }
644
645 /*****************************************************************************/
646
647 template <SIMDType simd>
648 class dng_limit_float_depth_task: public dng_area_task
649 {
650
651 private:
652
653 const dng_image &fSrcImage;
654
655 dng_image &fDstImage;
656
657 uint32 fBitDepth;
658
659 real32 fScale;
660
661 public:
662
663 dng_limit_float_depth_task (const dng_image &srcImage,
664 dng_image &dstImage,
665 uint32 bitDepth,
666 real32 scale);
667
668 virtual dng_rect RepeatingTile1 () const
669 {
670 return fSrcImage.RepeatingTile ();
671 }
672
673 virtual dng_rect RepeatingTile2 () const
674 {
675 return fDstImage.RepeatingTile ();
676 }
677
678 virtual void Process (uint32 threadIndex,
679 const dng_rect &tile,
680 dng_abort_sniffer *sniffer);
681
682 };
683
684 /*****************************************************************************/
685
686 template <SIMDType simd>
687 dng_limit_float_depth_task<simd>::dng_limit_float_depth_task
688 (const dng_image &srcImage,
689 dng_image &dstImage,
690 uint32 bitDepth,
691 real32 scale)
692
693 : dng_area_task ("dng_limit_float_depth_task")
694
695 , fSrcImage (srcImage)
696 , fDstImage (dstImage)
697 , fBitDepth (bitDepth)
698 , fScale (scale)
699
700 {
701
702 }
703
704 /*****************************************************************************/
705
706 template <SIMDType simd>
707
708 #ifdef __INTEL_LLVM_COMPILER
709 __attribute__((SET_CPU_FEATURE(simd)))
710 #endif // __INTEL_LLVM_COMPILER
711
712 void dng_limit_float_depth_task<simd>::Process (uint32 /* threadIndex */,
713 const dng_rect &tile,
714 dng_abort_sniffer * /* sniffer */)
715 {
716
717 INTEL_COMPILER_NEEDED_NOTE
718
719
720 #ifdef __INTEL_COMPILER
721 SET_CPU_FEATURE(simd);
722 #endif // __INTEL_COMPILER
723
724
725 dng_const_tile_buffer srcBuffer (fSrcImage, tile);
726 dng_dirty_tile_buffer dstBuffer (fDstImage, tile);
727
728 uint32 count0 = tile.H ();
729 uint32 count1 = tile.W ();
730 uint32 count2 = fDstImage.Planes ();
731
732 int32 sStep0 = srcBuffer.fRowStep;
733 int32 sStep1 = srcBuffer.fColStep;
734 int32 sStep2 = srcBuffer.fPlaneStep;
735
736 int32 dStep0 = dstBuffer.fRowStep;
737 int32 dStep1 = dstBuffer.fColStep;
738 int32 dStep2 = dstBuffer.fPlaneStep;
739
740 const void *sPtr = srcBuffer.ConstPixel (tile.t,
741 tile.l,
742 0);
743
744 void *dPtr = dstBuffer.DirtyPixel (tile.t,
745 tile.l,
746 0);
747
748 OptimizeOrder (sPtr,
749 dPtr,
750 srcBuffer.fPixelSize,
751 dstBuffer.fPixelSize,
752 count0,
753 count1,
754 count2,
755 sStep0,
756 sStep1,
757 sStep2,
758 dStep0,
759 dStep1,
760 dStep2);
761
762 const real32 *sPtr0 = (const real32 *) sPtr;
763 real32 *dPtr0 = ( real32 *) dPtr;
764
765 real32 scale = fScale;
766
767 bool limit16 = (fBitDepth == 16);
768 bool limit24 = (fBitDepth == 24);
769
770 for (uint32 index0 = 0; index0 < count0; index0++)
771 {
772
773 const real32 *sPtr1 = sPtr0;
774 real32 *dPtr1 = dPtr0;
775
776 for (uint32 index1 = 0; index1 < count1; index1++)
777 {
778
779 // If the scale is a NOP, and the data is packed solid, we can just do memory
780 // copy.
781
782 if (scale == 1.0f && sStep2 == 1 && dStep2 == 1)
783 {
784
785 if (dPtr1 != sPtr1) // srcImage != dstImage
786 {
787
788 memcpy (dPtr1, sPtr1, count2 * (uint32) sizeof (real32));
789
790 }
791
792 }
793
794 else
795 {
796
797 const real32 *sPtr2 = sPtr1;
798 real32 *dPtr2 = dPtr1;
799 INTEL_PRAGMA_SIMD_ASSERT_VECLEN_FLOAT(simd)
800 for (uint32 index2 = 0; index2 < count2; index2++)
801 {
802
803 real32 x = sPtr2 [0];
804
805 x *= scale;
806
807 dPtr2 [0] = x;
808
809 sPtr2 += sStep2;
810 dPtr2 += dStep2;
811
812 }
813
814 }
815
816 // The data is now in the destination buffer.
817
818 if (limit16)
819 {
820
821 //start by using intrinsic __m256__mm256_cvtph_ps_(__m128i_a)
822 //once the intrinsic is written, merge this branch with previous one
823
824 uint32 *dPtr2 = (uint32 *) dPtr1;
825
826 INTEL_PRAGMA_SIMD_ASSERT_VECLEN_INT32(simd)
827
828 for (uint32 index2 = 0; index2 < count2; index2++)
829 {
830
831 uint32 x = dPtr2 [0];
832
833 uint16 y = DNG_FloatToHalf (x);
834
835 x = DNG_HalfToFloat (y);
836
837 dPtr2 [0] = x;
838
839 dPtr2 += dStep2;
840
841 }
842
843 }
844
845 else if (limit24)
846 {
847
848 uint32 *dPtr2 = (uint32 *) dPtr1;
849
850 for (uint32 index2 = 0; index2 < count2; index2++)
851 {
852
853 uint32 x = dPtr2 [0];
854
855 uint8 temp [3];
856
857 DNG_FloatToFP24 (x, temp);
858
859 x = DNG_FP24ToFloat (temp);
860
861 dPtr2 [0] = x;
862
863 dPtr2 += dStep2;
864
865 }
866
867 }
868
869 sPtr1 += sStep1;
870 dPtr1 += dStep1;
871
872 }
873
874 sPtr0 += sStep0;
875 dPtr0 += dStep0;
876
877 }
878
879 }
880
881 /******************************************************************************/
882
883 template <SIMDType simd>
884 void LimitFloatBitDepth (dng_host &host,
885 const dng_image &srcImage,
886 dng_image &dstImage,
887 uint32 bitDepth,
888 real32 scale)
889 {
890
891 DNG_ASSERT (srcImage.PixelType () == ttFloat, "Floating point image expected");
892 DNG_ASSERT (dstImage.PixelType () == ttFloat, "Floating point image expected");
893
894 dng_limit_float_depth_task<simd> task (srcImage,
895 dstImage,
896 bitDepth,
897 scale);
898
899 host.PerformAreaTask (task, dstImage.Bounds ());
900
901 }
902
903 /*****************************************************************************/
904
905 template
906 void LimitFloatBitDepth<Scalar> (dng_host &host,
907 const dng_image &srcImage,
908 dng_image &dstImage,
909 uint32 bitDepth,
910 real32 scale);
911
912 /*****************************************************************************/
913
914 #if qDNGIntelCompiler
915
916 template
917 void LimitFloatBitDepth<AVX2> (dng_host &host,
918 const dng_image &srcImage,
919 dng_image &dstImage,
920 uint32 bitDepth,
921 real32 scale);
922
923 #endif // qDNGIntelCompiler
924
925 /*****************************************************************************/
926
927 void LimitFloatBitDepth (dng_host &host,
928 const dng_image &srcImage,
929 dng_image &dstImage,
930 uint32 bitDepth,
931 real32 scale)
932 {
933
934 // Kludge: Turning this off for now because the AVX2 path produces
935 // slightly different results from the Scalar routine causing a mis-match
936 // in raw digest values when building HDR merge result negatives which
937 // causes the client to display a "file appears to be damaged" warning.
938 // -bury 11/13/2017
939
940 #if (qDNGIntelCompiler && qDNGExperimental && 0)
941
942 if (gDNGMaxSIMD >= AVX2)
943 {
944
945 LimitFloatBitDepth<AVX2> (host,
946 srcImage,
947 dstImage,
948 bitDepth,
949 scale);
950
951 }
952
953 else
954
955 #endif // qDNGIntelCompiler && qDNGExperimental
956
957 {
958
959 LimitFloatBitDepth<Scalar> (host,
960 srcImage,
961 dstImage,
962 bitDepth,
963 scale);
964
965 }
966
967 }
968
969 /*****************************************************************************/
970
971 uint32 MinBackwardVersionForCompression (uint32 compression)
972 {
973
974 if (compression == ccLossyJPEG)
975 return dngVersion_1_4_0_0;
976
977 if (compression == ccJXL)
978 return dngVersion_1_7_0_0;
979
980 return dngVersion_1_1_0_0;
981
982 }
983
984 /*****************************************************************************/
985
986 tiff_tag * dng_image_sequence_info::MakeTag (dng_memory_allocator &allocator) const
987 {
988
989 dng_memory_stream stream (allocator);
990
991 TempBigEndian tempEndian (stream);
992
993 // Write Sequence ID.
994
995 if (fSequenceID.NotEmpty ())
996 stream.Put (fSequenceID.Get (),
997 fSequenceID.Length ());
998
999 stream.PutZeros (1);
1000
1001 // Write Sequence Type.
1002
1003 if (fSequenceType.NotEmpty ())
1004 stream.Put (fSequenceType.Get (),
1005 fSequenceType.Length ());
1006
1007 stream.PutZeros (1);
1008
1009 // Write frame info.
1010
1011 if (fFrameInfo.NotEmpty ())
1012 stream.Put (fFrameInfo.Get (),
1013 fFrameInfo.Length ());
1014
1015 stream.PutZeros (1);
1016
1017 // Write index, count, and final.
1018
1019 stream.Put_uint32 (fIndex);
1020 stream.Put_uint32 (fCount);
1021 stream.Put_uint8 (fIsFinal);
1022
1023 stream.SetReadPosition (0);
1024
1025 const_dng_memory_block_sptr block (stream.AsMemoryBlock (allocator));
1026
1027 AutoPtr<tag_owned_data_ptr> tag
1028 (new tag_owned_data_ptr (tcImageSequenceInfo,
1029 ttUndefined,
1030 block->LogicalSize (),
1031 block));
1032
1033 return tag.Release ();
1034
1035 }
1036
1037 /*****************************************************************************/
1038 /*****************************************************************************/
1039 /*****************************************************************************/
1040
1041 bool dng_image_stats::IsValidForPlaneCount (uint32 planeCount) const
1042 {
1043
1044 DNG_REQUIRE (planeCount > 0, "Invalid plane count");
1045
1046 if (fWeightedAverage.size () >= 2)
1047 return false;
1048
1049 if (fWeights.size () != 0 &&
1050 fWeights.size () != size_t (planeCount))
1051 return false;
1052
1053 if (fColorAverage.size () != 0 &&
1054 fColorAverage.size () != size_t (planeCount))
1055 return false;
1056
1057 // Check weighted samples.
1058
1059 if (!fWeightedSamples.empty ())
1060 {
1061
1062 // Check too many samples.
1063
1064 if (fWeightedSamples.size () > kMaxSamples)
1065 return false;
1066
1067 // Check non-increasing order.
1068
1069 real32 fPrev = fWeightedSamples.front ().fFrac;
1070
1071 for (size_t i = 1; i < fWeightedSamples.size (); i++)
1072 {
1073
1074 real32 fCurrent = fWeightedSamples [i].fFrac;
1075
1076 if (fCurrent <= fPrev)
1077 return false;
1078
1079 fPrev = fCurrent;
1080
1081 }
1082
1083 }
1084
1085 // Check color samples.
1086
1087 if (!fColorSamples.empty ())
1088 {
1089
1090 // Check too many samples.
1091
1092 if (fColorSamples.size () > kMaxSamples)
1093 return false;
1094
1095 // Check non-increasing order and invalid plane count.
1096
1097 real32 fPrev = fColorSamples.front ().fFrac;
1098
1099 for (size_t i = 1; i < fColorSamples.size (); i++)
1100 {
1101
1102 const auto &sample = fColorSamples [i];
1103
1104 if (sample.fFrac <= fPrev)
1105 return false;
1106
1107 fPrev = sample.fFrac;
1108
1109 // Also check plane count.
1110
1111 if (sample.fValues.size () != size_t (planeCount))
1112 return false;
1113
1114 }
1115
1116 }
1117
1118 // Looks ok.
1119
1120 return true;
1121
1122 }
1123
1124 /*****************************************************************************/
1125
1126 uint32 dng_image_stats::TagCount () const
1127 {
1128
1129 uint32 count = 0;
1130
1131 count += (!fWeightedAverage.empty () ? 1 : 0);
1132 count += (!fWeightedSamples.empty () ? 1 : 0);
1133 count += (!fWeights .empty () ? 1 : 0);
1134 count += (!fColorAverage .empty () ? 1 : 0);
1135 count += (!fColorSamples .empty () ? 1 : 0);
1136
1137 return count;
1138
1139 }
1140
1141 /*****************************************************************************/
1142
1143 static void Put (dng_stream &stream,
1144 uint32 tagCode,
1145 const std::vector<real32> &values)
1146 {
1147
1148 if (!values.empty ())
1149 {
1150
1151 // Sanity check on values size.
1152
1153 DNG_REQUIRE (values.size () <= 16,
1154 "values vector too large");
1155
1156 // Child tag code.
1157
1158 stream.Put_uint32 (tagCode);
1159
1160 // Byte length of child tag data.
1161
1162 stream.Put_uint32 (uint32 (4 * values.size ()));
1163
1164 // Child tag data.
1165
1166 for (const auto x : values)
1167 stream.Put_real32 (x);
1168
1169 }
1170
1171 }
1172
1173 /*****************************************************************************/
1174
1175 static void Put (dng_stream &stream,
1176 uint32 tagCode,
1177 const std::vector<dng_image_stats::weighted_sample> &samples)
1178 {
1179
1180 if (!samples.empty ())
1181 {
1182
1183 // Sanity check on samples size.
1184
1185 DNG_REQUIRE (samples.size () <= dng_image_stats::kMaxSamples,
1186 "samples vector too large");
1187
1188 // Child tag code.
1189
1190 stream.Put_uint32 (tagCode);
1191
1192 // Byte length of child tag data.
1193
1194 stream.Put_uint32 (uint32 (4 + 8 * samples.size ()));
1195
1196 // Child tag data.
1197
1198 // Write number of samples.
1199
1200 stream.Put_uint32 (uint32 (samples.size ()));
1201
1202 // Write data for each sample.
1203
1204 for (const auto &sample : samples)
1205 {
1206 stream.Put_real32 (sample.fFrac);
1207 stream.Put_real32 (sample.fValue);
1208 }
1209
1210 }
1211
1212 }
1213
1214 /*****************************************************************************/
1215
1216 static void Put (dng_stream &stream,
1217 uint32 tagCode,
1218 const std::vector<dng_image_stats::color_sample> &samples)
1219 {
1220
1221 if (!samples.empty ())
1222 {
1223
1224 // Sanity check on samples size.
1225
1226 DNG_REQUIRE (samples.size () <= dng_image_stats::kMaxSamples,
1227 "samples vector too large");
1228
1229 // Child tag code.
1230
1231 stream.Put_uint32 (tagCode);
1232
1233 // Byte length of child tag data.
1234
1235 uint32 bytes = 4;
1236
1237 for (const auto &sample : samples)
1238 bytes += (4 + 4 * uint32 (sample.fValues.size ()));
1239
1240 stream.Put_uint32 (bytes);
1241
1242 // Child tag data.
1243
1244 // Write number of samples.
1245
1246 stream.Put_uint32 (uint32 (samples.size ()));
1247
1248 // Write data for each sample.
1249
1250 for (const auto &sample : samples)
1251 {
1252
1253 stream.Put_real32 (sample.fFrac);
1254
1255 for (const auto &x : sample.fValues)
1256 stream.Put_real32 (x);
1257
1258 }
1259
1260 }
1261
1262 }
1263
1264 /*****************************************************************************/
1265
1266 tiff_tag * dng_image_stats::MakeTag (dng_memory_allocator &allocator) const
1267 {
1268
1269 dng_memory_stream stream (allocator);
1270
1271 // Tag data is big-endian byte order.
1272
1273 TempBigEndian tempEndian (stream);
1274
1275 // Write the number of tags.
1276
1277 uint32 count = TagCount ();
1278
1279 stream.Put_uint32 (count);
1280
1281 // Write child tag table.
1282
1283 Put (stream, kTag_WeightedAverage , fWeightedAverage);
1284 Put (stream, kTag_WeightedSamples , fWeightedSamples);
1285 Put (stream, kTag_Weights , fWeights);
1286 Put (stream, kTag_ColorAverage , fColorAverage);
1287 Put (stream, kTag_ColorSamples , fColorSamples);
1288
1289 // Make a tag from the data.
1290
1291 stream.SetReadPosition (0);
1292
1293 const_dng_memory_block_sptr block (stream.AsMemoryBlock (allocator));
1294
1295 AutoPtr<tag_owned_data_ptr> tag
1296 (new tag_owned_data_ptr (tcImageStats,
1297 ttUndefined,
1298 block->LogicalSize (),
1299 block));
1300
1301 return tag.Release ();
1302
1303 }
1304
1305 /*****************************************************************************/
1306
1307 bool dng_image_stats::operator== (const dng_image_stats &src) const
1308 {
1309
1310 return (fWeightedAverage == src.fWeightedAverage &&
1311 fWeightedSamples == src.fWeightedSamples &&
1312 fWeights == src.fWeights &&
1313 fColorAverage == src.fColorAverage &&
1314 fColorSamples == src.fColorSamples);
1315
1316 }
1317
1318 /*****************************************************************************/
1319
1320 void dng_image_stats::Parse (dng_stream &stream)
1321 {
1322
1323 // Tag data is big-endian byte order.
1324
1325 TempBigEndian tempEndian (stream);
1326
1327 // Read the number of tags.
1328
1329 uint32 count = stream.Get_uint32 ();
1330
1331 // There are only 5 possible tags, and no tag may be repeated. Therefore,
1332 // more than 5 tags is an error.
1333
1334 if (count > 5)
1335 ThrowBadFormat ("too many tags in dng_image_stats");
1336
1337 // Read each child tag.
1338
1339 for (uint32 i = 0; i < count; i++)
1340 {
1341
1342 // Read child tag code.
1343
1344 uint32 childTagCode = stream.Get_uint32 ();
1345
1346 // Read byte length of child tag data.
1347
1348 uint32 length = stream.Get_uint32 ();
1349
1350 // Byte length must be positive.
1351
1352 if (length == 0)
1353 ThrowBadFormat ("child tag byte length must be > 0");
1354
1355 // Byte length must be multiple of 4.
1356
1357 if ((length & 3) != 0)
1358 ThrowBadFormat ("child tag byte length expected to be multiple of 4");
1359
1360 // Check maximum value of byte length.
1361
1362 constexpr uint32 kMaxBytes = 4 + kMaxSamples * 4 * (kMaxColorPlanes + 1);
1363
1364 if (length > kMaxBytes)
1365 ThrowBadFormat ("child tag byte length too large");
1366
1367 // Read all floats.
1368
1369 std::vector<real32> *data = nullptr;
1370
1371 switch (childTagCode)
1372 {
1373
1374 case kTag_WeightedAverage:
1375 {
1376 data = &fWeightedAverage;
1377 break;
1378 }
1379
1380 case kTag_Weights:
1381 {
1382 data = &fWeights;
1383 break;
1384 }
1385
1386 case kTag_ColorAverage:
1387 {
1388 data = &fColorAverage;
1389 break;
1390 }
1391
1392 default:
1393 break;
1394
1395 }
1396
1397 if (data)
1398 {
1399
1400 const uint32 numFloats = (length >> 2);
1401
1402 data->resize (numFloats);
1403
1404 for (uint32 c = 0; c < numFloats; c++)
1405 (*data) [c] = stream.Get_real32 ();
1406
1407 }
1408
1409 else if (childTagCode == kTag_WeightedSamples)
1410 {
1411
1412 const uint32 sampleCount = stream.Get_uint32 ();
1413
1414 // Check sample count requirements.
1415
1416 if (sampleCount == 0)
1417 ThrowBadFormat ("too few samples for weighted samples");
1418
1419 if (sampleCount > kMaxSamples)
1420 ThrowBadFormat ("too many samples for weighted samples");
1421
1422 // Check byte length.
1423
1424 if (4 + (8 * sampleCount) != length)
1425 ThrowBadFormat ("mismatch byte length for weighted samples");
1426
1427 // Read the child tag data.
1428
1429 fWeightedSamples.resize (sampleCount);
1430
1431 for (auto &sample : fWeightedSamples)
1432 {
1433
1434 sample.fFrac = stream.Get_real32 ();
1435 sample.fValue = stream.Get_real32 ();
1436
1437 }
1438
1439 }
1440
1441 else if (childTagCode == kTag_ColorSamples)
1442 {
1443
1444 const uint32 sampleCount = stream.Get_uint32 ();
1445
1446 // Check sample count requirements.
1447
1448 if (sampleCount == 0)
1449 ThrowBadFormat ("too few samples for color samples");
1450
1451 if (sampleCount > kMaxSamples)
1452 ThrowBadFormat ("too many samples for color samples");
1453
1454 // Infer plane count.
1455
1456 const uint32 planes = ((length - 4) / sampleCount / 4) - 1;
1457
1458 if (planes == 0)
1459 ThrowBadFormat ("unexpected 0 plane count for color samples");
1460
1461 if (planes > kMaxColorPlanes)
1462 ThrowBadFormat ("too large plane count for color samples");
1463
1464 if (4 + (sampleCount * 4 * (planes + 1)) != length)
1465 ThrowBadFormat ("mismatched plane count for color samples");
1466
1467 // Read the child tag data.
1468
1469 fColorSamples.resize (sampleCount);
1470
1471 for (auto &sample : fColorSamples)
1472 {
1473
1474 sample.fFrac = stream.Get_real32 ();
1475
1476 sample.fValues.resize (planes);
1477
1478 for (auto &value : sample.fValues)
1479 value = stream.Get_real32 ();
1480
1481 }
1482
1483 }
1484
1485 else
1486 {
1487
1488 ThrowBadFormat ("unsupported child tag code");
1489
1490 }
1491
1492 }
1493
1494 }
1495
1496 /*****************************************************************************/
1497
1498 #if qDNGValidate
1499
1500 /*****************************************************************************/
1501
1502 static void DumpTag (const char *name,
1503 const std::vector<real32> &values)
1504 {
1505
1506 if (!values.empty ())
1507 {
1508
1509 printf (" %s: %.4f",
1510 name,
1511 values.front ());
1512
1513 for (size_t i = 1; i < values.size (); i++)
1514 printf (", %.4f", values [i]);
1515
1516 printf ("\n");
1517
1518 }
1519
1520 }
1521
1522 /*****************************************************************************/
1523
1524 void dng_image_stats::Dump () const
1525 {
1526
1527 printf ("ImageStats: %u child tag(s)\n", TagCount ());
1528
1529 DumpTag ("weights", fWeights);
1530
1531 DumpTag ("weighted average", fWeightedAverage);
1532
1533 DumpTag ("color average", fColorAverage);
1534
1535 if (!fWeightedSamples.empty ())
1536 {
1537
1538 printf (" weighted samples:\n");
1539
1540 for (const auto &s : fWeightedSamples)
1541 {
1542
1543 printf (" frac: %.6f, value: %.6lf\n",
1544 s.fFrac,
1545 s.fValue);
1546
1547 }
1548
1549 }
1550
1551 if (!fColorSamples.empty ())
1552 {
1553
1554 printf (" color samples:\n");
1555
1556 for (const auto &s : fColorSamples)
1557 {
1558
1559 printf (" frac: %.6f, values: ",
1560 s.fFrac);
1561
1562 if (s.fValues.empty ())
1563 continue;
1564
1565 printf ("%.6f", s.fValues.front ());
1566
1567 for (size_t i = 1; i < s.fValues.size (); i++)
1568 printf (", %.6f", s.fValues [i]);
1569
1570 printf ("\n");
1571
1572 }
1573
1574 }
1575
1576 }
1577
1578 /*****************************************************************************/
1579
1580 #endif // qDNGValidate
1581
1582 /*****************************************************************************/