File: writer_test.cpp

package info (click to toggle)
sight 25.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 42,180 kB
  • sloc: cpp: 289,476; xml: 17,257; ansic: 9,878; python: 1,379; sh: 144; makefile: 33
file content (1035 lines) | stat: -rw-r--r-- 33,833 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
/************************************************************************
 *
 * Copyright (C) 2023-2025 IRCAD France
 *
 * This file is part of Sight.
 *
 * Sight is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Sight is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Sight. If not, see <https://www.gnu.org/licenses/>.
 *
 ***********************************************************************/

#include "writer_test.hpp"
#include "helper.hxx"

#include <core/progress/observer.hpp>
#include <core/profiling.hpp>
#include <core/os/temp_path.hpp>
#include <core/tools/uuid.hpp>

#include <io/bitmap/writer.hpp>
#include <io/dicom/reader/file.hpp>

#include <utest/filter.hpp>
#include <utest/profiling.hpp>

#include <cstdlib>
#include <future>

// This is for putenv() which is part of <cstdlib>
// cspell:ignore hicpp nvjpeg LIBJPEG LIBTIFF LUMA Acuson IMWRITE IMREAD ANYDEPTH ANYCOLOR OPENCV stoull
// NOLINTNEXTLINE(hicpp-deprecated-headers,modernize-deprecated-headers)
#include <stdlib.h>

// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION(sight::io::bitmap::ut::writer_test);

namespace sight::io::bitmap::ut
{

//------------------------------------------------------------------------------

inline static std::vector<data::image::sptr> read_dicom_images(std::size_t _count = 3)
{
    static const std::vector<data::image::sptr> s_RESULT =
        []
        {
            std::vector<data::image::sptr> images;
            auto series_set = std::make_shared<data::series_set>();
            auto reader     = std::make_shared<io::dicom::reader::file>();

            reader->set_object(series_set);

            // Read a DICOM image "us/Ultrasound Image Storage/GE, lossy JPEG"
            reader->set_folder(utest_data::dir() / "us/Ultrasound Image Storage/GE, lossy JPEG");
            {
                auto observer = std::make_shared<core::progress::observer>("Reading DICOM images");
                CPPUNIT_ASSERT_NO_THROW(reader->read(observer));
            }

            // Just to be sure we read the good data
            CPPUNIT_ASSERT_EQUAL(std::size_t(1), series_set->size());

            auto image_series = std::dynamic_pointer_cast<data::image_series>(series_set->at(0));
            CPPUNIT_ASSERT(image_series);

            auto size = image_series->size();
            CPPUNIT_ASSERT_EQUAL(std::size_t(636), size[0]);
            CPPUNIT_ASSERT_EQUAL(std::size_t(434), size[1]);
            CPPUNIT_ASSERT_EQUAL(std::size_t(1), size[2]);

            images.push_back(image_series);
            series_set->clear();

            // Read next image "us/Ultrasound Image Storage/Siemens Acuson 500"
            reader->set_folder(utest_data::dir() / "us/Ultrasound Image Storage/Siemens Acuson 500");
            {
                auto observer = std::make_shared<core::progress::observer>("Reading DICOM images");
                CPPUNIT_ASSERT_NO_THROW(reader->read(observer));
            }

            // Just to be sure we read the good data
            CPPUNIT_ASSERT_EQUAL(std::size_t(1), series_set->size());

            image_series = std::dynamic_pointer_cast<data::image_series>(series_set->at(0));
            CPPUNIT_ASSERT(image_series);

            size = image_series->size();
            CPPUNIT_ASSERT_EQUAL(std::size_t(800), size[0]);
            CPPUNIT_ASSERT_EQUAL(std::size_t(600), size[1]);
            CPPUNIT_ASSERT_EQUAL(std::size_t(1), size[2]);

            images.push_back(image_series);
            series_set->clear();

            // Read next image "us/Ultrasound Multi-frame Image Storage/Siemens Acuson 500"
            reader->set_folder(utest_data::dir() / "us/Ultrasound Multi-frame Image Storage/Siemens Acuson 500");
            {
                auto observer = std::make_shared<core::progress::observer>("Reading DICOM images");
                CPPUNIT_ASSERT_NO_THROW(reader->read(observer));
            }

            // Just to be sure we read the good data
            CPPUNIT_ASSERT_EQUAL(std::size_t(1), series_set->size());

            image_series = std::dynamic_pointer_cast<data::image_series>(series_set->at(0));
            CPPUNIT_ASSERT(image_series);

            size = image_series->size();
            CPPUNIT_ASSERT_EQUAL(std::size_t(800), size[0]);
            CPPUNIT_ASSERT_EQUAL(std::size_t(600), size[1]);
            CPPUNIT_ASSERT_EQUAL(std::size_t(60), size[2]);

            images.push_back(image_series);
            return images;
        }();

    auto copy = s_RESULT;
    copy.resize(_count);
    return copy;
}

//------------------------------------------------------------------------------

inline static void profile_writer(
    const std::vector<data::image::sptr>& _images,
    const std::filesystem::path& _tmp_folder,
    std::size_t _loop,
    backend _backend,
    writer::mode _mode,
    std::vector<std::future<void> >& _tasks
)
{
    auto writer = std::make_shared<io::bitmap::writer>();

    const auto [BACKEND, EXT] = backend_to_string(_backend);
    const std::string mode = mode_to_string(_mode);

    const std::string file_suffix = "_" + BACKEND + "_" + mode + EXT;
    const std::string label       = BACKEND + " (" + mode + ")";

    // Get size, psnr, ...
    for(std::size_t i = 0 ; const auto& image : _images)
    {
        // Write image
        writer->set_object(image);
        const auto& tmp_path = _tmp_folder / (std::to_string(i) + file_suffix);
        writer->set_file(tmp_path);
        CPPUNIT_ASSERT_NO_THROW(writer->write(_backend, _mode));

        SIGHT_INFO(label << " size: " << std::filesystem::file_size(tmp_path));

        // PSNR is only relevant with lossy format...
        if(EXT.ends_with("jpg") || EXT.ends_with(".jpeg"))
        {
            SIGHT_INFO(label << " PSNR: " << compute_psnr(image, read_image(tmp_path)));
        }

        // Cleanup
        std::filesystem::remove_all(tmp_path);
        ++i;
    }

    // Now profile writing
    SIGHT_PROFILE_FUNC(
        [&]
        (std::size_t _i)
        {
            for(std::size_t j = 0 ; const auto& image : _images)
            {
                writer->set_object(image);
                const auto& tmp_path = _tmp_folder / (std::to_string(_i) + "_" + std::to_string(j++) + file_suffix);
                writer->set_file(tmp_path);

                CPPUNIT_ASSERT_NO_THROW(writer->write(_backend, _mode));

                // Schedule cleanup
                _tasks.emplace_back(std::async(std::launch::deferred, [ = ]{std::filesystem::remove_all(tmp_path);}));
            }
        },
        _loop,
        label,
        0.1
    );

    // Wait for all file delete task to finish
    while(!_tasks.empty())
    {
        _tasks.back().wait();
        _tasks.pop_back();
    }
}

//------------------------------------------------------------------------------

inline static void profile_open_cv_writer(
    const std::vector<data::image::sptr>& _images,
    const std::filesystem::path& _tmp_folder,
    std::size_t _loop,
    std::string _ext,
    writer::mode _mode,
    std::vector<std::future<void> >& _tasks
)
{
    const std::string mode = mode_to_string(_mode);

    const std::string file_suffix = "_OPENCV_" + mode + "." + _ext;
    const std::string label       = "OpenCV (" + _ext + " - " + mode + ")";

    // Get size, psnr, ...
    for(std::size_t i = 0 ; const auto& image : _images)
    {
        const auto& tmp_path = _tmp_folder / (std::to_string(i++) + file_suffix);

        // Convert Image to OpenCV Mat
        const cv::Mat& mat = image_to_mat(image);

        // Write image
        if(_mode == writer::mode::best)
        {
            CPPUNIT_ASSERT(
                cv::imwrite(
                    tmp_path.string(),
                    mat,
                {
                    cv::IMWRITE_JPEG_QUALITY, 100,
                    cv::IMWRITE_JPEG_CHROMA_QUALITY, 100,
                    cv::IMWRITE_JPEG_LUMA_QUALITY, 100,
                    cv::IMWRITE_JPEG_OPTIMIZE, 1,
                    cv::IMWRITE_PNG_COMPRESSION, 9,
                    cv::IMWRITE_PNG_STRATEGY, cv::IMWRITE_PNG_STRATEGY_DEFAULT
                })
            );
        }
        else
        {
            CPPUNIT_ASSERT(cv::imwrite(tmp_path.string(), mat));
        }

        SIGHT_INFO(label << " size: " << std::filesystem::file_size(tmp_path));

        if(_ext.ends_with("jpg") || _ext.ends_with(".jpeg"))
        {
            SIGHT_INFO(label << " PSNR: " << compute_psnr(image, read_image(tmp_path)));
        }

        // Cleanup
        std::filesystem::remove_all(tmp_path);
    }

    // Now profile writing
    SIGHT_PROFILE_FUNC(
        [&]
        (std::size_t _i)
        {
            for(std::size_t j = 0 ; const auto& image : _images)
            {
                const auto& tmp_path = _tmp_folder / (std::to_string(_i) + "_" + std::to_string(j++) + file_suffix);

                // Convert Image to OpenCV Mat
                const cv::Mat& mat = image_to_mat(image);

                // Write image
                if(_mode == writer::mode::best)
                {
                    CPPUNIT_ASSERT(
                        cv::imwrite(
                            tmp_path.string(),
                            mat,
                    {
                        cv::IMWRITE_JPEG_QUALITY, 100,
                        cv::IMWRITE_JPEG_CHROMA_QUALITY, 100,
                        cv::IMWRITE_JPEG_LUMA_QUALITY, 100,
                        cv::IMWRITE_JPEG_OPTIMIZE, 1,
                        cv::IMWRITE_PNG_COMPRESSION, 9,
                        cv::IMWRITE_PNG_STRATEGY, cv::IMWRITE_PNG_STRATEGY_DEFAULT
                    })
                    );
                }
                else
                {
                    CPPUNIT_ASSERT(cv::imwrite(tmp_path.string(), mat));
                }

                // Schedule cleanup
                _tasks.emplace_back(std::async(std::launch::deferred, [ = ]{std::filesystem::remove_all(tmp_path);}));
            }
        },
        _loop,
        label,
        0.1
    );

    // Wait for all file delete task to finish
    while(!_tasks.empty())
    {
        _tasks.back().wait();
        _tasks.pop_back();
    }
}

//------------------------------------------------------------------------------

void writer_test::setUp()
{
    std::string jasper("OPENCV_IO_ENABLE_JASPER=1");
    putenv(jasper.data());
}

//------------------------------------------------------------------------------

void writer_test::tearDown()
{
}

//------------------------------------------------------------------------------

void writer_test::basic_test()
{
    auto writer = std::make_shared<io::bitmap::writer>();

    CPPUNIT_ASSERT_EQUAL(io::bitmap::extensions(backend::libtiff).front(), writer->extension());
}

//------------------------------------------------------------------------------

void writer_test::extensions_test()
{
    std::vector<data::sequenced_set<std::string> > extensions {
        {".jpg", ".jpeg"},
        {".jp2"},
        {".j2k"},
        {".tiff", ".tif"},
        {".png"}
    };

    std::vector<backend> backends {
        io::bitmap::nvjpeg() ? backend::nvjpeg : backend::libjpeg,
        io::bitmap::nvjpeg2k() ? backend::nvjpeg2k : backend::openjpeg,
        io::bitmap::nvjpeg2k() ? backend::nvjpeg2k_j2k : backend::openjpeg_j2k,
        backend::libtiff,
        backend::libpng
    };

    for(std::size_t i = 0 ; i < extensions.size() ; ++i)
    {
        const auto& extension_set        = extensions[i];
        const auto& backend              = backends[i];
        const auto& actual_extension_set = io::bitmap::extensions(backend);

        CPPUNIT_ASSERT_EQUAL(extension_set.size(), actual_extension_set.size());

        for(std::size_t j = 0 ; j < extension_set.size() ; ++j)
        {
            CPPUNIT_ASSERT_EQUAL(extension_set[j], actual_extension_set[j]);
        }
    }
}

//------------------------------------------------------------------------------

void writer_test::wildcard_test()
{
    std::vector<backend> backends {
        io::bitmap::nvjpeg() ? backend::nvjpeg : backend::libjpeg,
        io::bitmap::nvjpeg2k() ? backend::nvjpeg2k : backend::openjpeg,
        io::bitmap::nvjpeg2k() ? backend::nvjpeg2k_j2k : backend::openjpeg_j2k,
        backend::libtiff,
        backend::libpng
    };

    static constexpr auto s_JPEG_LABEL {"JPEG image"};
    static constexpr auto s_TIFF_LABEL {"TIFF image"};
    static constexpr auto s_PNG_LABEL {"PNG image"};
    static constexpr auto s_J2_K_LABEL {"JPEG2000 image"};

    std::vector<std::string> labels {
        s_JPEG_LABEL,
        s_J2_K_LABEL,
        s_J2_K_LABEL,
        s_TIFF_LABEL,
        s_PNG_LABEL
    };

    static constexpr auto s_JPEG_EXT {".jpeg"};
    static constexpr auto s_JPG_EXT {".jpg"};
    static constexpr auto s_TIF_EXT {".tif"};
    static constexpr auto s_TIFF_EXT {".tiff"};
    static constexpr auto s_PNG_EXT {".png"};
    static constexpr auto s_J_P2_EXT {".jp2"};
    static constexpr auto s_J2_K_EXT {".j2k"};

    std::vector<std::string> wildcards {
        std::string("*") + s_JPG_EXT + " *" + s_JPEG_EXT,
        std::string("*") + s_J_P2_EXT,
        std::string("*") + s_J2_K_EXT,
        std::string("*") + s_TIF_EXT + " *" + s_TIFF_EXT,
        std::string("*") + s_PNG_EXT
    };

    for(std::size_t index = 0 ; const auto& backend : backends)
    {
        const auto& [label, wildcard] = io::bitmap::wildcard_filter(backend);

        CPPUNIT_ASSERT_EQUAL(labels[index], label);
        CPPUNIT_ASSERT_EQUAL(wildcards[index], wildcard);
        ++index;
    }
}

//------------------------------------------------------------------------------

inline static void conformance(
    const std::vector<backend>& _supported,
    const std::vector<backend>& _unsupported,
    core::type _type,
    enum data::image::pixel_format_t _format
)
{
    // Create a temporary directory
    core::os::temp_dir tmp_dir;

    // Create the synthetic image
    const auto& expected_image = get_synthetic_image(0, _type, _format);

    // Create the writer
    auto writer = std::make_shared<io::bitmap::writer>();
    writer->set_object(expected_image);

    // Build mode list
    const std::vector modes {
        writer::mode::best,
        writer::mode::fast
    };

    // For each backend and each mode
    for(const auto& backend : _supported)
    {
        const std::string& backend_string = backend_to_string(backend).first;

        for(const auto& mode : modes)
        {
            // Test write
            const auto& file_path = tmp_dir / ("conformance" + file_suffix(backend, mode));
            CPPUNIT_ASSERT_NO_THROW(writer->set_file(file_path));
            CPPUNIT_ASSERT_NO_THROW(writer->write(backend, mode));
            CPPUNIT_ASSERT_MESSAGE(file_path.string() + " doesn't exist.", std::filesystem::exists(file_path));

            const auto& actual_image = read_image(file_path.string());
            CPPUNIT_ASSERT(actual_image);

            if(backend == backend::openjpeg || backend == backend::nvjpeg2k)
            {
                // Because of bad encoder or decoder implementation, JPEG2000 is not always *perfectly* lossless.
                // Indeed, it is mathematically, but the implementation can suffer from some corner floating point
                // rounding errors. This seems to be the case with openCV/Jasper plugin, at least, in this test
                // which uses synthetic data. One component value differ 0x254 instead of 0x253
                // As a workaround, we try to encode two times, and we consider success if multiple pass doesn't
                // degrade the situation more.
                writer->set_object(actual_image);
                const auto& copy_file_path = tmp_dir / ("conformance_copy" + file_suffix(backend, mode));
                CPPUNIT_ASSERT_NO_THROW(writer->set_file(copy_file_path));
                CPPUNIT_ASSERT_NO_THROW(writer->write(backend, mode));
                CPPUNIT_ASSERT_MESSAGE(
                    copy_file_path.string() + " doesn't exist.",
                    std::filesystem::exists(copy_file_path)
                );

                const auto& actual_image_copy = read_image(copy_file_path.string());
                CPPUNIT_ASSERT(actual_image_copy);

                CPPUNIT_ASSERT_MESSAGE(
                    "The image are not equal for backend '" + backend_string + "', mode '" + mode_to_string(mode)
                    + "', format '" + pixel_format_to_string(_format) + "', type '" + _type.name() + "'",
                    *expected_image == *actual_image
                );

                // Restore back the original source
                writer->set_object(expected_image);
            }
            // Compare pixels only for lossless backend
            else if(backend != backend::libjpeg && backend != backend::nvjpeg)
            {
                CPPUNIT_ASSERT_MESSAGE(
                    "The image are not equal for backend '" + backend_string + "', mode '" + mode_to_string(mode)
                    + "', format '" + pixel_format_to_string(_format) + "', type '" + _type.name() + "'",
                    *expected_image == *actual_image
                );
            }
            else
            {
                // Compare at least sizes...
                const auto& expected_size = expected_image->size();
                const auto& actual_size   = actual_image->size();
                CPPUNIT_ASSERT_EQUAL(expected_size[0], actual_size[0]);
                CPPUNIT_ASSERT_EQUAL(expected_size[1], actual_size[1]);
                CPPUNIT_ASSERT_EQUAL(expected_size[2], actual_size[2]);
                CPPUNIT_ASSERT_EQUAL(expected_image->pixel_format(), actual_image->pixel_format());
                CPPUNIT_ASSERT_EQUAL(expected_image->type(), actual_image->type());

                // Ensure that psnr is at least > 20
                const double psnr = compute_psnr(expected_image, actual_image);
                CPPUNIT_ASSERT_MESSAGE(
                    "The image seems to be different with backend '"
                    + backend_string
                    + "', PSNR="
                    + std::to_string(psnr)
                    + "dB",
                    psnr > 20
                );
            }
        }
    }

    // For each backend and each mode
    for(const auto& backend : _unsupported)
    {
        for(const auto& mode : modes)
        {
            // Test write
            const auto& file_path = tmp_dir / ("conformance" + file_suffix(backend, mode));
            CPPUNIT_ASSERT_NO_THROW(writer->set_file(file_path));
            CPPUNIT_ASSERT_THROW(writer->write(backend, mode), core::exception);
        }
    }
}

//------------------------------------------------------------------------------

void writer_test::conformance_test()
{
    // UINT8 RGB
    {
        if(io::bitmap::nvjpeg2k())
        {
            conformance(
                {
                    backend::libjpeg,
                    backend::libpng,
                    backend::libtiff,
                    backend::openjpeg,
                    backend::nvjpeg2k,
                    backend::nvjpeg
                },
                {},
                core::type::UINT8,
                data::image::pixel_format_t::rgb
            );
        }
        else if(io::bitmap::nvjpeg())
        {
            conformance(
                {backend::libjpeg, backend::libpng, backend::libtiff, backend::openjpeg, backend::nvjpeg},
                {backend::nvjpeg2k},
                core::type::UINT8,
                data::image::pixel_format_t::rgb
            );
        }
        else
        {
            conformance(
                {backend::libjpeg, backend::libpng, backend::libtiff, backend::openjpeg},
                {backend::nvjpeg2k, backend::nvjpeg},
                core::type::UINT8,
                data::image::pixel_format_t::rgb
            );
        }
    }

    // UINT8 GRAYSCALE
    {
        if(io::bitmap::nvjpeg2k())
        {
            conformance(
                {backend::libjpeg, backend::libpng, backend::libtiff, backend::openjpeg, backend::nvjpeg2k},
                {backend::nvjpeg},
                core::type::UINT8,
                data::image::pixel_format_t::gray_scale
            );
        }
        else
        {
            conformance(
                {backend::libjpeg, backend::libpng, backend::libtiff, backend::openjpeg},
                {backend::nvjpeg2k, backend::nvjpeg},
                core::type::UINT8,
                data::image::pixel_format_t::gray_scale
            );
        }
    }

    // UINT16 RGB
    {
        if(io::bitmap::nvjpeg2k())
        {
            conformance(
                {backend::libtiff, backend::openjpeg, backend::nvjpeg2k},
                {backend::libjpeg, backend::nvjpeg},
                core::type::UINT16,
                data::image::pixel_format_t::rgb
            );
        }
        else
        {
            conformance(
                {backend::libpng, backend::libtiff, backend::openjpeg},
                {backend::libjpeg, backend::nvjpeg2k, backend::nvjpeg},
                core::type::UINT16,
                data::image::pixel_format_t::rgb
            );
        }
    }

    // UINT16 GRAYSCALE
    {
        if(io::bitmap::nvjpeg2k())
        {
            conformance(
                {backend::libpng, backend::libtiff, backend::openjpeg, backend::nvjpeg2k},
                {backend::libjpeg, backend::nvjpeg},
                core::type::UINT16,
                data::image::pixel_format_t::gray_scale
            );
        }
        else
        {
            conformance(
                {backend::libpng, backend::libtiff, backend::openjpeg},
                {backend::libjpeg, backend::nvjpeg2k, backend::nvjpeg},
                core::type::UINT16,
                data::image::pixel_format_t::gray_scale
            );
        }
    }
}

//------------------------------------------------------------------------------

void writer_test::empty_image_test()
{
    // Create a temporary directory
    core::os::temp_dir tmp_dir;

    const auto& empty_image = std::make_shared<data::image>();
    auto writer             = std::make_shared<io::bitmap::writer>();
    writer->set_object(empty_image);

    std::vector<std::string> extensions {".jpeg", ".tiff", ".png", ".jp2", ".j2k"};

    for(const auto& ext : extensions)
    {
        const auto& tmp_path = tmp_dir / ("empty" + ext);
        CPPUNIT_ASSERT_NO_THROW(writer->set_file(tmp_path));
        auto observer = std::make_shared<core::progress::observer>("Writing empty image... ");
        CPPUNIT_ASSERT_THROW(writer->write(observer), core::exception);
        CPPUNIT_ASSERT_MESSAGE(tmp_path.string() + " exists.", !std::filesystem::exists(tmp_path));
    }
}

//------------------------------------------------------------------------------

void writer_test::wrong_path_test()
{
    // Create a temporary directory, with a non existing leaf directory
    core::os::temp_dir tmp_dir;
    const auto tmp_folder = tmp_dir / uuid::generate();
    std::filesystem::remove_all(tmp_folder);

    const auto& image_series = read_dicom_images(1);
    auto writer              = std::make_shared<io::bitmap::writer>();
    writer->set_object(image_series.front());

    std::vector<std::string> extensions {".jpeg", ".tiff", ".png", ".jp2", ".j2k"};

    for(const auto& ext : extensions)
    {
        const auto& tmp_path = tmp_folder / ("wrong_path" + ext);
        CPPUNIT_ASSERT_NO_THROW(writer->set_file(tmp_path));
        auto observer = std::make_shared<core::progress::observer>("Writing wrong path image... ");
        CPPUNIT_ASSERT_NO_THROW(writer->write(observer));
        CPPUNIT_ASSERT_MESSAGE(tmp_path.string() + " doesn't exist.", std::filesystem::exists(tmp_path));
    }
}

//------------------------------------------------------------------------------

void writer_test::from_dicom_test()
{
    const auto& image_series = read_dicom_images();

    // Create a temporary directory
    core::os::temp_dir tmp_dir;

    // Use a big epsilon since size can vary between platforms and libraries version, especially for nvJPEG2000
    static constexpr std::int64_t s_EPSILON = 5000;

    static constexpr std::array<std::int64_t, 3> s_NVJPEG_SIZE       = {278295, 174839, 254339};
    static constexpr std::array<std::int64_t, 3> s_LIBJPEG_SIZE      = {176726, 140868, 165298};
    static constexpr std::array<std::int64_t, 3> s_NVJPEG2K_JP2_SIZE = {282577, 144367, 276889};
    static constexpr std::array<std::int64_t, 3> s_NVJPEG2K_JK2_SIZE = {279052, 141242, 272350};
    static constexpr std::array<std::int64_t, 3> s_TIFF_SIZE         = {493572, 597782, 693950};
    static constexpr std::array<std::int64_t, 3> s_PNG_SIZE          = {313130, 220007, 352335};
    static constexpr std::array<std::int64_t, 3> s_OPENJPEG_JP2_SIZE = {279111, 141282, 272407};
    static constexpr std::array<std::int64_t, 3> s_OPENJPEG_JK2_SIZE = {279111, 141282, 272407};

    auto writer = std::make_shared<io::bitmap::writer>();

    const auto& write =
        [&](std::size_t _i, const std::string& _ext)
        {
            const auto& tmp_path = tmp_dir / (std::to_string(_i) + "_from_dicom" + _ext);
            CPPUNIT_ASSERT_NO_THROW(writer->set_file(tmp_path));
            auto observer = std::make_shared<core::progress::observer>("Writing from DICOM image... ");
            CPPUNIT_ASSERT_NO_THROW(writer->write(observer));
            CPPUNIT_ASSERT(std::filesystem::exists(tmp_path));

            return std::int64_t(std::filesystem::file_size(tmp_path));
        };

    for(std::size_t i = 0 ; const auto& image : image_series)
    {
        writer->set_object(image);

        // Test .jpg with nvJPEG (if available)
        if(io::bitmap::nvjpeg())
        {
            const auto file_size = write(i, ".jpg");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_NVJPEG_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_NVJPEG_SIZE[i] - file_size) <= s_EPSILON
            );
        }
        else
        {
            // Use libJPEG as fallback
            const auto file_size = write(i, ".jpg");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_LIBJPEG_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_LIBJPEG_SIZE[i] - file_size) <= s_EPSILON
            );
        }

        // Test .jp2 with nvjpeg2k (if available)
        if(io::bitmap::nvjpeg2k())
        {
            const auto file_size = write(i, ".jp2");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_NVJPEG2K_JP2_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_NVJPEG2K_JP2_SIZE[i] - file_size) <= s_EPSILON
            );
        }
        else
        {
            // Use openJPEG as fallback
            const auto file_size = write(i, ".jp2");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_OPENJPEG_JP2_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_OPENJPEG_JP2_SIZE[i] - file_size) <= s_EPSILON
            );
        }

        // Test .j2k with nvjpeg2k (if available)
        if(io::bitmap::nvjpeg2k())
        {
            const auto file_size = write(i, ".j2k");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_NVJPEG2K_JK2_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_NVJPEG2K_JK2_SIZE[i] - file_size) <= s_EPSILON
            );
        }
        else
        {
            // Use openJPEG as fallback
            const auto file_size = write(i, ".j2k");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_OPENJPEG_JK2_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_OPENJPEG_JK2_SIZE[i] - file_size) <= s_EPSILON
            );
        }

        // test .tiff with libTIFF
        {
            const auto file_size = write(i, ".tiff");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_TIFF_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_TIFF_SIZE[i] - file_size) <= s_EPSILON
            );
        }

        // test .png with libPNG
        {
            const auto file_size = write(i, ".png");

            CPPUNIT_ASSERT_MESSAGE(
                "expected[" + std::to_string(i) + "] (" + std::to_string(s_PNG_SIZE[i])
                + ") != actual (" + std::to_string(file_size) + ")",
                std::abs(s_PNG_SIZE[i] - file_size) <= s_EPSILON
            );
        }

        ++i;
    }
}

//------------------------------------------------------------------------------

void writer_test::profiling_test()
{
    auto images = read_dicom_images();
    images.push_back(get_synthetic_image(0));

    // Create a temporary directory
    core::os::temp_dir tmp_dir;

    // Check how many loop to perform
    static const char* const s_ENV_LOOP   = std::getenv("PROFILETEST_LOOP");
    static const std::size_t s_LOOP_COUNT =
        s_ENV_LOOP != nullptr
        ? std::stoull(s_ENV_LOOP)
        : 1;

    SIGHT_INFO("Loop: " << s_LOOP_COUNT);

    std::vector<std::future<void> > tasks;

    // nvJPEG
    if(io::bitmap::nvjpeg())
    {
        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::nvjpeg,
            writer::mode::fast,
            tasks
        );

        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::nvjpeg,
            writer::mode::best,
            tasks
        );
    }

    // nvjpeg2k
    if(io::bitmap::nvjpeg2k())
    {
        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::nvjpeg2k,
            writer::mode::fast,
            tasks
        );

        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::nvjpeg2k,
            writer::mode::best,
            tasks
        );
    }

    // libJPEG
    {
        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::libjpeg,
            writer::mode::fast,
            tasks
        );

        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::libjpeg,
            writer::mode::best,
            tasks
        );
    }

    // libTIFF
    {
        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::libtiff,
            writer::mode::fast,
            tasks
        );

        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::libtiff,
            writer::mode::best,
            tasks
        );
    }

    // libPNG
    {
        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::libpng,
            writer::mode::fast,
            tasks
        );

        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::libpng,
            writer::mode::best,
            tasks
        );
    }

    // openjpeg
    {
        profile_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            backend::openjpeg,
            writer::mode::fast,
            tasks
        );
    }

    if(!utest::filter::ignore_slow_tests() && s_ENV_LOOP != nullptr)
    {
        // Use OPENCV JPEG
        profile_open_cv_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            "jpg",
            writer::mode::fast,
            tasks
        );

        profile_open_cv_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            "jpg",
            writer::mode::best,
            tasks
        );

        // Use OPENCV TIFF
        profile_open_cv_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            "tiff",
            writer::mode::fast,
            tasks
        );

        // Use OPENCV PNG
        profile_open_cv_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            "png",
            writer::mode::fast,
            tasks
        );

        profile_open_cv_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            "png",
            writer::mode::best,
            tasks
        );

        // Use OPENCV WEBP
        profile_open_cv_writer(
            images,
            tmp_dir,
            s_LOOP_COUNT,
            "webp",
            writer::mode::fast,
            tasks
        );
    }

    for(const auto& task : tasks)
    {
        task.wait();
    }
}

} // namespace sight::io::bitmap::ut