This file is indexed.

/usr/include/OpenImageIO/imageio.h is in libopenimageio-dev 1.3.12~dfsg0-1ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
/*
  Copyright 2008 Larry Gritz and the other authors and contributors.
  All Rights Reserved.
  Based on BSD-licensed software Copyright 2004 NVIDIA Corp.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  * Neither the name of the software's owners nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.
  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

  (This is the Modified BSD License)
*/


/////////////////////////////////////////////////////////////////////////////
/// \file
///
/// Provides a simple API that abstracts the reading and writing of
/// images.  Subclasses, which may be found in DSO/DLL's, implement
/// particular formats.
///
/////////////////////////////////////////////////////////////////////////////


#ifndef OPENIMAGEIO_IMAGEIO_H
#define OPENIMAGEIO_IMAGEIO_H

#if defined(_MSC_VER)
// Ignore warnings about DLL exported classes with member variables that are template classes.
// This happens with the std::vector<T> and std::string members of the classes below.
#  pragma warning (disable : 4251)
#endif

#include <vector>
#include <string>
#include <limits>
#include <cmath>

#include "export.h"
#include "typedesc.h"   /* Needed for TypeDesc definition */
#include "paramlist.h"
#include "version.h"

OIIO_NAMESPACE_ENTER
{

/// Type we use for stride lengths.  This is only used to designate
/// pixel, scanline, tile, or image plane sizes in user-allocated memory,
/// so it doesn't need to represent sizes larger than can be malloced,
/// therefore ptrdiff_t seemed right.
typedef ptrdiff_t stride_t;


/// Type we use to express how many pixels (or bytes) constitute an image,
/// tile, or scanline.  Needs to be large enough to handle very big images
/// (which we presume could be > 4GB).
#if defined(LINUX64) || defined(_WIN64) /* add others if we know for sure size_t is ok */
typedef size_t imagesize_t;
#else
typedef unsigned long long imagesize_t;
#endif



/// Special value to indicate a stride length that should be
/// auto-computed.
const stride_t AutoStride = std::numeric_limits<stride_t>::min();



/// Pointer to a function called periodically by read_image and
/// write_image.  This can be used to implement progress feedback, etc.
/// It takes an opaque data pointer (passed to read_image/write_image)
/// and a float giving the portion of work done so far.  It returns a
/// bool, which if 'true' will STOP the read or write.
typedef bool (*ProgressCallback)(void *opaque_data, float portion_done);



typedef ParamValue ImageIOParameter;
typedef ParamValueList ImageIOParameterList;



/// ImageSpec describes the data format of an image --
/// dimensions, layout, number and meanings of image channels.
class OIIO_API ImageSpec {
public:
    int x, y, z;              ///< origin (upper left corner) of pixel data
    int width;                ///< width of the pixel data window
    int height;               ///< height of the pixel data window
    int depth;                ///< depth of pixel data, >1 indicates a "volume"
    int full_x;               ///< origin of the full (display) window
    int full_y;               ///< origin of the full (display) window
    int full_z;               ///< origin of the full (display) window
    int full_width;           ///< width of the full (display) window
    int full_height;          ///< height of the full (display) window
    int full_depth;           ///< depth of the full (display) window
    int tile_width;           ///< tile width (0 for a non-tiled image)
    int tile_height;          ///< tile height (0 for a non-tiled image)
    int tile_depth;           ///< tile depth (0 for a non-tiled image,
                              ///<             1 for a non-volume image)
    int nchannels;            ///< number of image channels, e.g., 4 for RGBA
    TypeDesc format;          ///< data format of the channels
    std::vector<TypeDesc> channelformats;   ///< Optional per-channel formats
    std::vector<std::string> channelnames;  ///< Names for each channel,
                                            ///< e.g., {"R","G","B","A"}
    int alpha_channel;        ///< Index of alpha channel, or -1 if not known
    int z_channel;            ///< Index of depth channel, or -1 if not known
    bool deep;                ///< Contains deep data

    // quantize is used for ImageOutput
    int quant_black;          ///< quantization of black (0.0) level
    int quant_white;          ///< quantization of white (1.0) level
    int quant_min;            ///< quantization minimum clamp value
    int quant_max;            ///< quantization maximum clamp value

    /// The above contains all the information that is likely needed for
    /// every image file, and common to all formats.  Rather than bloat
    /// this structure, customize it for new formats, or break back
    /// compatibility as we think of new things, we provide extra_attribs
    /// as a holder for any other properties of the image.  The public
    /// functions attribute and find_attribute may be used to access
    /// these data.  Note, however, that the names and semantics of such
    /// extra attributes are plugin-dependent and are not enforced by
    /// the imageio library itself.
    ImageIOParameterList extra_attribs;  ///< Additional attributes

    /// Constructor: given just the data format, set the default quantize
    /// and set all other channels to something reasonable.
    ImageSpec (TypeDesc format = TypeDesc::UNKNOWN);

    /// Constructor for simple 2D scanline image with nothing special.
    /// If fmt is not supplied, default to unsigned 8-bit data.
    ImageSpec (int xres, int yres, int nchans, TypeDesc fmt = TypeDesc::UINT8);

    /// Set the data format, and as a side effect set quantize
    /// to good defaults for that format
    void set_format (TypeDesc fmt);

    /// Set the channelnames to reasonable defaults ("R", "G", "B", "A"),
    /// and alpha_channel, based on the number of channels.
    void default_channel_names ();

    /// Given quantization parameters, deduce a TypeDesc that can
    /// be used without unacceptable loss of significant bits.
    static TypeDesc format_from_quantize (int quant_black, int quant_white,
                                          int quant_min, int quant_max);

    /// Return the number of bytes for each channel datum, assuming they
    /// are all stored using the data format given by this->format.
    size_t channel_bytes() const { return format.size(); }

    /// Return the number of bytes needed for the single specified
    /// channel.  If native is false (default), compute the size of one
    /// channel of this->format, but if native is true, compute the size
    /// of the channel in terms of the "native" data format of that
    /// channel as stored in the file.
    size_t channel_bytes (int chan, bool native=false) const;

    /// Return the number of bytes for each pixel (counting all channels).
    /// If native is false (default), assume all channels are in 
    /// this->format, but if native is true, compute the size of a pixel
    /// in the "native" data format of the file (these may differ in
    /// the case of per-channel formats).
    /// This will return std::numeric_limits<size_t>::max() in the
    /// event of an overflow where it's not representable in a size_t.
    size_t pixel_bytes (bool native=false) const;

    /// Return the number of bytes for just the subset of channels in
    /// each pixel described by [chbegin,chend).
    /// If native is false (default), assume all channels are in 
    /// this->format, but if native is true, compute the size of a pixel
    /// in the "native" data format of the file (these may differ in
    /// the case of per-channel formats).
    /// This will return std::numeric_limits<size_t>::max() in the
    /// event of an overflow where it's not representable in a size_t.
    size_t pixel_bytes (int chbegin, int chend, bool native=false) const;

    /// Return the number of bytes for each scanline.  This will return
    /// std::numeric_limits<imagesize_t>::max() in the event of an
    /// overflow where it's not representable in an imagesize_t.
    /// If native is false (default), assume all channels are in 
    /// this->format, but if native is true, compute the size of a pixel
    /// in the "native" data format of the file (these may differ in
    /// the case of per-channel formats).
    imagesize_t scanline_bytes (bool native=false) const;

    /// Return the number of pixels for a tile.  This will return
    /// std::numeric_limits<imagesize_t>::max() in the event of an
    /// overflow where it's not representable in an imagesize_t.
    imagesize_t tile_pixels () const;

    /// Return the number of bytes for each a tile of the image.  This
    /// will return std::numeric_limits<imagesize_t>::max() in the event
    /// of an overflow where it's not representable in an imagesize_t.
    /// If native is false (default), assume all channels are in 
    /// this->format, but if native is true, compute the size of a pixel
    /// in the "native" data format of the file (these may differ in
    /// the case of per-channel formats).
    imagesize_t tile_bytes (bool native=false) const;

    /// Return the number of pixels for an entire image.  This will
    /// return std::numeric_limits<imagesize_t>::max() in the event of
    /// an overflow where it's not representable in an imagesize_t.
    imagesize_t image_pixels () const;

    /// Return the number of bytes for an entire image.  This will
    /// return std::numeric_limits<image size_t>::max() in the event of
    /// an overflow where it's not representable in an imagesize_t.
    /// If native is false (default), assume all channels are in 
    /// this->format, but if native is true, compute the size of a pixel
    /// in the "native" data format of the file (these may differ in
    /// the case of per-channel formats).
    imagesize_t image_bytes (bool native=false) const;

    /// Verify that on this platform, a size_t is big enough to hold the
    /// number of bytes (and pixels) in a scanline, a tile, and the
    /// whole image.  If this returns false, the image is much too big
    /// to allocate and read all at once, so client apps beware and check
    /// these routines for overflows!
    bool size_t_safe() const {
        const imagesize_t big = std::numeric_limits<size_t>::max();
        return image_bytes() < big && scanline_bytes() < big &&
            tile_bytes() < big;
    }

    /// Adjust the stride values, if set to AutoStride, to be the right
    /// sizes for contiguous data with the given format, channels,
    /// width, height.
    static void auto_stride (stride_t &xstride, stride_t &ystride,
                             stride_t &zstride, stride_t channelsize,
                             int nchannels, int width, int height) {
        if (xstride == AutoStride)
            xstride = nchannels * channelsize;
        if (ystride == AutoStride)
            ystride = xstride * width;
        if (zstride == AutoStride)
            zstride = ystride * height;
    }

    /// Adjust the stride values, if set to AutoStride, to be the right
    /// sizes for contiguous data with the given format, channels,
    /// width, height.
    static void auto_stride (stride_t &xstride, stride_t &ystride,
                             stride_t &zstride, TypeDesc format,
                             int nchannels, int width, int height) {
        auto_stride (xstride, ystride, zstride, format.size(),
                     nchannels, width, height);
    }

    /// Adjust xstride, if set to AutoStride, to be the right size for
    /// contiguous data with the given format and channels.
    static void auto_stride (stride_t &xstride, TypeDesc format, int nchannels) {
        if (xstride == AutoStride)
            xstride = nchannels * format.size();
    }

    /// Add an optional attribute to the extra attribute list
    ///
    void attribute (const std::string &name, TypeDesc type, const void *value);

    /// Add an optional attribute to the extra attribute list.
    ///
    void attribute (const std::string &name, TypeDesc type, const std::string &value);

    /// Add an unsigned int attribute
    ///
    void attribute (const std::string &name, unsigned int value) {
        attribute (name, TypeDesc::UINT, &value);
    }

    /// Add an int attribute
    ///
    void attribute (const std::string &name, int value) {
        attribute (name, TypeDesc::INT, &value);
    }

    /// Add a float attribute
    ///
    void attribute (const std::string &name, float value) {
        attribute (name, TypeDesc::FLOAT, &value);
    }

    /// Add a string attribute
    ///
    void attribute (const std::string &name, const char *value) {
        attribute (name, TypeDesc::STRING, &value);
    }

    /// Add a string attribute
    ///
    void attribute (const std::string &name, const std::string &value) {
        attribute (name, value.c_str());
    }

    /// Remove the specified attribute from the list of extra
    /// attributes. If not found, do nothing.
    void erase_attribute (const std::string &name,
                          TypeDesc searchtype=TypeDesc::UNKNOWN,
                          bool casesensitive=false);

    /// Search for a attribute of the given name in the list of extra
    /// attributes.
    ImageIOParameter * find_attribute (const std::string &name,
                                       TypeDesc searchtype=TypeDesc::UNKNOWN,
                                       bool casesensitive=false);
    const ImageIOParameter *find_attribute (const std::string &name,
                                            TypeDesc searchtype=TypeDesc::UNKNOWN,
                                            bool casesensitive=false) const;

    /// Simple way to get an integer attribute, with default provided.
    /// Automatically will return an int even if the data is really
    /// unsigned, short, or byte.
    int get_int_attribute (const std::string &name, int defaultval=0) const;

    /// Simple way to get a float attribute, with default provided.
    /// Automatically will return a float even if the data is really
    /// double or half.
    float get_float_attribute (const std::string &name,
                               float defaultval=0) const;

    /// Simple way to get a string attribute, with default provided.
    ///
    std::string get_string_attribute (const std::string &name,
                          const std::string &defaultval = std::string()) const;

    /// For a given parameter (in this ImageSpec's extra_attribs),
    /// format the value nicely as a string.  If 'human' is true, use
    /// especially human-readable explanations (units, or decoding of
    /// values) for certain known metadata.
    std::string metadata_val (const ImageIOParameter &p,
                              bool human=false) const;

    /// Convert ImageSpec class into XML string.
    ///
    std::string to_xml () const;

    /// Get an ImageSpec class from XML string.
    ///
    void from_xml (const char *xml);

    /// Helper function to verify that the given pixel range exactly covers
    /// a set of tiles.  Also returns false if the spec indicates that the
    /// image isn't tiled at all.
    bool valid_tile_range (int xbegin, int xend, int ybegin, int yend,
                           int zbegin, int zend) {
        return (tile_width &&
                ((xbegin-x) % tile_width)  == 0 &&
                ((ybegin-y) % tile_height) == 0 &&
                ((zbegin-z) % tile_depth)  == 0 &&
                (((xend-x) % tile_width)  == 0 || (xend-x) == width) &&
                (((yend-y) % tile_height) == 0 || (yend-y) == height) &&
                (((zend-z) % tile_depth)  == 0 || (zend-z) == depth));
    }

    /// Return teh channelformat of the given channel.
    TypeDesc channelformat (int chan) const {
        return chan >= (int)channelformats.size() ? format : channelformats[chan];
    }

    /// Fill in an array of channel formats describing all channels in
    /// the image.  (Note that this differs slightly from the member
    /// data channelformats, which is empty if there are not separate
    /// per-channel formats.)
    void get_channelformats (std::vector<TypeDesc> &formats) const {
        formats = channelformats;
        if ((int)formats.size() < nchannels)
            formats.resize (nchannels, format);
    }
};



/// Structure to hold "deep" data -- multiple samples per pixel.
struct OIIO_API DeepData {
public:
    int npixels, nchannels;
    std::vector<TypeDesc> channeltypes;  // for each channel [c]
    std::vector<unsigned int> nsamples;// for each pixel [z][y][x]
    std::vector<void *> pointers;    // for each channel per pixel [z][y][x][c]
    std::vector<char> data;          // for each sample [z][y][x][c][s]

    DeepData () : npixels(0), nchannels(0) { }
    /// Initialize size and allocate nsamples, pointers
    void init (int npix, int nchan,
               const TypeDesc *chbegin, const TypeDesc *chend);
    /// After nsamples[] has been filled in, allocate enough scratch space
    /// for data and set up all the pointers.
    void alloc ();
    /// Clear the vectors and reset size to 0.
    void clear ();
    /// Deallocate all space in the vectors
    void free ();
};



/// ImageInput abstracts the reading of an image file in a file
/// format-agnostic manner.
class OIIO_API ImageInput {
public:
    /// Create an ImageInput subclass instance that is able to read
    /// the given file and open it, returning the opened ImageInput if
    /// successful.  If it fails, return NULL and set an error that can
    /// be retrieved by OpenImageIO::geterror().
    ///
    /// The 'config', if not NULL, points to an ImageSpec giving
    /// requests or special instructions.  ImageInput implementations
    /// are free to not respond to any such requests, so the default
    /// implementation is just to ignore config.
    ///
    /// open() will first try to make an ImageInput corresponding to
    /// the format implied by the file extension (for example, "foo.tif"
    /// will try the TIFF plugin), but if one is not found or if the
    /// inferred one does not open the file, every known ImageInput type
    /// will be tried until one is found that will open the file.
    static ImageInput *open (const std::string &filename,
                             const ImageSpec *config = NULL);

    /// Create and return an ImageInput implementation that is willing
    /// to read the given file.  The plugin_searchpath parameter is a
    /// colon-separated list of directories to search for ImageIO plugin
    /// DSO/DLL's (not a searchpath for the image itself!).  This will
    /// actually just try every imageio plugin it can locate, until it
    /// finds one that's able to open the file without error.  This just
    /// creates the ImageInput, it does not open the file.
    ///
    /// If the caller intends to immediately open the file, then it is
    /// simpler to call static ImageInput::open().
    static ImageInput *create (const std::string &filename,
                               const std::string &plugin_searchpath="");

    ImageInput () { }
    virtual ~ImageInput () { }

    /// Return the name of the format implemented by this class.
    ///
    virtual const char *format_name (void) const = 0;

    /// Return true if the named file is file of the type for this
    /// ImageInput.  The implementation will try to determine this as
    /// efficiently as possible, in most cases much less expensively
    /// than doing a full open().  Note that a file can appear to be of
    /// the right type (i.e., valid_file() returning true) but still
    /// fail a subsequent call to open(), such as if the contents of the
    /// file are truncated, nonsensical, or otherwise corrupted.
    virtual bool valid_file (const std::string &filename) const;

    /// Open file with given name.  Various file attributes are put in
    /// newspec and a copy is also saved in this->spec.  From these
    /// attributes, you can discern the resolution, if it's tiled,
    /// number of channels, and native data format.  Return true if the
    /// file was found and opened okay.
    virtual bool open (const std::string &name, ImageSpec &newspec) = 0;

    /// Open file with given name, similar to open(name,newspec). The
    /// 'config' is an ImageSpec giving requests or special
    /// instructions.  ImageInput implementations are free to not
    /// respond to any such requests, so the default implementation is
    /// just to ignore config and call regular open(name,newspec).
    virtual bool open (const std::string &name, ImageSpec &newspec,
                       const ImageSpec & /*config*/) { return open(name,newspec); }

    /// Return a reference to the image format specification of the
    /// current subimage/MIPlevel.  Note that the contents of the spec
    /// are invalid before open() or after close(), and may change with
    /// a call to seek_subimage().
    const ImageSpec &spec (void) const { return m_spec; }

    /// Given the name of a 'feature', return whether this ImageInput
    /// supports input of images with the given properties.
    /// Feature names that ImageIO plugins are expected to recognize
    /// include:
    ///    none at this time
    ///
    /// Note that main advantage of this approach, versus having
    /// separate individual supports_foo() methods, is that this allows
    /// future expansion of the set of possible queries without changing
    /// the API, adding new entry points, or breaking linkage
    /// compatibility.
    virtual bool supports (const std::string & /*feature*/) const { return false; }

    /// Close an image that we are totally done with.
    ///
    virtual bool close () = 0;

    /// Returns the index of the subimage that is currently being read.
    /// The first subimage (or the only subimage, if there is just one)
    /// is number 0.
    virtual int current_subimage (void) const { return 0; }

    /// Returns the index of the MIPmap image that is currently being read.
    /// The highest-res MIP level (or the only level, if there is just
    /// one) is number 0.
    virtual int current_miplevel (void) const { return 0; }

    /// Seek to the given subimage and MIP-map level within the open
    /// image file.  The first subimage of the file has index 0, the
    /// highest-resolution MIP level has index 0.  Return true on
    /// success, false on failure (including that there is not a
    /// subimage or MIP level with the specified index).  The new
    /// subimage's vital statistics are put in newspec (and also saved
    /// in this->spec).  The reader is expected to give the appearance
    /// of random access to subimages and MIP levels -- in other words,
    /// if it can't randomly seek to the given subimage/level, it should
    /// transparently close, reopen, and sequentially read through prior
    /// subimages and levels.
    virtual bool seek_subimage (int subimage, int miplevel,
                                ImageSpec &newspec) {
        if (subimage == current_subimage() && miplevel == current_miplevel()) {
            newspec = spec();
            return true;
        }
        return false;
    }

    /// Seek to the given subimage -- backwards-compatible call that
    /// doesn't worry about MIP-map levels at all.
    bool seek_subimage (int subimage, ImageSpec &newspec) {
        return seek_subimage (subimage, 0 /* miplevel */, newspec);
    }

    /// Read the scanline that includes pixels (*,y,z) into data,
    /// converting if necessary from the native data format of the file
    /// into the 'format' specified (z==0 for non-volume images).  The
    /// stride value gives the data spacing of adjacent pixels (in
    /// bytes).  Strides set to AutoStride imply 'contiguous' data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    /// If format is TypeDesc::UNKNOWN, then rather than converting to
    /// format, it will just copy pixels in the file's native data layout
    /// (including, possibly, per-channel data formats).
    /// The reader is expected to give the appearance of random access --
    /// in other words, if it can't randomly seek to the given scanline,
    /// it should transparently close, reopen, and sequentially read
    /// through prior scanlines.  The base ImageInput class has a
    /// default implementation that calls read_native_scanline and then
    /// does appropriate format conversion, so there's no reason for
    /// each format plugin to override this method.
    virtual bool read_scanline (int y, int z, TypeDesc format, void *data,
                                stride_t xstride=AutoStride);

    ///
    /// Simple read_scanline reads to contiguous float pixels.
    bool read_scanline (int y, int z, float *data) {
        return read_scanline (y, z, TypeDesc::FLOAT, data);
    }

    /// Read multiple scanlines that include pixels (*,y,z) for all
    /// ybegin <= y < yend, into data, using the strides given and
    /// converting to the requested data format (unless format is
    /// TypeDesc::UNKNOWN, in which case pixels will be copied in the
    /// native data layout, including per-channel data formats).  This
    /// is analogous to read_scanline except that it may be used to read
    /// more than one scanline at a time (which, for some formats, may
    /// be able to be done much more efficiently or in parallel).
    virtual bool read_scanlines (int ybegin, int yend, int z,
                                 TypeDesc format, void *data,
                                 stride_t xstride=AutoStride,
                                 stride_t ystride=AutoStride);

    /// Read multiple scanlines that include pixels (*,y,z) for all
    /// ybegin <= y < yend, into data, using the strides given and
    /// converting to the requested data format (unless format is
    /// TypeDesc::UNKNOWN, in which case pixels will be copied in the
    /// native data layout, including per-channel data formats).  Only
    /// channels [chbegin,chend) will be read/copied (chbegin=0,
    /// chend=spec.nchannels reads all channels, yielding equivalent
    /// behavior to the simpler variant of read_scanlines).
    virtual bool read_scanlines (int ybegin, int yend, int z,
                                 int chbegin, int chend,
                                 TypeDesc format, void *data,
                                 stride_t xstride=AutoStride,
                                 stride_t ystride=AutoStride);

    /// Read the tile whose upper-left origin is (x,y,z) into data,
    /// converting if necessary from the native data format of the file
    /// into the 'format' specified.  (z==0 for non-volume images.)  The
    /// stride values give the data spacing of adjacent pixels,
    /// scanlines, and volumetric slices (measured in bytes).  Strides
    /// set to AutoStride imply 'contiguous' data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    ///     ystride == xstride*spec.tile_width
    ///     zstride == ystride*spec.tile_height
    /// If format is TypeDesc::UNKNOWN, then rather than converting to
    /// format, it will just copy pixels in the file's native data layout
    /// (including, possibly, per-channel data formats).
    /// The reader is expected to give the appearance of random access
    /// -- in other words, if it can't randomly seek to the given tile,
    /// it should transparently close, reopen, and sequentially read
    /// through prior tiles.  The base ImageInput class has a default
    /// implementation that calls read_native_tile and then does
    /// appropriate format conversion, so there's no reason for each
    /// format plugin to override this method.
    virtual bool read_tile (int x, int y, int z, TypeDesc format,
                            void *data, stride_t xstride=AutoStride,
                            stride_t ystride=AutoStride,
                            stride_t zstride=AutoStride);

    ///
    /// Simple read_tile reads to contiguous float pixels.
    bool read_tile (int x, int y, int z, float *data) {
        return read_tile (x, y, z, TypeDesc::FLOAT, data,
                          AutoStride, AutoStride, AutoStride);
    }

    /// Read the block of multiple tiles that include all pixels in
    /// [xbegin,xend) X [ybegin,yend) X [zbegin,zend), into data, using
    /// the strides given and converting to the requested data format
    /// (unless format is TypeDesc::UNKNOWN, in which case pixels will
    /// be copied in the native data layout, including per-channel data
    /// formats).  This is analogous to read_tile except that it may be
    /// used to read more than one tile at a time (which, for some
    /// formats, may be able to be done much more efficiently or in
    /// parallel).  The begin/end pairs must correctly delineate tile
    /// boundaries, with the exception that it may also be the end of
    /// the image data if the image resolution is not a whole multiple
    /// of the tile size.
    virtual bool read_tiles (int xbegin, int xend, int ybegin, int yend,
                             int zbegin, int zend, TypeDesc format,
                             void *data, stride_t xstride=AutoStride,
                             stride_t ystride=AutoStride,
                             stride_t zstride=AutoStride);

    /// Read the block of multiple tiles that include all pixels in
    /// [xbegin,xend) X [ybegin,yend) X [zbegin,zend), into data, using
    /// the strides given and converting to the requested data format
    /// (unless format is TypeDesc::UNKNOWN, in which case pixels will
    /// be copied in the native data layout, including per-channel data
    /// formats).  Only channels [chbegin,chend) will be read/copied
    /// (chbegin=0, chend=spec.nchannels reads all channels, yielding
    /// equivalent behavior to the simpler variant of read_tiles).
    virtual bool read_tiles (int xbegin, int xend, int ybegin, int yend,
                             int zbegin, int zend, 
                             int chbegin, int chend, TypeDesc format,
                             void *data, stride_t xstride=AutoStride,
                             stride_t ystride=AutoStride,
                             stride_t zstride=AutoStride);

    /// Read the entire image of spec.width x spec.height x spec.depth
    /// pixels into data (which must already be sized large enough for
    /// the entire image) with the given strides and in the desired
    /// format.  Read tiles or scanlines automatically.  Strides set to
    /// AutoStride imply 'contiguous' data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    ///     ystride == xstride*spec.width
    ///     zstride == ystride*spec.height
    /// If format is TypeDesc::UNKNOWN, then rather than converting to
    /// format, it will just copy pixels in the file's native data layout
    /// (including, possibly, per-channel data formats).
    /// Because this may be an expensive operation, a progress callback
    /// may be passed.  Periodically, it will be called as follows:
    ///     progress_callback (progress_callback_data, float done)
    /// where 'done' gives the portion of the image
    virtual bool read_image (TypeDesc format, void *data,
                             stride_t xstride=AutoStride,
                             stride_t ystride=AutoStride,
                             stride_t zstride=AutoStride,
                             ProgressCallback progress_callback=NULL,
                             void *progress_callback_data=NULL);

    ///
    /// Simple read_image reads to contiguous float pixels.
    bool read_image (float *data) {
        return read_image (TypeDesc::FLOAT, data);
    }


    /// read_native_scanline is just like read_scanline, except that it
    /// keeps the data in the native format of the disk file and always
    /// reads into contiguous memory (no strides).  It's up to the user to
    /// have enough space allocated and know what to do with the data.
    /// IT IS EXPECTED THAT EACH FORMAT PLUGIN WILL OVERRIDE THIS METHOD.
    virtual bool read_native_scanline (int y, int z, void *data) = 0;

    /// read_native_scanlines is just like read_scanlines, except that
    /// it keeps the data in the native format of the disk file and
    /// always reads into contiguous memory (no strides).  It's up to
    /// the user to have enough space allocated and know what to do with
    /// the data.  If a format reader subclass does not override this
    /// method, the default implementation it will simply be a loop
    /// calling read_native_scanline for each scanline.
    virtual bool read_native_scanlines (int ybegin, int yend, int z,
                                        void *data);

    /// A variant of read_native_scanlines that reads only channels
    /// [chbegin,chend).  If a format reader subclass does
    /// not override this method, the default implementation will simply
    /// call the all-channel version of read_native_scanlines into a
    /// temporary buffer and copy the subset of channels.
    virtual bool read_native_scanlines (int ybegin, int yend, int z,
                                        int chbegin, int chend, void *data);

    /// read_native_tile is just like read_tile, except that it
    /// keeps the data in the native format of the disk file and always
    /// read into contiguous memory (no strides).  It's up to the user to
    /// have enough space allocated and know what to do with the data.
    /// IT IS EXPECTED THAT EACH FORMAT PLUGIN WILL OVERRIDE THIS METHOD
    /// IF IT SUPPORTS TILED IMAGES.
    virtual bool read_native_tile (int x, int y, int z, void *data);

    /// read_native_tiles is just like read_tiles, except that it keeps
    /// the data in the native format of the disk file and always reads
    /// into contiguous memory (no strides).  It's up to the caller to
    /// have enough space allocated and know what to do with the data.
    /// If a format reader does not override this method, the default
    /// implementation it will simply be a loop calling read_native_tile
    /// for each tile in the block.
    virtual bool read_native_tiles (int xbegin, int xend, int ybegin, int yend,
                                    int zbegin, int zend, void *data);

    /// A variant of read_native_tiles that reads only channels
    /// [chbegin,chend).  If a format reader subclass does
    /// not override this method, the default implementation will simply
    /// call the all-channel version of read_native_tiles into a
    /// temporary buffer and copy the subset of channels.
    virtual bool read_native_tiles (int xbegin, int xend, int ybegin, int yend,
                                    int zbegin, int zend,
                                    int chbegin, int chend, void *data);

    /// Read native deep data from multiple scanlines that include
    /// pixels (*,y,z) for all ybegin <= y < yend, into deepdata.  Only
    /// channels [chbegin, chend) will be read (chbegin=0,
    /// chend=spec.nchannels reads all channels).
    virtual bool read_native_deep_scanlines (int ybegin, int yend, int z,
                                             int chbegin, int chend,
                                             DeepData &deepdata);

    /// Read the block of multiple native deep data tiles that include
    /// all pixels in [xbegin,xend) X [ybegin,yend) X [zbegin,zend),
    /// into deepdata.  Only channels [chbegin,chend) will
    /// be read (chbegin=0, chend=spec.nchannels reads all channels).
    virtual bool read_native_deep_tiles (int xbegin, int xend,
                                         int ybegin, int yend,
                                         int zbegin, int zend,
                                         int chbegin, int chend,
                                         DeepData &deepdata);

    /// Read the entire deep data image of spec.width x spec.height x
    /// spec.depth pixels, all channels, into deepdata.
    virtual bool read_native_deep_image (DeepData &deepdata);


    /// General message passing between client and image input server
    ///
    virtual int send_to_input (const char *format, ...);
    int send_to_client (const char *format, ...);

    /// If any of the API routines returned false indicating an error,
    /// this routine will return the error string (and clear any error
    /// flags).  If no error has occurred since the last time geterror()
    /// was called, it will return an empty string.
    std::string geterror () const {
        std::string e = m_errmessage;
        m_errmessage.clear ();
        return e;
    }

    /// An ImageInput::Creator is a function that creates and returns an
    /// ImageInput.  Once invoked, the resulting ImageInput is owned by
    /// the caller, who is responsible for deleting it when done with it.
    typedef ImageInput* (*Creator)();

protected:
    /// Error reporting for the plugin implementation: call this with
    /// printf-like arguments.  Note however that this is fully typesafe!
    // void error (const char *format, ...) const;
    TINYFORMAT_WRAP_FORMAT (void, error, const,
        std::ostringstream msg;, msg, append_error(msg.str());)

protected:
    ImageSpec m_spec;  // format spec of the current open subimage/MIPlevel

private:
    mutable std::string m_errmessage;  // private storage of error message
    void append_error (const std::string& message) const; // add to m_errmessage
    static ImageInput *create (const std::string &filename, bool do_open,
                               const std::string &plugin_searchpath);

};




/// ImageOutput abstracts the writing of an image file in a file
/// format-agnostic manner.
class OIIO_API ImageOutput {
public:
    /// Create an ImageOutput that will write to a file, with the format
    /// inferred from the extension of the name.  The plugin_searchpath
    /// parameter is a colon-separated list of directories to search for
    /// ImageIO plugin DSO/DLL's.  This just creates the ImageOutput, it
    /// does not open the file.
    static ImageOutput *create (const std::string &filename,
                                const std::string &plugin_searchpath="");

    ImageOutput () { }
    virtual ~ImageOutput () { }

    /// Return the name of the format implemented by this class.
    ///
    virtual const char *format_name (void) const = 0;

    // Overrride these functions in your derived output class
    // to inform the client which formats are supported

    /// Given the name of a 'feature', return whether this ImageOutput
    /// supports output of images with the given properties.
    /// Feature names that ImageIO plugins are expected to recognize
    /// include:
    ///    "tiles"          Is this format able to write tiled images?
    ///    "rectangles"     Does this plugin accept arbitrary rectangular
    ///                       pixel regions, not necessarily aligned to
    ///                       scanlines or tiles?
    ///    "random_access"  May tiles or scanlines be written in
    ///                       any order (false indicates that they MUST
    ///                       be in successive order).
    ///    "multiimage"     Does this format support multiple subimages
    ///                       within a file?
    ///    "appendsubimage" Does this format support adding subimages one at
    ///                       a time through open(name,spec,AppendSubimage)?
    ///                       If not, then open(name,subimages,specs) must
    ///                       be used instead.
    ///    "mipmap"         Does this format support multiple resolutions
    ///                       for an image/subimage?
    ///    "volumes"        Does this format support "3D" pixel arrays?
    ///    "rewrite"        May the same scanline or tile be sent more than
    ///                       once?  (Generally, this will be true for
    ///                       plugins that implement interactive display.)
    ///    "empty"          Does this plugin support passing a NULL data
    ///                       pointer to write_scanline or write_tile to
    ///                       indicate that the entire data block is zero?
    ///    "channelformats" Does the plugin/format support per-channel
    ///                       data formats?
    ///    "displaywindow"  Does the format support display ("full") windows
    ///                        distinct from the pixel data window?
    ///    "origin"         Does the format support a nonzero x,y,z
    ///                        origin of the pixel data window?
    ///    "negativeorigin" Does the format support negative x,y,z
    ///                        and full_{x,y,z} origin values?
    ///    "deepdata"       Deep (multi-sample per pixel) data
    ///
    /// Note that main advantage of this approach, versus having
    /// separate individual supports_foo() methods, is that this allows
    /// future expansion of the set of possible queries without changing
    /// the API, adding new entry points, or breaking linkage
    /// compatibility.
    virtual bool supports (const std::string & /*feature*/) const { return false; }

    enum OpenMode { Create, AppendSubimage, AppendMIPLevel };

    /// Open the file with given name, with resolution and other format
    /// data as given in newspec.  Open returns true for success, false
    /// for failure.  Note that it is legal to call open multiple times
    /// on the same file without a call to close(), if it supports
    /// multiimage and mode is AppendSubimage, or if it supports
    /// MIP-maps and mode is AppendMIPLevel -- this is interpreted as
    /// appending a subimage, or a MIP level to the current subimage,
    /// respectively.
    virtual bool open (const std::string &name, const ImageSpec &newspec,
                       OpenMode mode=Create) = 0;

    /// Open the file with given name, expecting to have a given total
    /// number of subimages, described by specs[0..subimages-1].  
    /// Return true for success, false for failure.  Upon success, the
    /// first subimage will be open and ready for transmission of
    /// pixels.  Subsequent subimages will be denoted with the usual
    /// call of open(name,spec,AppendSubimage) (and MIP levels by
    /// open(name,spec,AppendMIPLevel)).
    ///
    /// The purpose of this call is to accommodate format-writing
    /// libraries that fmust know the number and specifications of the
    /// subimages upon first opening the file; such formats can be
    /// detected by
    ///     supports("multiimage") && !supports("appendsubimage")
    /// The individual specs passed to the appending open() calls for
    /// subsequent subimages MUST match the ones originally passed.
    virtual bool open (const std::string &name, int subimages,
                       const ImageSpec *specs) {
        // Default implementation: just a regular open, assume that
        // appending will work.
        return open (name, specs[0]);
    }

    /// Return a reference to the image format specification of the
    /// current subimage.  Note that the contents of the spec are
    /// invalid before open() or after close().
    const ImageSpec &spec (void) const { return m_spec; }

    /// Close an image that we are totally done with.  This should leave
    /// the plugin in a state where it could open a new file safely,
    /// without having to destroy the writer.
    virtual bool close () = 0;

    /// Write a full scanline that includes pixels (*,y,z).  (z is
    /// ignored for 2D non-volume images.)  The stride value gives the
    /// distance between successive pixels (in bytes).  Strides set to
    /// AutoStride imply 'contiguous' data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    /// The data are automatically converted from 'format' to the actual
    /// output format (as specified to open()) by this method.  
    /// If format is TypeDesc::UNKNOWN, then rather than converting from
    /// format, it will just copy pixels in the file's native data layout
    /// (including, possibly, per-channel data formats).
    /// Return true for success, false for failure.  It is a failure to
    /// call write_scanline with an out-of-order scanline if this format
    /// driver does not support random access.
    virtual bool write_scanline (int y, int z, TypeDesc format,
                                 const void *data, stride_t xstride=AutoStride);

    /// Write multiple scanlines that include pixels (*,y,z) for all
    /// ybegin <= y < yend, from data.  This is analogous to
    /// write_scanline except that it may be used to write more than one
    /// scanline at a time (which, for some formats, may be able to be
    /// done much more efficiently or in parallel).
    virtual bool write_scanlines (int ybegin, int yend, int z,
                                  TypeDesc format, const void *data,
                                  stride_t xstride=AutoStride,
                                  stride_t ystride=AutoStride);

    /// Write the tile with (x,y,z) as the upper left corner.  (z is
    /// ignored for 2D non-volume images.)  The three stride values give
    /// the distance (in bytes) between successive pixels, scanlines,
    /// and volumetric slices, respectively.  Strides set to AutoStride
    /// imply 'contiguous' data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    ///     ystride == xstride*spec.tile_width
    ///     zstride == ystride*spec.tile_height
    /// The data are automatically converted from 'format' to the actual
    /// output format (as specified to open()) by this method.  
    /// If format is TypeDesc::UNKNOWN, then rather than converting from
    /// format, it will just copy pixels in the file's native data layout
    /// (including, possibly, per-channel data formats).
    /// Return true for success, false for failure.  It is a failure to
    /// call write_tile with an out-of-order tile if this format driver
    /// does not support random access.
    virtual bool write_tile (int x, int y, int z, TypeDesc format,
                             const void *data, stride_t xstride=AutoStride,
                             stride_t ystride=AutoStride,
                             stride_t zstride=AutoStride);

    /// Write the block of multiple tiles that include all pixels in
    /// [xbegin,xend) X [ybegin,yend) X [zbegin,zend).  This is
    /// analogous to write_tile except that it may be used to write more
    /// than one tile at a time (which, for some formats, may be able to
    /// be done much more efficiently or in parallel).
    /// The begin/end pairs must correctly delineate tile boundaries,
    /// with the exception that it may also be the end of the image data
    /// if the image resolution is not a whole multiple of the tile size.
    virtual bool write_tiles (int xbegin, int xend, int ybegin, int yend,
                              int zbegin, int zend, TypeDesc format,
                              const void *data, stride_t xstride=AutoStride,
                              stride_t ystride=AutoStride,
                              stride_t zstride=AutoStride);

    /// Write a rectangle of pixels given by the range
    ///   [xbegin,xend) X [ybegin,yend) X [zbegin,zend)
    /// The three stride values give the distance (in bytes) between
    /// successive pixels, scanlines, and volumetric slices,
    /// respectively.  Strides set to AutoStride imply 'contiguous'
    /// data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    ///     ystride == xstride * (xmax-xmin+1)
    ///     zstride == ystride * (ymax-ymin+1)
    /// The data are automatically converted from 'format' to the actual
    /// output format (as specified to open()) by this method.  If
    /// format is TypeDesc::UNKNOWN, it will just copy pixels assuming
    /// they are already in the file's native data layout (including,
    /// possibly, per-channel data formats).
    ///
    /// Return true for success, false for failure.  It is a failure to
    /// call write_rectangle for a format plugin that does not return
    /// true for supports("rectangles").
    virtual bool write_rectangle (int xbegin, int xend, int ybegin, int yend,
                                  int zbegin, int zend, TypeDesc format,
                                  const void *data, stride_t xstride=AutoStride,
                                  stride_t ystride=AutoStride,
                                  stride_t zstride=AutoStride);

    /// Write the entire image of spec.width x spec.height x spec.depth
    /// pixels, with the given strides and in the desired format.
    /// Strides set to AutoStride imply 'contiguous' data, i.e.,
    ///     xstride == spec.nchannels*format.size()
    ///     ystride == xstride*spec.width
    ///     zstride == ystride*spec.height
    /// Depending on spec, write either all tiles or all scanlines.
    /// Assume that data points to a layout in row-major order.
    /// If format is TypeDesc::UNKNOWN, then rather than converting from
    /// format, it will just copy pixels in the file's native data layout
    /// (including, possibly, per-channel data formats).
    /// Because this may be an expensive operation, a progress callback
    /// may be passed.  Periodically, it will be called as follows:
    ///   progress_callback (progress_callback_data, float done)
    /// where 'done' gives the portion of the image
    virtual bool write_image (TypeDesc format, const void *data,
                              stride_t xstride=AutoStride,
                              stride_t ystride=AutoStride,
                              stride_t zstride=AutoStride,
                              ProgressCallback progress_callback=NULL,
                              void *progress_callback_data=NULL);

    /// Write deep scanlines containing pixels (*,y,z), for all y in
    /// [ybegin,yend), to a deep file.
    virtual bool write_deep_scanlines (int ybegin, int yend, int z,
                                       const DeepData &deepdata);

    /// Write the block of deep tiles that include all pixels in
    /// [xbegin,xend) X [ybegin,yend) X [zbegin,zend).  
    /// The begin/end pairs must correctly delineate tile boundaries,
    /// with the exception that it may also be the end of the image data
    /// if the image resolution is not a whole multiple of the tile size.
    virtual bool write_deep_tiles (int xbegin, int xend, int ybegin, int yend,
                                   int zbegin, int zend,
                                   const DeepData &deepdata);

    /// Write the entire deep image denoted by data.
    virtual bool write_deep_image (const DeepData &deepdata);

    /// Read the current subimage of 'in', and write it as the next
    /// subimage of *this, in a way that is efficient and does not alter
    /// pixel values, if at all possible.  Both in and this must be a
    /// properly-opened ImageInput and ImageOutput, respectively, and
    /// their current images must match in size and number of channels.
    /// Return true if it works ok, false if for some reason the
    /// operation wasn't possible.
    ///
    /// If a particular ImageOutput implementation does not supply a
    /// copy_image method, it will inherit the default implementation,
    /// which is to simply read scanlines or tiles from 'in' and write
    /// them to *this.  However, some ImageIO implementations may have a
    /// special technique for directly copying raw pixel data from the
    /// input to the output, when both input and output are the SAME
    /// file type and the same data format.  This can be more efficient
    /// than in->read_image followed by out->write_image, and avoids any
    /// unintended pixel alterations, especially for formats that use
    /// lossy compression.
    virtual bool copy_image (ImageInput *in);

    /// General message passing between client and image output server
    ///
    virtual int send_to_output (const char *format, ...);
    int send_to_client (const char *format, ...);

    /// If any of the API routines returned false indicating an error,
    /// this routine will return the error string (and clear any error
    /// flags).  If no error has occurred since the last time geterror()
    /// was called, it will return an empty string.
    std::string geterror () const {
        std::string e = m_errmessage;
        m_errmessage.clear ();
        return e;
    }

    /// An ImageOutput::Creator is a function that creates and returns an
    /// ImageOutput.  Once invoked, the resulting ImageOutput is owned by
    /// the caller, who is responsible for deleting it when done with it.
    typedef ImageOutput* (*Creator)();

protected:
    /// Error reporting for the plugin implementation: call this with
    /// printf-like arguments.  Note however that this is fully typesafe!
    /// void error (const char *format, ...)
    TINYFORMAT_WRAP_FORMAT (void, error, const,
        std::ostringstream msg;, msg, append_error(msg.str());)

    /// Helper routines used by write_* implementations: convert data (in
    /// the given format and stride) to the "native" format of the file
    /// (described by the 'spec' member variable), in contiguous order.
    /// This requires a scratch space to be passed in so that there are
    /// no memory leaks.  Returns a pointer to the native data, which may
    /// be the original data if it was already in native format and
    /// contiguous, or it may point to the scratch space if it needed to
    /// make a copy or do conversions.
    const void *to_native_scanline (TypeDesc format,
                                    const void *data, stride_t xstride,
                                    std::vector<unsigned char> &scratch);
    const void *to_native_tile (TypeDesc format, const void *data,
                                stride_t xstride, stride_t ystride,
                                stride_t zstride,
                                std::vector<unsigned char> &scratch);
    const void *to_native_rectangle (int xbegin, int xend, int ybegin, int yend,
                                     int zbegin, int zend,
                                     TypeDesc format, const void *data,
                                     stride_t xstride, stride_t ystride,
                                     stride_t zstride,
                                     std::vector<unsigned char> &scratch);

protected:
    ImageSpec m_spec;           ///< format spec of the currently open image

private:
    void append_error (const std::string& message) const; // add to m_errmessage
    mutable std::string m_errmessage;   ///< private storage of error message
};



// Utility functions

/// Retrieve the version of OpenImageIO for the library.  This is so
/// plugins can query to be sure they are linked against an adequate
/// version of the library.
OIIO_API int openimageio_version ();

/// Special geterror() called after ImageInput::create or
/// ImageOutput::create, since if create fails, there's no object on
/// which call obj->geterror().  This function returns the last error
/// for this particular thread; separate threads will not clobber each
/// other's global error messages.
OIIO_API std::string geterror ();

/// Set a global attribute controlling OpenImageIO.  Return true
/// if the name and type were recognized and the attribute was set.
///
/// Documented attributes:
///     int threads
///             How many threads to use for operations that can be sped
///             by spawning threads (default=1; note that 0 means "as
///             many threads as cores").
///     string plugin_searchpath
///             Colon-separated list of directories to search for 
///             dynamically-loaded format plugins.
///     string format_list     (for 'getattribute' only, cannot set)
///             Comma-separated list of all format names supported
///             or for which plugins could be found.
///     string extension_list   (for 'getattribute' only, cannot set)
///             For each format, the format name followed by a colon,
///             followed by comma-separated list of all extensions that
///             are presumed to be used for that format.  Semicolons
///             separate the lists for formats.  For example,
///                "tiff:tif;jpeg:jpg,jpeg;openexr:exr"
OIIO_API bool attribute (const std::string &name, TypeDesc type,
                          const void *val);
// Shortcuts for common types
inline bool attribute (const std::string &name, int val) {
    return attribute (name, TypeDesc::TypeInt, &val);
}
inline bool attribute (const std::string &name, float val) {
    return attribute (name, TypeDesc::TypeFloat, &val);
}
inline bool attribute (const std::string &name, const char *val) {
    return attribute (name, TypeDesc::TypeString, &val);
}
inline bool attribute (const std::string &name, const std::string &val) {
    const char *s = val.c_str();
    return attribute (name, TypeDesc::TypeString, &s);
}

/// Get the named global attribute of OpenImageIO, store it in *val.
/// Return true if found and it was compatible with the type specified,
/// otherwise return false and do not modify the contents of *val.  It
/// is up to the caller to ensure that val points to the right kind and
/// size of storage for the given type.
OIIO_API bool getattribute (const std::string &name, TypeDesc type,
                             void *val);
// Shortcuts for common types
inline bool getattribute (const std::string &name, int &val) {
    return getattribute (name, TypeDesc::TypeInt, &val);
}
inline bool getattribute (const std::string &name, float &val) {
    return getattribute (name, TypeDesc::TypeFloat, &val);
}
inline bool getattribute (const std::string &name, char **val) {
    return getattribute (name, TypeDesc::TypeString, val);
}
inline bool getattribute (const std::string &name, std::string &val) {
    const char *s = NULL;
    bool ok = getattribute (name, TypeDesc::TypeString, &s);
    if (ok)
        val = s ? s : "";
    return ok;
}


/// Register the input and output 'create' routines and list of file
/// extensions for a particular format.
OIIO_API void declare_imageio_format (const std::string &format_name,
                                      ImageInput::Creator input_creator,
                                      const char **input_extensions,
                                      ImageOutput::Creator output_creator,
                                      const char **output_extensions);


/// Helper routine: quantize a value to an integer given the
/// quantization parameters.
OIIO_API int quantize (float value, int quant_black, int quant_white,
                        int quant_min, int quant_max);

/// Helper function: convert contiguous arbitrary data between two
/// arbitrary types (specified by TypeDesc's)
/// Return true if ok, false if it didn't know how to do the
/// conversion.  If dst_type is UNKNWON, it will be assumed to be the
/// same as src_type.
OIIO_API bool convert_types (TypeDesc src_type, const void *src,
                              TypeDesc dst_type, void *dst, int n);

/// DEPRECATED -- for some reason we had a convert_types that took
/// alpha_channel and z_channel parameters, but never did anything
/// with them.
OIIO_API bool convert_types (TypeDesc src_type, const void *src,
                             TypeDesc dst_type, void *dst, int n,
                             int alpha_channel, int z_channel = -1);

/// Helper routine for data conversion: Convert an image of nchannels x
/// width x height x depth from src to dst.  The src and dst may have
/// different data formats and layouts.  Clever use of this function can
/// not only exchange data among different formats (e.g., half to 8-bit
/// unsigned), but also can copy selective channels, copy subimages,
/// etc.  If you're lazy, it's ok to pass AutoStride for any of the
/// stride values, and they will be auto-computed assuming contiguous
/// data.  Return true if ok, false if it didn't know how to do the
/// conversion.
OIIO_API bool convert_image (int nchannels, int width, int height, int depth,
                              const void *src, TypeDesc src_type,
                              stride_t src_xstride, stride_t src_ystride,
                              stride_t src_zstride,
                              void *dst, TypeDesc dst_type,
                              stride_t dst_xstride, stride_t dst_ystride,
                              stride_t dst_zstride,
                              int alpha_channel = -1, int z_channel = -1);

/// A version of convert_image that will break up big jobs into multiple
/// threads.
OIIO_API bool parallel_convert_image (
               int nchannels, int width, int height, int depth,
               const void *src, TypeDesc src_type,
               stride_t src_xstride, stride_t src_ystride,
               stride_t src_zstride,
               void *dst, TypeDesc dst_type,
               stride_t dst_xstride, stride_t dst_ystride,
               stride_t dst_zstride,
               int alpha_channel=-1, int z_channel=-1, int nthreads=0);


/// Helper routine for data conversion: Copy an image of nchannels x
/// width x height x depth from src to dst.  The src and dst may have
/// different data layouts, but must have the same data type.  Clever
/// use of this function can change layouts or strides, copy selective
/// channels, copy subimages, etc.  If you're lazy, it's ok to pass
/// AutoStride for any of the stride values, and they will be
/// auto-computed assuming contiguous data.  Return true if ok, false if
/// it didn't know how to do the conversion.
OIIO_API bool copy_image (int nchannels, int width, int height, int depth,
                           const void *src, stride_t pixelsize,
                           stride_t src_xstride, stride_t src_ystride,
                           stride_t src_zstride,
                           void *dst, stride_t dst_xstride,
                           stride_t dst_ystride, stride_t dst_zstride);

/// Decode a raw Exif data block and save all the metadata in an
/// ImageSpec.  Return true if all is ok, false if the exif block was
/// somehow malformed.  The binary data pointed to by 'exif' should
/// start with a TIFF directory header.
OIIO_API bool decode_exif (const void *exif, int length, ImageSpec &spec);

/// Construct an Exif data block from the ImageSpec, appending the Exif 
/// data as a big blob to the char vector.
OIIO_API void encode_exif (const ImageSpec &spec, std::vector<char> &blob);

/// Add metadata to spec based on raw IPTC (International Press
/// Telecommunications Council) metadata in the form of an IIM
/// (Information Interchange Model).  Return true if all is ok, false if
/// the iptc block was somehow malformed.  This is a utility function to
/// make it easy for multiple format plugins to support embedding IPTC
/// metadata without having to duplicate functionality within each
/// plugin.  Note that IIM is actually considered obsolete and is
/// replaced by an XML scheme called XMP.
OIIO_API bool decode_iptc_iim (const void *iptc, int length, ImageSpec &spec);

/// Find all the IPTC-amenable metadata in spec and assemble it into an
/// IIM data block in iptc.  This is a utility function to make it easy
/// for multiple format plugins to support embedding IPTC metadata
/// without having to duplicate functionality within each plugin.  Note
/// that IIM is actually considered obsolete and is replaced by an XML
/// scheme called XMP.
OIIO_API void encode_iptc_iim (const ImageSpec &spec, std::vector<char> &iptc);

/// Add metadata to spec based on XMP data in an XML block.  Return true
/// if all is ok, false if the xml was somehow malformed.  This is a
/// utility function to make it easy for multiple format plugins to
/// support embedding XMP metadata without having to duplicate
/// functionality within each plugin.
OIIO_API bool decode_xmp (const std::string &xml, ImageSpec &spec);

/// Find all the relavant metadata (IPTC, Exif, etc.) in spec and
/// assemble it into an XMP XML string.  This is a utility function to
/// make it easy for multiple format plugins to support embedding XMP
/// metadata without having to duplicate functionality within each
/// plugin.  If 'minimal' is true, then don't encode things that would
/// be part of ordinary TIFF or exif tags.
OIIO_API std::string encode_xmp (const ImageSpec &spec, bool minimal=false);

// All the wrap_foo functions implement a wrap mode, wherein coord is
// altered to be origin <= coord < origin+width.  The return value
// indicates if the resulting wrapped value is valid (example, for
// wrap_black, values outside the region are invalid and do not modify
// the coord parameter).
OIIO_API bool wrap_black (int &coord, int origin, int width);
OIIO_API bool wrap_clamp (int &coord, int origin, int width);
OIIO_API bool wrap_periodic (int &coord, int origin, int width);
OIIO_API bool wrap_periodic_pow2 (int &coord, int origin, int width);
OIIO_API bool wrap_mirror (int &coord, int origin, int width);

// Typedef for the function signature of a wrap implementation.
typedef bool (*wrap_impl) (int &coord, int origin, int width);


// to force correct linkage on some systems
OIIO_API void _ImageIO_force_link ();

}
OIIO_NAMESPACE_EXIT

#endif  // OPENIMAGEIO_IMAGEIO_H