forked from AcademySoftwareFoundation/OpenImageIO
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoiiotool.cpp
More file actions
7701 lines (6796 loc) · 280 KB
/
oiiotool.cpp
File metadata and controls
7701 lines (6796 loc) · 280 KB
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
// Copyright Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause and Apache-2.0
// https://github.com/AcademySoftwareFoundation/OpenImageIO
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <regex>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "oiiotool.h"
#include <OpenEXR/ImfTimeCode.h>
#include <OpenImageIO/Imath.h>
#include <OpenImageIO/argparse.h>
#include <OpenImageIO/color.h>
#include <OpenImageIO/deepdata.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/filter.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
#include <OpenImageIO/imagebufalgo_util.h>
#include <OpenImageIO/imagecache.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/simd.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/timer.h>
#ifndef NDEBUG
# define OIIO_UNIT_TEST_QUIET_SUCCESS
# include <OpenImageIO/unittest.h>
#endif
#ifdef USE_OPENCV
# include <OpenImageIO/imagebufalgo_opencv.h>
#endif
using namespace OIIO;
using namespace OiioTool;
using namespace ImageBufAlgo;
using pvt::print_info_options;
#ifndef NDEBUG
# define OIIO_UNIT_TESTS 1
#endif
#ifndef OPENIMAGEIO_METADATA_HISTORY_DEFAULT
# define OPENIMAGEIO_METADATA_HISTORY_DEFAULT 0
#endif
// Macro to fully set up the "action" function that straightforwardly calls
// a lambda for each subimage. Beware, the macro expansion rules may require
// you may need to enclose the lambda itself in parenthesis () if there it
// contains commas that are not inside other parentheses.
#define OIIOTOOL_OP(name, ninputs, ...) \
static void action_##name(Oiiotool& ot, cspan<const char*> argv) \
{ \
if (ot.postpone_callback(ninputs, action_##name, argv)) \
return; \
OiiotoolOp op(ot, "-" #name, argv, ninputs, __VA_ARGS__); \
op(); \
}
// Lke OIIOTOOL_OP, but designate the op as "inplace" -- which means it
// uses the input image itself as the destination.
#define OIIOTOOL_INPLACE_OP(name, ninputs, ...) \
static void action_##name(Oiiotool& ot, cspan<const char*> argv) \
{ \
if (ot.postpone_callback(ninputs, action_##name, argv)) \
return; \
OiiotoolOp op(ot, "-" #name, argv, ninputs, __VA_ARGS__); \
op.inplace(true); \
op(); \
}
// Canned setup for an op that uses one image on the stack.
#define UNARY_IMAGE_OP(name, impl) \
OIIOTOOL_OP(name, 1, [](OiiotoolOp& op, span<ImageBuf*> img) { \
return impl(*img[0], *img[1]); \
})
// Canned setup for an op that uses two images on the stack.
#define BINARY_IMAGE_OP(name, impl) \
OIIOTOOL_OP(name, 2, [](OiiotoolOp& op, span<ImageBuf*> img) { \
return impl(*img[0], *img[1], *img[2]); \
})
// Canned setup for an op that uses one image on the stack and one float
// on the command line.
#define BINARY_IMAGE_FLOAT_OP(name, impl) \
OIIOTOOL_OP(name, 1, [](OiiotoolOp& op, span<ImageBuf*> img) { \
float val = Strutil::stof(op.args(1)); \
return impl(*img[0], *img[1], val); \
})
// Canned setup for an op that uses one image on the stack and one color
// on the command line.
#define BINARY_IMAGE_COLOR_OP(name, impl, defaultval) \
OIIOTOOL_OP(name, 1, [](OiiotoolOp& op, span<ImageBuf*> img) { \
int nchans = img[1]->spec().nchannels; \
std::vector<float> val(nchans, defaultval); \
int nvals = Strutil::extract_from_list_string(val, op.args(1)); \
val.resize(nvals); \
val.resize(nchans, val.size() == 1 ? val.back() : defaultval); \
return impl(*img[0], *img[1], val, ROI(), 0); \
})
// Macro to fully set up the "action" function that straightforwardly
// calls a custom OiiotoolOp class.
#define OP_CUSTOMCLASS(name, opclass, ninputs) \
static void action_##name(Oiiotool& ot, cspan<const char*> argv) \
{ \
if (ot.postpone_callback(ninputs, action_##name, argv)) \
return; \
opclass op(ot, #name, argv); \
op(); \
}
Oiiotool::Oiiotool() { clear_options(); }
void
Oiiotool::clear_options()
{
verbose = false;
quiet = false;
debug = false;
dryrun = false;
runstats = false;
noclobber = false;
allsubimages = false;
printinfo = false;
printstats = false;
dumpdata = false;
dumpdata_showempty = true;
dumpdata_C = false;
hash = false;
updatemode = false;
autoorient = false;
autocc = false;
autoccunpremult = false;
autopremult = true;
nativeread = false;
metamerge = false;
cachesize = 4096;
autotile = 0; // was: 4096
// FIXME: Turned off autotile by default Jan 2018 after thinking that
// it was possible to deadlock when doing certain parallel IBA functions
// in combination with autotile. When the deadlock possibility is fixed,
// maybe we'll turn it back to on by default.
frame_padding = 0;
eval_enable = true;
skip_bad_frames = false;
full_command_line.clear();
printinfo_metamatch.clear();
printinfo_nometamatch.clear();
printinfo_verbose = false;
clear_input_config();
m_first_input_dimensions = ImageSpec();
output_dataformat = TypeDesc::UNKNOWN;
output_channelformats.clear();
output_bitspersample = 0;
output_scanline = false;
output_tilewidth = 0;
output_tileheight = 0;
output_compression = "";
output_quality = -1;
output_planarconfig = "default";
output_adjust_time = false;
output_autocrop = true;
output_autotrim = false;
output_dither = false;
output_force_tiles = false;
metadata_nosoftwareattrib = false;
#if OPENIMAGEIO_METADATA_HISTORY_DEFAULT
metadata_history = Strutil::from_string<int>(
getenv("OPENIMAGEIO_METADATA_HISTORY", "1"));
#else
metadata_history = Strutil::from_string<int>(
getenv("OPENIMAGEIO_METADATA_HISTORY"));
#endif
diff_warnthresh = 1.0e-6f;
diff_warnpercent = 0;
diff_hardwarn = std::numeric_limits<float>::max();
diff_failthresh = 1.0e-6f;
diff_failpercent = 0;
diff_hardfail = std::numeric_limits<float>::max();
m_pending_callback = nullptr;
m_pending_argv.clear();
frame_number = 0;
frame_padding = 0;
input_dataformat = TypeUnknown;
input_bitspersample = 0;
input_channelformats.clear();
}
ColorConfig&
Oiiotool::colorconfig()
{
// It's safe to check the pointer and if it exists, return it, since
// once it's created, it will never be changed.
if (ColorConfig* cc = m_colorconfig.get())
return *cc;
// Otherwise, we need to create it. But we need to be thread-safe.
static std::mutex colorconfig_mutex;
std::lock_guard lock(colorconfig_mutex);
if (!m_colorconfig) {
if (debug)
OIIO::print("oiiotool Creating ColorConfig\n");
m_colorconfig.reset(new ColorConfig);
}
return *m_colorconfig.get();
}
void
Oiiotool::clear_input_config()
{
input_config = ImageSpec();
input_config_set = false;
if (!autopremult) {
input_config.attribute("oiio:UnassociatedAlpha", 1);
input_config_set = true;
}
}
static std::string
format_resolution(int w, int h, int x, int y)
{
return Strutil::fmt::format("{}x{}{:+d}{:+d}", w, h, x, y);
}
static std::string
format_resolution(float w, float h, float x, float y)
{
return Strutil::fmt::format("{}x{}{:+g}{:+g}", w, h, x, y);
}
static std::string
format_resolution(int w, int h, int d, int x, int y, int z)
{
return Strutil::fmt::format("{}x{}x{}{:+d}{:+d}{:+d}", w, h, d, x, y, z);
}
template<typename T>
static bool
scan_resolution(string_view str, T& w, T& h)
{
return Strutil::parse_value(str, w) && Strutil::parse_char(str, 'x')
&& Strutil::parse_value(str, h);
}
template<typename T>
static bool
scan_offset(string_view str, T& x, T& y)
{
return Strutil::parse_value(str, x)
&& (str.size() && (str[0] == '+' || str[0] == '-'))
&& Strutil::parse_value(str, y);
}
template<typename T>
static bool
scan_res_offset(string_view str, T& w, T& h, T& x, T& y)
{
return Strutil::parse_value(str, w) && Strutil::parse_char(str, 'x')
&& Strutil::parse_value(str, h)
&& (str.size() && (str[0] == '+' || str[0] == '-'))
&& Strutil::parse_value(str, x)
&& (str.size() && (str[0] == '+' || str[0] == '-'))
&& Strutil::parse_value(str, y); // NOSONAR
}
static bool
scan_scale_percent(string_view str, float& x, float& y)
{
return Strutil::parse_value(str, x) && Strutil::parse_char(str, '%')
&& Strutil::parse_char(str, 'x') && Strutil::parse_value(str, y)
&& Strutil::parse_char(str, '%'); // NOSONAR
}
static bool
scan_scale_percent(string_view str, float& x)
{
return Strutil::parse_value(str, x) && Strutil::parse_char(str, '%');
}
template<typename T>
static bool
scan_box(string_view str, T& xmin, T& ymin, T& xmax, T& ymax)
{
Strutil::trim_whitespace(str);
T f[4];
if (Strutil::parse_values(str, "", f, ",") && str.empty()) {
xmin = f[0];
ymin = f[1];
xmax = f[2];
ymax = f[3];
return true;
}
return false;
}
#ifdef OIIO_UNIT_TESTS
static void
unit_test_scan_box()
{
Strutil::print("unit test scan_box...\n");
{
int xmin = -1, ymin = -1, xmax = -1, ymax = -1;
OIIO_CHECK_ASSERT(scan_box("11,12,13,14", xmin, ymin, xmax, ymax)
&& xmin == 11 && ymin == 12 && xmax == 13
&& ymax == 14);
OIIO_CHECK_ASSERT(scan_box("1,2,3", xmin, ymin, xmax, ymax) == false);
OIIO_CHECK_ASSERT(scan_box("1,2,3,4,5", xmin, ymin, xmax, ymax)
== false);
OIIO_CHECK_ASSERT(scan_box("1,2.5,3,4", xmin, ymin, xmax, ymax)
== false);
}
{
float xmin = -1, ymin = -1, xmax = -1, ymax = -1;
OIIO_CHECK_ASSERT(scan_box("11,12,13,14", xmin, ymin, xmax, ymax)
&& xmin == 11 && ymin == 12 && xmax == 13
&& ymax == 14);
OIIO_CHECK_ASSERT(
scan_box("11.5,12.5,13.5,14.5", xmin, ymin, xmax, ymax)
&& xmin == 11.5f && ymin == 12.5f && xmax == 13.5f
&& ymax == 14.5f);
OIIO_CHECK_ASSERT(scan_box("1,2,3", xmin, ymin, xmax, ymax) == false);
OIIO_CHECK_ASSERT(scan_box("1,2,3,4,5", xmin, ymin, xmax, ymax)
== false);
}
}
#endif
// Helper: Remove an optional modifier ":NAME=value" from command string str
static std::string
remove_modifier(string_view str, string_view name)
{
std::string sentinel = Strutil::fmt::format(":{}=", name);
std::string result;
size_t start = str.find(sentinel);
if (start != string_view::npos) {
size_t end = start + sentinel.size();
end = std::min(str.find(":", end), str.size());
result = Strutil::concat(str.substr(0, start), str.substr(end));
} else {
result = str;
}
return result;
}
// FIXME -- lots of things we skimped on so far:
// FIXME: reject volume images?
// FIXME: do all ops respect -a (or lack thereof?)
bool
Oiiotool::read(ImageRecRef img, ReadPolicy readpolicy, string_view channel_set)
{
// If the image is already elaborated, take an early out, both to
// save time, but also because we only want to do the format and
// tile adjustments below as images are read in fresh from disk.
if (img->elaborated())
return true;
// Cause the ImageRec to get read. Try to compute how long it took.
// Subtract out ImageCache time, to avoid double-accounting it later.
float pre_ic_time, post_ic_time;
imagecache->getattribute("stat:fileio_time", pre_ic_time);
total_readtime.start();
if (nativeread)
readpolicy = ReadPolicy(readpolicy | ReadNative);
bool ok = img->read(readpolicy, channel_set);
total_readtime.stop();
imagecache->getattribute("stat:fileio_time", post_ic_time);
total_imagecache_readtime += post_ic_time - pre_ic_time;
total_readtime.add_seconds(pre_ic_time - post_ic_time);
// If this is the first tiled image we have come across, use it to
// set our tile size (unless the user explicitly set a tile size, or
// explicitly instructed scanline output).
const ImageSpec& nspec((*img)().nativespec());
if (nspec.tile_width && !output_tilewidth && !output_scanline) {
output_tilewidth = nspec.tile_width;
output_tileheight = nspec.tile_height;
}
// Remember the channel format details of the first example of each
// channel name that we encounter.
remember_input_channelformats(img);
if (!ok)
error("read", format_read_error(img->name(), img->geterror()));
return ok;
}
bool
Oiiotool::read_nativespec(ImageRecRef img)
{
// If the image is already elaborated, take an early out, both to
// save time, but also because we only want to do the format and
// tile adjustments below as images are read in fresh from disk.
if (img->elaborated())
return true;
// Cause the ImageRec to get read. Try to compute how long it took.
// Subtract out ImageCache time, to avoid double-accounting it later.
float pre_ic_time, post_ic_time;
imagecache->getattribute("stat:fileio_time", pre_ic_time);
total_readtime.start();
bool ok = img->read_nativespec();
total_readtime.stop();
imagecache->getattribute("stat:fileio_time", post_ic_time);
total_imagecache_readtime += post_ic_time - pre_ic_time;
if (!ok)
error("read", format_read_error(img->name(), img->geterror()));
return ok;
}
void
Oiiotool::remember_input_channelformats(ImageRecRef img)
{
for (int s = 0, subimages = img->subimages(); s < subimages; ++s) {
const ImageSpec& nspec((*img)(s, 0).nativespec());
// Overall default format is the merged type of all subimages
// of the first input image.
input_dataformat = TypeDesc::basetype_merge(input_dataformat,
nspec.format);
std::string subimagename = nspec.get_string_attribute(
"oiio:subimagename");
if (subimagename.size()) {
// Record a best guess for this subimage, if not already set.
auto key = Strutil::fmt::format("{}.*", subimagename);
if (input_channelformats[key] == "")
input_channelformats[key] = nspec.format.c_str();
}
if (!input_bitspersample)
input_bitspersample = nspec.get_int_attribute("oiio:BitsPerSample");
for (int c = 0; c < nspec.nchannels; ++c) {
// For each channel, if we don't already have a type recorded
// for its name, record it. Both the bare channel name, and also
// "subimagename.channelname", so that we can remember the same
// name differently for different subimages.
std::string chname = nspec.channel_name(c);
std::string chtypename = nspec.channelformat(c).c_str();
if (subimagename.size()) {
std::string subchname
= Strutil::fmt::format("{}.{}", subimagename, chname);
if (input_channelformats[subchname] == "")
input_channelformats[subchname] = chtypename;
} else {
if (input_channelformats[chname] == "")
input_channelformats[chname] = chtypename;
}
}
}
#if 0
std::cout << "Input channel type map:\n";
for (auto& x : input_channelformats)
std::cout << " " << x.first << " -> " << x.second << "\n";
#endif
}
bool
Oiiotool::postpone_callback(int required_images, CallbackFunction func,
cspan<const char*> argv)
{
if (image_stack_depth() < required_images) {
// Not enough have inputs been specified so far, so put this function
// on the "pending" list. Use ustring to turn it into char*'s that
// won't disappear out from under us.
m_pending_callback = func;
m_pending_argv.assign(argv.begin(), argv.end());
for (auto& s : m_pending_argv)
s = ustring(s).c_str();
return true;
}
return false;
}
void
Oiiotool::process_pending()
{
// Process any pending command -- this is a case where the
// command line had prefix 'oiiotool --action file1 file2'
// instead of infix 'oiiotool file1 --action file2'.
if (m_pending_callback) {
std::vector<const char*> argv = std::move(m_pending_argv);
CallbackFunction callback = m_pending_callback;
m_pending_callback = NULL;
(*callback)(*this, argv);
}
}
void
Oiiotool::error(string_view command, string_view explanation) const
{
auto& errstream(nostderr ? std::cout : std::cerr);
errstream << "oiiotool ERROR";
if (command.size())
errstream << ": " << command;
if (explanation.size())
errstream << " : " << explanation;
else
errstream << " (unknown error)";
errstream << "\n";
// Repeat the command line, so if oiiotool is being called from a
// script, it's easy to debug how the command was mangled.
errstream << "Full command line was:\n> " << full_command_line << "\n";
if (!noerrexit) {
// Cease further processing of the command line
const_cast<Oiiotool*>(this)->ap.abort();
const_cast<Oiiotool*>(this)->return_value = EXIT_FAILURE;
}
}
void
Oiiotool::warning(string_view command, string_view explanation) const
{
auto& errstream(nostderr ? std::cout : std::cerr);
errstream << "oiiotool WARNING";
if (command.size())
errstream << ": " << command;
if (explanation.size())
errstream << " : " << explanation;
else
errstream << " (unknown warning)";
errstream << "\n";
}
ParamValueList
Oiiotool::extract_options(string_view command)
{
using namespace Strutil;
ParamValueList optlist;
// Note: the first execution of the loop test will skip over the initial
// section through the first colon (--foo:), and the test will fail and
// end the loop when we've exhausted `command`.
while (parse_until_char(command, ':') && parse_char(command, ':')) {
string_view name = parse_identifier(command);
string_view value;
bool ok = parse_char(command, '=');
if (name.size() && ok) {
if (command.size() && (command[0] == '\'' || command[0] == '\"')) {
// If single or double quoted, the value is the contents
// between the quotes.
ok = parse_string(command, value, true, DeleteQuotes);
} else {
// If not quoted, the value is everything until the next ':'
value = parse_until(command, ":");
}
}
if (ok && name.size() && value.size()) {
// We seem to have a name and value. Add to the optlist.
optlist[name] = value;
}
}
return optlist;
}
// --threads
static void
set_threads(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 2);
if (ot.in_parallel_frame_loop())
return;
int nthreads = Strutil::stoi(argv[1]);
OIIO::attribute("threads", nthreads);
OIIO::attribute("exr_threads", nthreads);
}
// --cache
static void
set_cachesize(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 2);
ot.cachesize = Strutil::stoi(argv[1]);
if (ot.cachesize) {
OIIO::attribute("imagebuf:use_imagecache", 1);
ot.imagecache->attribute("max_memory_MB", float(ot.cachesize));
} else {
OIIO::attribute("imagebuf:use_imagecache", 0);
}
}
// --autotile
static void
set_autotile(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 2);
ot.autotile = Strutil::stoi(argv[1]);
ot.imagecache->attribute("autotile", ot.autotile);
ot.imagecache->attribute("autoscanline", int(ot.autotile ? 1 : 0));
}
// --native
static void
set_native(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 1);
ot.nativeread = true;
ot.imagecache->attribute("forcefloat", 0);
}
// --dumpdata
static void
set_dumpdata(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 1);
string_view command = ot.express(argv[0]);
auto options = ot.extract_options(command);
ot.dumpdata = true;
ot.dumpdata_showempty = options.get_int("empty", 1);
ot.dumpdata_C_name = options.get_string("C");
ot.dumpdata_C = ot.dumpdata_C_name.size();
}
// --info
static void
set_printinfo(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 1);
string_view command = ot.express(argv[0]);
ot.printinfo = true;
auto options = ot.extract_options(command);
ot.printinfo_format = options["format"];
ot.printinfo_verbose = options.get_int("verbose");
}
// --autocc
static void
set_autocc(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 1);
string_view command = ot.express(argv[0]);
auto options = ot.extract_options(command);
ot.autocc = true;
ot.autoccunpremult = options.get_int("unpremult");
}
// --autopremult
static void
set_autopremult(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 1);
ot.autopremult = true;
ot.imagecache->attribute("unassociatedalpha", 0);
ot.input_config.erase_attribute("oiio:UnassociatedAlpha");
}
// --no-autopremult
static void
unset_autopremult(Oiiotool& ot, cspan<const char*> argv)
{
OIIO_DASSERT(argv.size() == 1);
ot.autopremult = false;
ot.imagecache->attribute("unassociatedalpha", 1);
ot.input_config.attribute("oiio:UnassociatedAlpha", 1);
ot.input_config_set = true;
}
// --label
static void
action_label(Oiiotool& ot, cspan<const char*> argv)
{
string_view command = ot.express(argv[0]);
string_view name = ot.express(argv[1]);
if (!Strutil::string_is_identifier(name)) {
ot.errorfmt(command, "Invalid label name \"{}\"", name);
return;
}
ot.image_labels[name] = ot.curimg;
}
static void
string_to_dataformat(const std::string& s, TypeDesc& dataformat, int& bits)
{
struct DataFormat {
const char* name;
TypeDesc format;
int bits;
};
// clang-format off
static DataFormat formats[] = {
{ "uint8", TypeDesc::UINT8, 8 },
{ "int8", TypeDesc::INT8, 8 },
{ "uint10", TypeDesc::UINT16, 10 },
{ "uint12", TypeDesc::UINT16, 12 },
{ "uint16", TypeDesc::UINT16, 16 },
{ "int16", TypeDesc::INT16, 16 },
{ "uint32", TypeDesc::UINT32, 32 },
{ "int32", TypeDesc::INT32, 32 },
{ "half", TypeDesc::HALF, 16 },
{ "float", TypeDesc::FLOAT, 32 },
{ "double", TypeDesc::DOUBLE, 64 },
{ "uint6", TypeDesc::UINT8, 6 },
{ "uint4", TypeDesc::UINT8, 4 },
{ "uint2", TypeDesc::UINT8, 2 },
{ "uint1", TypeDesc::UINT8, 1 },
};
// clang-format on
for (auto& f : formats) {
if (s == f.name) {
dataformat = f.format;
bits = f.bits;
return;
}
}
dataformat = TypeUnknown;
bits = 0;
}
inline int
get_value_override(string_view localoption, int defaultval = 0)
{
return localoption.size() ? Strutil::from_string<int>(localoption)
: defaultval;
}
inline float
get_value_override(string_view localoption, float defaultval)
{
return localoption.size() ? Strutil::from_string<float>(localoption)
: defaultval;
}
inline string_view
get_value_override(string_view localoption, string_view defaultval)
{
return localoption.size() ? localoption : defaultval;
}
// Given a (potentially empty) overall data format, per-channel formats,
// and bit depth, modify the existing spec.
static void
set_output_dataformat(ImageSpec& spec, TypeDesc format,
std::map<std::string, std::string>& channelformats,
int bitdepth)
{
if (format != TypeUnknown)
spec.format = format;
spec.channelformats.resize(spec.nchannels, spec.format);
if (!channelformats.empty()) {
std::string subimagename = spec["oiio:subimagename"];
for (int c = 0; c < spec.nchannels; ++c) {
std::string chname = spec.channel_name(c);
auto subchname = Strutil::fmt::format("{}.{}", subimagename,
chname);
TypeDesc chtype = spec.channelformat(c);
if (subimagename.size() && channelformats[subchname] != "")
chtype = TypeDesc(channelformats[subchname]);
else if (channelformats[chname] != "")
chtype = TypeDesc(channelformats[chname]);
if (chtype != TypeUnknown)
spec.channelformats[c] = chtype;
}
}
// Eliminate the per-channel formats if they are all the same.
if (spec.channelformats.size()) {
bool allsame = true;
for (auto& c : spec.channelformats)
allsame &= (c == spec.channelformats[0]);
if (allsame) {
spec.format = spec.channelformats[0];
spec.channelformats.clear();
}
}
if (bitdepth)
spec.attribute("oiio:BitsPerSample", bitdepth);
else
spec.erase_attribute("oiio:BitsPerSample");
}
static void
adjust_output_options(string_view filename, ImageSpec& spec,
const ImageSpec* nativespec, const Oiiotool& ot,
bool format_supports_tiles,
const ParamValueList& fileoptions,
bool was_direct_read = false)
{
// What data format and bit depth should we use for the output? Here's
// the logic:
// * If a specific request was made on this command (e.g. -o:format=half)
// or globally (e.g., -d half), honor that, with a per-command request
// taking precedence.
// * Otherwise, If the buffer is more or less a direct copy from an
// input image (as read, not the result of subsequent operations,
// which will tend to generate float output no matter what the
// inputs), write it out in the same format it was read from.
// * Otherwise, output the same type as the FIRST file that was input
// (we are guessing that even if the operations made result buffers
// that were float, the user probably wanted to output it the same
// format as the input, or else she would have said so).
// * Otherwise, just write the buffer's format, regardless of how it got
// that way.
// spec is what we're going to use for output.
// Accumulating results here
TypeDesc requested_output_dataformat;
std::map<std::string, std::string> requested_channelformats;
int requested_output_bits = 0;
if (was_direct_read && nativespec) {
// If the image we're outputting is an unmodified direct read of a
// file, assume that we'll default to outputting the same channel
// formats it started in.
requested_output_dataformat = nativespec->format;
for (int c = 0; c < nativespec->nchannels; ++c) {
requested_channelformats[nativespec->channel_name(c)]
= nativespec->channelformat(c).c_str();
}
requested_output_bits = nativespec->get_int_attribute(
"oiio:BitsPerSample");
} else if (ot.input_dataformat != TypeUnknown) {
// If the image we're outputting is a computed or modified image, not
// a direct read, then assume that the FIRST image we read in provides
// a template for the output we want (if we ever read an image).
requested_output_dataformat = ot.input_dataformat;
requested_channelformats = ot.input_channelformats;
requested_output_bits = ot.input_bitspersample;
}
// Any "global" format requests set by -d override the above.
if (ot.output_dataformat != TypeUnknown) {
// `-d type` clears the board and imposes the request
requested_output_dataformat = ot.output_dataformat;
requested_channelformats.clear();
spec.channelformats.clear();
if (ot.output_bitspersample)
requested_output_bits = ot.output_bitspersample;
}
if (!ot.output_channelformats.empty()) {
// `-d chan=type` overrides the format for a specific channel
for (auto&& c : ot.output_channelformats)
requested_channelformats[c.first] = c.second;
}
// Any override options on the -o command itself take precedence over
// everything else.
if (fileoptions.contains("type")) {
requested_output_dataformat.fromstring(fileoptions.get_string("type"));
requested_channelformats.clear();
spec.channelformats.clear();
} else if (fileoptions.contains("datatype")) {
requested_output_dataformat.fromstring(
fileoptions.get_string("datatype"));
requested_channelformats.clear();
spec.channelformats.clear();
}
requested_output_bits = fileoptions.get_int("bits", requested_output_bits);
// At this point, the trio of "requested" variable reflect any global or
// command requests to override the logic of what was found in the input
// files.
// Set the types in the spec
set_output_dataformat(spec, requested_output_dataformat,
requested_channelformats, requested_output_bits);
// Tiling strategy:
// * If a specific request was made for tiled or scanline output, honor
// that (assuming the file format supports it).
// * Otherwise, if the buffer is a direct copy from an input image, try
// to write it with the same tile/scanline choices as the input (if
// the file format supports it).
// * Otherwise, just default to scanline.
int requested_tilewidth = ot.output_tilewidth;
int requested_tileheight = ot.output_tileheight;
std::string tilesize = fileoptions["tile"];
if (tilesize.size()) {
int x, y; // dummy vals for adjust_geometry
ot.adjust_geometry("-o", requested_tilewidth, requested_tileheight, x,
y, tilesize.c_str(), false);
}
bool requested_scanline = fileoptions.get_int("scanline",
ot.output_scanline);
if (requested_tilewidth && !requested_scanline && format_supports_tiles) {
// Explicit request to tile, honor it.
spec.tile_width = requested_tilewidth;
spec.tile_height = requested_tileheight ? requested_tileheight
: requested_tilewidth;
spec.tile_depth = 1; // FIXME if we ever want volume support
} else if (was_direct_read && nativespec && nativespec->tile_width > 0
&& nativespec->tile_height > 0 && !requested_scanline
&& format_supports_tiles) {
// No explicit request, but a direct read of a tiled input: keep the
// input tiling.
spec.tile_width = nativespec->tile_width;
spec.tile_height = nativespec->tile_height;
spec.tile_depth = nativespec->tile_depth;
} else {
// Otherwise, be safe and force scanline output.
spec.tile_width = spec.tile_height = spec.tile_depth = 0;
}
if (!ot.output_compression.empty()) {
// Note: may be in the form "name:quality"
spec.attribute("compression", ot.output_compression);
}
if (ot.output_quality > 0)
spec.attribute("CompressionQuality", ot.output_quality);
if (fileoptions.get_int("separate"))
spec.attribute("planarconfig", "separate");
else if (fileoptions.get_int("contig"))
spec.attribute("planarconfig", "contig");
else if (ot.output_planarconfig == "contig"
|| ot.output_planarconfig == "separate")
spec.attribute("planarconfig", ot.output_planarconfig);