Annotation of parser3/src/classes/image.C, revision 1.186

1.1       paf         1: /** @file
                      2:        Parser: @b image parser class.
                      3: 
1.184     moko        4:        Copyright (c) 2001-2023 Art. Lebedev Studio (http://www.artlebedev.com)
                      5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.73      paf         6: */
1.1       paf         7: 
1.31      parser      8: /*
                      9:        jpegsize: gets the width and height (in pixels) of a jpeg file
                     10:        Andrew Tong, werdna@ugcs.caltech.edu           February 14, 1995
                     11:        modified slightly by alex@ed.ac.uk
                     12:        and further still by rjray@uswest.com
                     13:        optimization and general re-write from tmetro@vl.com
                     14:        from perl by paf@design.ru
1.1       paf        15: */
                     16: 
                     17: #include "pa_config_includes.h"
1.139     moko       18: #include "gif.h"
1.1       paf        19: 
1.91      paf        20: #include "pa_vmethod_frame.h"
1.1       paf        21: #include "pa_common.h"
                     22: #include "pa_request.h"
                     23: #include "pa_vfile.h"
                     24: #include "pa_vimage.h"
1.89      paf        25: #include "pa_vdate.h"
1.91      paf        26: #include "pa_table.h"
1.163     moko       27: #include "pa_charsets.h"
1.1       paf        28: 
1.186   ! moko       29: volatile const char * IDENT_IMAGE_C="$Id: image.C,v 1.185 2024/09/11 21:07:36 moko Exp $";
1.139     moko       30: 
1.125     misha      31: // defines
                     32: 
1.126     misha      33: static const String spacebar_width_name("space");
                     34: static const String monospace_width_name("width");
                     35: static const String letter_spacing_name("spacing");
1.125     misha      36: 
1.22      paf        37: // class
                     38: 
1.91      paf        39: class MImage: public Methoded {
1.22      paf        40: public: // VStateless_class
1.130     misha      41:        Value* create_new_value(Pool&) { return new VImage(); }
1.22      paf        42: 
                     43: public:
1.91      paf        44:        MImage();
1.22      paf        45: };
1.1       paf        46: 
1.91      paf        47: // globals
                     48: 
1.151     moko       49: DECLARE_CLASS_VAR(image, new MImage);
1.91      paf        50: 
1.1       paf        51: // helpers
                     52: 
1.118     misha      53: #define EXIF_TAG(tag, name) put(tag, #name);
                     54: 
1.91      paf        55: /// value of exif tag -> it's value
                     56: class EXIF_tag_value2name: public Hash<int, const char*> {
                     57: public:
                     58:        EXIF_tag_value2name() {
                     59:        // image JPEG Exif
                     60:                // Tags used by IFD0 (main image)
                     61:                EXIF_TAG(0x010e,        ImageDescription);
                     62:                EXIF_TAG(0x010f,        Make);
                     63:                EXIF_TAG(0x0110,        Model);
                     64:                EXIF_TAG(0x0112,        Orientation);
                     65:                EXIF_TAG(0x011a,        XResolution);
                     66:                EXIF_TAG(0x011b,        YResolution);
                     67:                EXIF_TAG(0x0128,        ResolutionUnit);
                     68:                EXIF_TAG(0x0131,        Software);
                     69:                EXIF_TAG(0x0132,        DateTime);
                     70:                EXIF_TAG(0x013e,        WhitePoint);
                     71:                EXIF_TAG(0x013f,        PrimaryChromaticities);
                     72:                EXIF_TAG(0x0211,        YCbCrCoefficients);
                     73:                EXIF_TAG(0x0213,        YCbCrPositioning);
                     74:                EXIF_TAG(0x0214,        ReferenceBlackWhite);
                     75:                EXIF_TAG(0x8298,        Copyright);
                     76:                EXIF_TAG(0x8769,        ExifOffset);
                     77:                // Tags used by Exif SubIFD
                     78:                EXIF_TAG(0x829a,        ExposureTime);
                     79:                EXIF_TAG(0x829d,        FNumber);
                     80:                EXIF_TAG(0x8822,        ExposureProgram);
                     81:                EXIF_TAG(0x8827,        ISOSpeedRatings);
                     82:                EXIF_TAG(0x9000,        ExifVersion);
                     83:                EXIF_TAG(0x9003,        DateTimeOriginal);
                     84:                EXIF_TAG(0x9004,        DateTimeDigitized);
                     85:                EXIF_TAG(0x9101,        ComponentsConfiguration);
                     86:                EXIF_TAG(0x9102,        CompressedBitsPerPixel);
                     87:                EXIF_TAG(0x9201,        ShutterSpeedValue);
                     88:                EXIF_TAG(0x9202,        ApertureValue);
                     89:                EXIF_TAG(0x9203,        BrightnessValue);
                     90:                EXIF_TAG(0x9204,        ExposureBiasValue);
                     91:                EXIF_TAG(0x9205,        MaxApertureValue);
                     92:                EXIF_TAG(0x9206,        SubjectDistance);
                     93:                EXIF_TAG(0x9207,        MeteringMode);
                     94:                EXIF_TAG(0x9208,        LightSource);
                     95:                EXIF_TAG(0x9209,        Flash);
                     96:                EXIF_TAG(0x920a,        FocalLength);
                     97:                EXIF_TAG(0x927c,        MakerNote);
                     98:                EXIF_TAG(0x9286,        UserComment);
                     99:                EXIF_TAG(0x9290,        SubsecTime);
                    100:                EXIF_TAG(0x9291,        SubsecTimeOriginal);
                    101:                EXIF_TAG(0x9292,        SubsecTimeDigitized);
                    102:                EXIF_TAG(0xa000,        FlashPixVersion);
                    103:                EXIF_TAG(0xa001,        ColorSpace);
                    104:                EXIF_TAG(0xa002,        ExifImageWidth);
                    105:                EXIF_TAG(0xa003,        ExifImageHeight);
                    106:                EXIF_TAG(0xa004,        RelatedSoundFile);
                    107:                EXIF_TAG(0xa005,        ExifInteroperabilityOffset);
                    108:                EXIF_TAG(0xa20e,        FocalPlaneXResolution);
                    109:                EXIF_TAG(0xa20f,        FocalPlaneYResolution);
                    110:                EXIF_TAG(0xa210,        FocalPlaneResolutionUnit);
                    111:                EXIF_TAG(0xa215,        ExposureIndex);
                    112:                EXIF_TAG(0xa217,        SensingMethod);
                    113:                EXIF_TAG(0xa300,        FileSource);
                    114:                EXIF_TAG(0xa301,        SceneType);
                    115:                EXIF_TAG(0xa302,        CFAPattern);
                    116:                // Misc Tags
                    117:                EXIF_TAG(0x00fe,        NewSubfileType);
                    118:                EXIF_TAG(0x00ff,        SubfileType);
                    119:                EXIF_TAG(0x012d,        TransferFunction);
                    120:                EXIF_TAG(0x013b,        Artist);
                    121:                EXIF_TAG(0x013d,        Predictor);
                    122:                EXIF_TAG(0x0142,        TileWidth);
                    123:                EXIF_TAG(0x0143,        TileLength);
                    124:                EXIF_TAG(0x0144,        TileOffsets);
                    125:                EXIF_TAG(0x0145,        TileByteCounts);
                    126:                EXIF_TAG(0x014a,        SubIFDs);
                    127:                EXIF_TAG(0x015b,        JPEGTables);
                    128:                EXIF_TAG(0x828d,        CFARepeatPatternDim);
                    129:                EXIF_TAG(0x828e,        CFAPattern);
                    130:                EXIF_TAG(0x828f,        BatteryLevel);
                    131:                EXIF_TAG(0x83bb,        IPTC/NAA);
                    132:                EXIF_TAG(0x8773,        InterColorProfile);
                    133:                EXIF_TAG(0x8824,        SpectralSensitivity);
1.118     misha     134:                //EXIF_TAG(0x8825,      GPSInfo);
1.91      paf       135:                EXIF_TAG(0x8828,        OECF);
                    136:                EXIF_TAG(0x8829,        Interlace);
                    137:                EXIF_TAG(0x882a,        TimeZoneOffset);
                    138:                EXIF_TAG(0x882b,        SelfTimerMode);
                    139:                EXIF_TAG(0x920b,        FlashEnergy);
                    140:                EXIF_TAG(0x920c,        SpatialFrequencyResponse);
                    141:                EXIF_TAG(0x920d,        Noise);
                    142:                EXIF_TAG(0x9211,        ImageNumber);
                    143:                EXIF_TAG(0x9212,        SecurityClassification);
                    144:                EXIF_TAG(0x9213,        ImageHistory);
                    145:                EXIF_TAG(0x9214,        SubjectLocation);
                    146:                EXIF_TAG(0x9215,        ExposureIndex);
                    147:                EXIF_TAG(0x9216,        TIFF/EPStandardID);
                    148:                EXIF_TAG(0xa20b,        FlashEnergy);
                    149:                EXIF_TAG(0xa20c,        SpatialFrequencyResponse);
                    150:                EXIF_TAG(0xa214,        SubjectLocation);
1.118     misha     151: 
                    152:                // additional things added by misha@
                    153:                EXIF_TAG(0x0100,        ImageWidth);
                    154:                EXIF_TAG(0x0101,        ImageLength);
                    155:                EXIF_TAG(0x0102,        BitsPerSample);
                    156:                EXIF_TAG(0x0103,        Compression);
                    157:                EXIF_TAG(0x0106,        PhotometricInterpretation);
                    158:                EXIF_TAG(0x010a,        FillOrder);
                    159:                EXIF_TAG(0x010d,        DocumentName);
                    160:                EXIF_TAG(0x0111,        StripOffsets);
                    161:                EXIF_TAG(0x0115,        SamplesPerPixel);
                    162:                EXIF_TAG(0x0116,        RowsPerStrip);
                    163:                EXIF_TAG(0x0117,        StripByteCounts);
                    164:                EXIF_TAG(0x011c,        PlanarConfiguration);
                    165:                EXIF_TAG(0x0156,        TransferRange);
                    166:                EXIF_TAG(0x0200,        JPEGProc);
                    167:                EXIF_TAG(0x0201,        JPEGInterchangeFormat);
                    168:                EXIF_TAG(0x0202,        JPEGInterchangeFormatLength);
                    169:                EXIF_TAG(0x0212,        YCbCrSubSampling);
                    170:                EXIF_TAG(0xa401,        CustomRendered);
                    171:                EXIF_TAG(0xa402,        ExposureMode);
                    172:                EXIF_TAG(0xa403,        WhiteBalance);
                    173:                EXIF_TAG(0xa404,        DigitalZoomRatio);
                    174:                EXIF_TAG(0xa405,        FocalLengthIn35mmFilm);
                    175:                EXIF_TAG(0xa406,        SceneCaptureType);
                    176:                EXIF_TAG(0xa407,        GainControl);
                    177:                EXIF_TAG(0xa408,        Contrast);
                    178:                EXIF_TAG(0xa409,        Saturation);
                    179:                EXIF_TAG(0xa40a,        Sharpness);
                    180:                EXIF_TAG(0xa40b,        DeviceSettingDescription);
                    181:                EXIF_TAG(0xa40c,        SubjectDistanceRange);
                    182:                EXIF_TAG(0xa420,        ImageUniqueID);
1.149     moko      183: 
                    184:                // other tags
                    185:                EXIF_TAG(0xa430,        CameraOwnerName);
                    186:                EXIF_TAG(0xa431,        BodySerialNumber);
                    187:                EXIF_TAG(0xa432,        LensSpecification);
                    188:                EXIF_TAG(0xa433,        LensManufactor);
                    189:                EXIF_TAG(0xa434,        LensModel);
                    190:                EXIF_TAG(0xa435,        LensSerialNumber);
1.91      paf       191:        }
                    192: } exif_tag_value2name;
                    193: 
1.118     misha     194: class EXIF_gps_tag_value2name: public Hash<int, const char*> {
                    195: public:
                    196:                EXIF_gps_tag_value2name() {
                    197:                EXIF_TAG(0x0,   GPSVersionID);
                    198:                EXIF_TAG(0x1,   GPSLatitudeRef);
                    199:                EXIF_TAG(0x2,   GPSLatitude);
                    200:                EXIF_TAG(0x3,   GPSLongitudeRef);
                    201:                EXIF_TAG(0x4,   GPSLongitude);
                    202:                EXIF_TAG(0x5,   GPSAltitudeRef);
                    203:                EXIF_TAG(0x6,   GPSAltitude);
                    204:                EXIF_TAG(0x7,   GPSTimeStamp);
                    205:                EXIF_TAG(0x8,   GPSSatellites);
                    206:                EXIF_TAG(0x9,   GPSStatus);
                    207:                EXIF_TAG(0xA,   GPSMeasureMode);
                    208:                EXIF_TAG(0xB,   GPSDOP);
                    209:                EXIF_TAG(0xC,   GPSSpeedRef);
                    210:                EXIF_TAG(0xD,   GPSSpeed);
                    211:                EXIF_TAG(0xE,   GPSTrackRef);
                    212:                EXIF_TAG(0xF,   GPSTrack);
                    213:                EXIF_TAG(0x10,  GPSImgDirectionRef);
                    214:                EXIF_TAG(0x11,  GPSImgDirection);
                    215:                EXIF_TAG(0x12,  GPSMapDatum);
                    216:                EXIF_TAG(0x13,  GPSDestLatitudeRef);
                    217:                EXIF_TAG(0x14,  GPSDestLatitude);
                    218:                EXIF_TAG(0x15,  GPSDestLongitudeRef);
                    219:                EXIF_TAG(0x16,  GPSDestLongitude);
                    220:                EXIF_TAG(0x17,  GPSDestBearingRef);
                    221:                EXIF_TAG(0x18,  GPSDestBearing);
                    222:                EXIF_TAG(0x19,  GPSDestDistanceRef);
                    223:                EXIF_TAG(0x1A,  GPSDestDistance);
                    224:                EXIF_TAG(0x1B,  GPSProcessingMethod);
                    225:                EXIF_TAG(0x1C,  GPSAreaInformation);
                    226:                EXIF_TAG(0x1D,  GPSDateStamp);
                    227:                EXIF_TAG(0x1E,  GPSDifferential);
                    228:        }
                    229: } exif_gps_tag_value2name;
                    230: 
1.170     moko      231: 
1.169     moko      232: ///*********************************************** support functions
1.91      paf       233: 
1.1       paf       234: class Measure_reader {
                    235: public:
1.91      paf       236:        virtual size_t read(const char* &buf, size_t limit)=0;
1.174     moko      237:        virtual void seek(uint64_t value)=0;
                    238:        virtual uint64_t tell()=0;
                    239:        virtual uint64_t length()=0;
1.77      paf       240: };
1.1       paf       241: 
1.77      paf       242: class Measure_file_reader: public Measure_reader {
1.152     moko      243:        const String& file_name;
1.91      paf       244:        int f;
                    245: 
1.77      paf       246: public:
1.152     moko      247:        Measure_file_reader(int af, const String& afile_name):
                    248:                file_name(afile_name), f(af) {
1.1       paf       249:        }
                    250: 
1.91      paf       251:        override size_t read(const char* &abuf, size_t limit) {
1.77      paf       252:                if(limit==0)
1.1       paf       253:                        return 0;
1.77      paf       254: 
1.91      paf       255:                char* lbuf=new(PointerFreeGC) char[limit];
1.143     moko      256:                ssize_t read_size=::read(f, lbuf, limit);  abuf=lbuf;
                    257:                if(read_size<0)
                    258:                        throw Exception(0, &file_name, "measure read failed: %s (%d)", strerror(errno), errno);
1.1       paf       259:                return read_size;
                    260:        }
                    261: 
1.174     moko      262:        override void seek(uint64_t value) {
                    263:                if(pa_lseek(f, value, SEEK_SET)<0)
                    264:                        throw Exception(IMAGE_FORMAT, &file_name, "seek to %.15g failed: %s (%d)", (double)value, strerror(errno), errno);
1.77      paf       265:        }
                    266: 
1.174     moko      267:        override uint64_t tell() { return pa_lseek(f, 0, SEEK_CUR); }
                    268: 
                    269:        override uint64_t length() { return pa_lseek(f, 0, SEEK_END); }
1.79      paf       270: 
1.77      paf       271: };
                    272: 
                    273: class Measure_buf_reader: public Measure_reader {
1.91      paf       274: 
                    275:        const char* buf; size_t size;
                    276:        const String& file_name; 
                    277: 
                    278:        size_t offset;
                    279: 
1.77      paf       280: public:
1.91      paf       281:        Measure_buf_reader(const char* abuf, size_t asize, const String& afile_name): 
1.77      paf       282:                buf(abuf), size(asize), file_name(afile_name), offset(0) {
                    283:        }
                    284:        
1.91      paf       285:        override size_t read(const char* &abuf, size_t limit) {
1.77      paf       286:                size_t to_read=min(limit, size-offset);
1.91      paf       287:                abuf=buf+offset;
1.77      paf       288:                offset+=to_read;
                    289:                return to_read;
                    290:        }
                    291: 
1.174     moko      292:        override void seek(uint64_t value) {
                    293:                if(value>(uint64_t)size)
                    294:                        throw Exception(IMAGE_FORMAT, &file_name, "seek to %.15g failed: out of buffer (%.15g)", value, size);
                    295:                offset=(size_t)value;
1.77      paf       296:        }
                    297: 
1.174     moko      298:        override uint64_t tell() { return offset; }
                    299: 
                    300:        override uint64_t length() { return size; }
1.79      paf       301: 
1.1       paf       302: };
1.77      paf       303: 
1.1       paf       304: 
1.169     moko      305: struct Measure_info {
                    306:        ushort width;
                    307:        ushort height;
                    308:        Value** exif;
                    309:        Value** xmp;
                    310:        Charset* xmp_charset;
1.181     moko      311:        bool    video;
1.72      paf       312: };
                    313: 
1.164     moko      314: 
1.169     moko      315: inline ushort x_endian_to_ushort(uchar b0, uchar b1) {
                    316:        return (ushort)((b1<<8) + b0);
                    317: }
                    318: 
                    319: inline uint x_endian_to_uint(uchar b0, uchar b1, uchar b2, uchar b3) {
                    320:        return (uint)(((((b3<<8) + b2)<<8)+b1)<<8)+b0;
                    321: }
                    322: 
                    323: inline ushort endian_to_ushort(bool is_big, const uchar *b/* [2] */) {
                    324:        return is_big ? x_endian_to_ushort(b[1], b[0]) : x_endian_to_ushort(b[0], b[1]);
                    325: }
                    326: 
                    327: inline uint endian_to_uint(bool is_big, const uchar *b /* [4] */) {
                    328:        return is_big ? x_endian_to_uint(b[3], b[2], b[1], b[0]) : x_endian_to_uint(b[0], b[1], b[2], b[3]);
                    329: }
1.1       paf       330: 
1.170     moko      331: 
1.169     moko      332: ///*********************************************** JPEG
1.170     moko      333: 
1.31      parser    334: struct JPG_Segment_head {
1.80      paf       335:        uchar marker;
                    336:        uchar code;
                    337:        uchar length[2];
1.1       paf       338: };
1.21      paf       339: /// JPEG frame header
1.31      parser    340: struct JPG_Size_segment_body {
1.164     moko      341:        char data;              //< data precision of bits/sample
                    342:        uchar height[2];        //< image height
                    343:        uchar width[2];         //< image width
                    344:        char numComponents;     //< number of color components
1.1       paf       345: };
                    346: 
1.80      paf       347: /// JPEG Exif TIFF Header
                    348: struct JPG_Exif_TIFF_header {
1.165     moko      349:        char byte_align_identifier[2];
                    350:        uchar signature[2]; // always 000A [or 0A00]
1.80      paf       351:        uchar first_IFD_offset[4]; // Usually the first IFD starts immediately next to TIFF header, so this offset has value '0x00000008'.
                    352: };
                    353: 
                    354: // JPEG Exif IFD start
1.91      paf       355: struct JPG_Exif_IFD_begin {
1.80      paf       356:        uchar directory_entry_count[2]; // the number of directory entry contains in this IFD
                    357: };
                    358: 
                    359: // TTTT ffff NNNNNNNN DDDDDDDD 
                    360: struct JPG_Exif_IFD_entry {
                    361:        uchar tag[2]; // Tag number, this shows a kind of data
                    362:        uchar format[2]; // data format
                    363:        uchar components_count[4]; // number of components
                    364:        uchar value_or_offset_to_it[4]; // data value or offset to data value
                    365: };
                    366: 
                    367: #define JPG_IFD_TAG_EXIF_OFFSET 0x8769
                    368: 
1.118     misha     369: #define JPG_IFD_TAG_EXIF_GPS_OFFSET 0x8825
                    370: 
1.89      paf       371: #define JPEG_EXIF_DATE_CHARS 20
                    372: 
1.155     moko      373: static Value* parse_IFD_entry_formatted_one_value(bool is_big, ushort format, size_t component_size, const uchar *value) {
1.80      paf       374:        switch(format) {
                    375:        case 1: // unsigned byte
1.91      paf       376:                return new VInt((uchar)value[0]);
1.80      paf       377:        case 3: // unsigned short
1.91      paf       378:                return new VInt(endian_to_ushort(is_big, value));
1.80      paf       379:        case 4: // unsigned long
                    380:                 // 'double' because parser's Int is signed
1.91      paf       381:                return new VDouble(endian_to_uint(is_big, value));
1.80      paf       382:        case 5: // unsigned rational
                    383:                {
                    384:                        uint numerator=endian_to_uint(is_big, value); value+=component_size/2;
                    385:                        uint denominator=endian_to_uint(is_big, value);
                    386:                        if(!denominator)
                    387:                                return 0;
1.91      paf       388:                        return new VDouble(((double)numerator)/denominator);
1.80      paf       389:                }
                    390:        case 6: // signed byte
1.91      paf       391:                return new VInt((signed char)value[0]);
1.80      paf       392:        case 8: // signed short
1.91      paf       393:                return new VInt((signed short)endian_to_ushort(is_big, value));
1.80      paf       394:        case 9: // signed long
1.91      paf       395:                return new VInt((signed int)endian_to_uint(is_big, value));
1.80      paf       396:        case 10: // signed rational
                    397:                {
                    398:                        signed int numerator=(signed int)endian_to_uint(is_big, value); value+=component_size/2;
                    399:                        uint denominator=endian_to_uint(is_big, value);
                    400:                        if(!denominator)
                    401:                                return 0;
1.91      paf       402:                        return new VDouble(numerator/denominator);
1.80      paf       403:                }
                    404:                /*
                    405:        case 11: // single float
1.120     misha     406:                @todo
1.80      paf       407:        case 12: // double float
1.120     misha     408:                @todo
1.80      paf       409:                */
                    410:        };      
                    411:        
                    412:        return 0;
                    413: }
                    414: 
1.89      paf       415: // date.C
1.147     moko      416: tm cstr_to_time_t(char *, const char **);
1.89      paf       417: 
1.155     moko      418: static Value* parse_IFD_entry_formatted_value(bool is_big, ushort format, size_t component_size, uint components_count, const uchar *value) {
1.80      paf       419:        if(format==2) { // ascii string, exception: the only type with varying size
1.91      paf       420:                const char* cstr=(const char* )value;
                    421:                size_t length=components_count;
1.89      paf       422:                // Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes
1.155     moko      423:                if(length==JPEG_EXIF_DATE_CHARS && isdigit((unsigned char)cstr[0]) && cstr[length-1]==0) {
1.106     paf       424:                        try {
1.183     moko      425:                                tm tmIn=cstr_to_time_t(pa_strdup(cstr), 0);
1.146     moko      426:                                return new VDate(tmIn);
1.106     paf       427:                        }
                    428:                        catch(...) { /*ignore bad date times*/ }
1.89      paf       429:                }
                    430: 
1.123     misha     431:                return new VString(*new String(cstr, String::L_TAINTED));
1.80      paf       432:        }
                    433: 
                    434:        if(components_count==1)
1.91      paf       435:                return parse_IFD_entry_formatted_one_value(is_big, format, component_size, value);
1.80      paf       436: 
1.91      paf       437:        VHash* result=new VHash;
                    438:        HashStringValue& hash=result->hash();
1.80      paf       439:        for(uint i=0; i<components_count; i++, value+=component_size) {
1.91      paf       440:                hash.put(
1.185     moko      441:                        pa_uitoa(i),
1.91      paf       442:                        parse_IFD_entry_formatted_one_value(is_big, format, component_size, value));
1.80      paf       443:        }
                    444: 
1.91      paf       445:        return result;
1.80      paf       446: }
                    447: 
1.176     moko      448: static Value* parse_IFD_entry_value(bool is_big, Measure_reader& reader, uint64_t tiff_base, JPG_Exif_IFD_entry& entry) {
1.80      paf       449:        size_t format2component_size[]={
                    450:                0, // undefined
                    451:                1, // unsigned byte
                    452:                1, // ascii string
                    453:                2, // unsigned short
                    454:                4, // unsigned long
                    455:                8, // unsigned rational
                    456:                1, // signed byte
                    457:                0, // undefined
                    458:                2, // signed short
                    459:                4, // signed long
                    460:                8, // signed rational
                    461:                /*
                    462:                4, // single float
                    463:                8, // double float
                    464:                */
                    465:        };
                    466: 
                    467:        ushort format=endian_to_ushort(is_big, entry.format);
                    468:        if(format>=sizeof(format2component_size)/sizeof(format2component_size[0]))
                    469:                return 0; // format out of range, ignoring
                    470: 
                    471:        size_t component_size=format2component_size[format];
                    472:        if(component_size==0)
                    473:                return 0; // undefined format
                    474: 
                    475:        // You can get the total data byte length by multiplies 
                    476:        // a 'bytes/components' value (see above chart) by number of components stored 'NNNNNNNN' area
                    477:        uint components_count=endian_to_uint(is_big, entry.components_count);
1.121     misha     478:        uint value_size=component_size*components_count;
1.80      paf       479:        // If its size is over 4bytes, 'DDDDDDDD' contains the offset to data stored address
1.91      paf       480:        Value* result;
1.80      paf       481: 
                    482:        if(value_size<=4)
1.155     moko      483:                result=parse_IFD_entry_formatted_value(is_big, format, component_size, components_count, entry.value_or_offset_to_it);
1.80      paf       484:        else {
1.174     moko      485:                uint64_t remembered=reader.tell();
1.80      paf       486:                {
1.174     moko      487:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it));
1.91      paf       488:                        const char* value;
1.156     moko      489:                        if(reader.read(value, value_size)<value_size)
1.80      paf       490:                                return 0;
1.155     moko      491:                        result=parse_IFD_entry_formatted_value(is_big, format, component_size, components_count, (const uchar*)value);
1.80      paf       492:                }
1.174     moko      493:                reader.seek(remembered);
1.80      paf       494:        }
                    495: 
                    496:        return result;
                    497: }
                    498: 
1.176     moko      499: static void parse_IFD(HashStringValue& hash, bool is_big, Measure_reader& reader, uint64_t tiff_base, bool gps=false);
1.91      paf       500: 
1.176     moko      501: static void parse_IFD_entry(HashStringValue& hash, bool is_big, Measure_reader& reader, uint64_t tiff_base, JPG_Exif_IFD_entry& entry, bool gps=false) {
1.80      paf       502:        ushort tag=endian_to_ushort(is_big, entry.tag);
1.118     misha     503: 
                    504:        if(tag==JPG_IFD_TAG_EXIF_OFFSET || tag==JPG_IFD_TAG_EXIF_GPS_OFFSET){
1.174     moko      505:                uint64_t remembered=reader.tell();
1.80      paf       506:                {
1.174     moko      507:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it));
1.118     misha     508:                        parse_IFD(hash, is_big, reader, tiff_base, (tag==JPG_IFD_TAG_EXIF_GPS_OFFSET)?true:gps);
1.80      paf       509:                }
1.174     moko      510:                reader.seek(remembered);
1.80      paf       511:                return;
                    512:        }
1.118     misha     513: 
1.91      paf       514:        if(Value* value=parse_IFD_entry_value(is_big, reader, tiff_base, entry)) {
1.118     misha     515:                if(const char* name=(gps)?exif_gps_tag_value2name.get(tag):exif_tag_value2name.get(tag))
1.148     moko      516:                        hash.put(name, value);
1.80      paf       517:                else
1.185     moko      518:                        hash.put(pa_uitoa(tag), value);
1.80      paf       519:        }
1.1       paf       520: }
                    521: 
1.176     moko      522: static void parse_IFD(HashStringValue& hash, bool is_big, Measure_reader& reader, uint64_t tiff_base, bool gps) {
1.91      paf       523:        const char* buf;
                    524:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
1.80      paf       525:                return;
1.91      paf       526:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
1.80      paf       527: 
                    528:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    529:        for(int i=0; i<directory_entry_count; i++) {
                    530:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    531:                        return;
                    532: 
1.118     misha     533:                parse_IFD_entry(hash, is_big, reader, tiff_base, *(JPG_Exif_IFD_entry *)buf, gps);
1.80      paf       534:        }
                    535:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    536: }
                    537: 
1.162     moko      538: static Value* parse_exif(Measure_reader& reader) {
1.91      paf       539:        const char* buf;
1.80      paf       540: 
1.175     moko      541:        uint64_t tiff_base=reader.tell();
1.80      paf       542:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    543:                return 0;
                    544: 
                    545:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    546:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    547: 
                    548:        uint first_IFD_offset=endian_to_uint(is_big, head->first_IFD_offset);
1.174     moko      549:        reader.seek(tiff_base+first_IFD_offset);
1.80      paf       550: 
1.91      paf       551:        VHash* vhash=new VHash;
1.80      paf       552: 
                    553:        // IFD
1.91      paf       554:        parse_IFD(vhash->hash(), is_big, reader, tiff_base);
1.80      paf       555: 
1.91      paf       556:        return vhash;
1.80      paf       557: }
                    558: 
1.163     moko      559: static Value* parse_xmp(Measure_reader& reader, ushort xmp_length, Measure_info &info) {
1.162     moko      560:        const char* buf;
                    561:        if(reader.read(buf, xmp_length)<xmp_length)
                    562:                return 0;
1.163     moko      563: 
                    564:        String::C xmp = Charset::transcode(String::C(pa_strdup(buf, xmp_length), xmp_length), *info.xmp_charset, pa_thread_request().charsets.source());
                    565:        return new VString(*new String(xmp, String::L_TAINTED));
1.162     moko      566: }
                    567: 
                    568: static void measure_jpeg(const String& origin_string, Measure_reader& reader, Measure_info &info) {
1.2       paf       569:        // JFIF format markers
1.80      paf       570:        const uchar MARKER=0xFF;
                    571:        const uchar CODE_SIZE_A=0xC0;
                    572:        const uchar CODE_SIZE_B=0xC1;
                    573:        const uchar CODE_SIZE_C=0xC2;
                    574:        const uchar CODE_SIZE_D=0xC3;
1.162     moko      575:        const uchar CODE_APP1=0xE1;
1.2       paf       576: 
1.91      paf       577:        const char* buf;
1.18      paf       578:        const size_t prefix_size=2;
1.31      parser    579:        if(reader.read(buf, prefix_size)<prefix_size)
1.155     moko      580:                throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - too small");
1.80      paf       581:        uchar *signature=(uchar *)buf;
1.1       paf       582:        
1.31      parser    583:        if(!(signature[0]==0xFF && signature[1]==0xD8)) 
1.155     moko      584:                throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - wrong signature");
1.31      parser    585: 
                    586:        while(true) {
1.177     moko      587:                uint64_t segment_base=reader.tell()+2/*marker,code*/;
1.31      parser    588:                if(reader.read(buf, sizeof(JPG_Segment_head))<sizeof(JPG_Segment_head))
1.79      paf       589:                        break;
1.31      parser    590:                JPG_Segment_head *head=(JPG_Segment_head *)buf;
                    591: 
1.162     moko      592:                // Verify that it's a valid segment.
1.31      parser    593:                if(head->marker!=MARKER)
1.155     moko      594:                        throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - marker not found");
1.79      paf       595: 
1.162     moko      596:                ushort segment_length=endian_to_ushort(true, head->length);
                    597: 
1.79      paf       598:                switch(head->code) {
1.162     moko      599:                // http://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_JPEG_files
                    600:                case CODE_APP1:
                    601:                        {
                    602:                                const size_t EXIF_SIG_LEN=6; // Exif\0\0
                    603:                                const size_t XMP_SIG_LEN=29; // http://ns.adobe.com/xap/1.0/\0
                    604: 
                    605:                                if(segment_length<EXIF_SIG_LEN+2 || reader.read(buf, EXIF_SIG_LEN)<EXIF_SIG_LEN)
                    606:                                        break;
                    607:                                if(memcmp(buf, "Exif\0\0", EXIF_SIG_LEN)==0){
                    608:                                        if(info.exif && !*info.exif) // backward compatibility: using first segment
                    609:                                                *info.exif=parse_exif(reader);
                    610:                                        break;
                    611:                                }
                    612: 
                    613:                                if(memcmp(buf, "http:/", EXIF_SIG_LEN))
                    614:                                        break;
                    615:                                if(segment_length<XMP_SIG_LEN+2 || reader.read(buf, XMP_SIG_LEN-EXIF_SIG_LEN)<XMP_SIG_LEN-EXIF_SIG_LEN)
                    616:                                        break;
                    617:                                if(memcmp(buf, "/ns.adobe.com/xap/1.0/\0", XMP_SIG_LEN-EXIF_SIG_LEN)==0){
                    618:                                        if(info.xmp && !*info.xmp) // backward compatibility: using first segment
1.163     moko      619:                                                *info.xmp=parse_xmp(reader, segment_length - XMP_SIG_LEN - 2 /* segment_length */, info);
1.162     moko      620:                                }
                    621: 
                    622:                        }
1.1       paf       623:                        break;
1.31      parser    624: 
1.79      paf       625:                case CODE_SIZE_A:
                    626:                case CODE_SIZE_B:
                    627:                case CODE_SIZE_C:
                    628:                case CODE_SIZE_D:
                    629:                        {
                    630:                                // Segments that contain size info
                    631:                                if(reader.read(buf, sizeof(JPG_Size_segment_body))<sizeof(JPG_Size_segment_body))
1.155     moko      632:                                        throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - can not fully read Size segment");
1.79      paf       633:                                JPG_Size_segment_body *body=(JPG_Size_segment_body *)buf;
                    634:                                
1.162     moko      635:                                info.width=endian_to_ushort(true, body->width);
                    636:                                info.height=endian_to_ushort(true, body->height);
                    637:                        }
1.80      paf       638:                        return;
1.79      paf       639:                };
                    640: 
1.174     moko      641:                reader.seek(segment_base + segment_length);
1.31      parser    642:        }
                    643: 
1.155     moko      644:        throw Exception(IMAGE_FORMAT, &origin_string, "broken JPEG file - size frame not found");
1.1       paf       645: }
                    646: 
1.169     moko      647: ///*********************************************** TIFF
                    648: 
1.165     moko      649: static bool parse_tiff_IFD(bool is_big, Measure_reader& reader, Measure_info &info) {
                    650:        const char* buf;
                    651:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
                    652:                return false;
                    653:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
                    654: 
                    655:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    656:        for(int i=0; i<directory_entry_count; i++) {
                    657:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    658:                        return false;
                    659: 
                    660:                JPG_Exif_IFD_entry *entry=(JPG_Exif_IFD_entry *)buf;
                    661:                ushort entry_tag=endian_to_ushort(is_big, entry->tag);
                    662: 
                    663:                if(entry_tag == 256 || entry_tag == 257){
                    664:                        ushort entry_format=endian_to_ushort(is_big, entry->format);
                    665:                        if(entry_format != 3 && entry_format != 4 || endian_to_uint(is_big, entry->components_count) != 1)
                    666:                                return false;
                    667:                        uint value = (entry_format == 3) ? endian_to_ushort(is_big, entry->value_or_offset_to_it) : endian_to_uint(is_big, entry->value_or_offset_to_it);
1.178     moko      668:                        (entry_tag == 256) ? info.width=(short)value : info.height=(short)value;
1.165     moko      669:                        if(info.width && info.height)
                    670:                                return true;
                    671:                }
                    672:        }
                    673: 
                    674:        return false;
                    675:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    676: }
                    677: 
                    678: static void measure_tiff(const String& origin_string, Measure_reader& reader, Measure_info &info) {
                    679:        const char* buf;
                    680: 
                    681:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    682:                throw Exception(IMAGE_FORMAT, &origin_string, "not TIFF file - too small");
                    683: 
                    684:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    685: 
                    686:        if(strncmp(head->byte_align_identifier, "II", 2)!=0 && strncmp(head->byte_align_identifier, "MM", 2)!=0)
                    687:                throw Exception(IMAGE_FORMAT, &origin_string, "not TIFF file - wrong signature");
                    688: 
                    689:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    690: 
                    691:        if(endian_to_ushort(is_big, head->signature) != 42)
                    692:                throw Exception(IMAGE_FORMAT, &origin_string, "not TIFF file - wrong signature");
                    693: 
1.174     moko      694:        reader.seek(endian_to_uint(is_big, head->first_IFD_offset));
1.165     moko      695:        if(!parse_tiff_IFD(is_big, reader, info))
                    696:                throw Exception(IMAGE_FORMAT, &origin_string, "broken TIFF file - size field entry not found");
                    697: }
                    698: 
1.169     moko      699: 
                    700: ///*********************************************** GIF
                    701: 
                    702: struct GIF_Header {
                    703:        char    signature[3];   // 'GIF'
                    704:        char    version[3];
                    705:        uchar   width[2];
                    706:        uchar   height[2];
                    707:        char    dif;
                    708:        char    fonColor;
                    709:        char    nulls;
                    710: };
                    711: 
1.164     moko      712: static void measure_gif(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    713: 
                    714:        const char* buf;
                    715:        const size_t head_size=sizeof(GIF_Header);
                    716:        if(reader.read(buf, head_size)<head_size)
                    717:                throw Exception(IMAGE_FORMAT, &origin_string, "not GIF file - too small");
                    718:        GIF_Header *head=(GIF_Header *)buf;
                    719: 
                    720:        if(strncmp(head->signature, "GIF", 3)!=0)
                    721:                throw Exception(IMAGE_FORMAT, &origin_string, "not GIF file - wrong signature");
                    722: 
                    723:        width=endian_to_ushort(false, head->width);
                    724:        height=endian_to_ushort(false, head->height);
                    725: }
                    726: 
1.169     moko      727: 
                    728: ///*********************************************** PNG
                    729: 
                    730: struct PNG_Header {
                    731:        char    dummy[12];
                    732:        char    signature[4];   //< must be "IHDR"
                    733:        uchar   high_width[2];  //< image width high bytes [we ignore for now]
                    734:        uchar   width[2];       //< image width low bytes
                    735:        uchar   high_height[2]; //< image height high bytes [we ignore for now]
                    736:        uchar   height[4];      //< image height
                    737: };
                    738: 
1.152     moko      739: static void measure_png(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
1.72      paf       740: 
1.91      paf       741:        const char* buf;
1.102     paf       742:        const size_t head_size=sizeof(PNG_Header);
                    743:        if(reader.read(buf, head_size)<head_size)
1.152     moko      744:                throw Exception(IMAGE_FORMAT, &origin_string, "not PNG file - too small");
1.72      paf       745:        PNG_Header *head=(PNG_Header *)buf;
                    746: 
                    747:        if(strncmp(head->signature, "IHDR", 4)!=0)
1.152     moko      748:                throw Exception(IMAGE_FORMAT, &origin_string, "not PNG file - wrong signature");
1.72      paf       749: 
1.80      paf       750:        width=endian_to_ushort(true, head->width);
                    751:        height=endian_to_ushort(true, head->height);
1.72      paf       752: }
                    753: 
1.169     moko      754: 
                    755: ///*********************************************** BMP
                    756: 
                    757: struct BMP_Header {
                    758:        char    signature[2];   // 'BM'
                    759:        uchar   file_size[4];
                    760:        uchar   reserved[4];
                    761:        uchar   bitmap_offset[4];
                    762:        uchar   header_size[4];
                    763:        uchar   width[2];
                    764:        uchar   high_width[2];  //< image width high bytes [we ignore for now]
                    765:        uchar   height[2];
                    766:        uchar   high_height[2]; //< image height high bytes [we ignore for now]
                    767: };
                    768: 
1.164     moko      769: static void measure_bmp(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    770: 
                    771:        const char* buf;
                    772:        const size_t head_size=sizeof(BMP_Header);
                    773:        if(reader.read(buf, head_size)<head_size)
                    774:                throw Exception(IMAGE_FORMAT, &origin_string, "not BMP file - too small");
                    775:        BMP_Header *head=(BMP_Header *)buf;
                    776: 
                    777:        if(strncmp(head->signature, "BM", 2)!=0)
                    778:                throw Exception(IMAGE_FORMAT, &origin_string, "not BMP file - wrong signature");
                    779: 
1.174     moko      780:        if((uint)reader.length() != endian_to_uint(false, head->file_size))
1.164     moko      781:                throw Exception(IMAGE_FORMAT, &origin_string, "not BMP file - length header and file size do not match");
                    782: 
                    783:        width=endian_to_ushort(false, head->width);
                    784:        height=endian_to_ushort(false, head->height);
                    785: }
                    786: 
1.168     moko      787: 
1.169     moko      788: ///*********************************************** WEBP
                    789: 
                    790: struct WEBP_Header {
                    791:        char signature_riff[4]; // 'RIFF'
                    792:        uchar file_size[4];
                    793:        char signature[4];      // 'WEBP'
                    794:        char format[4];         // 'VP8 ' or 'VP8L' or 'VP8X'
                    795: };
                    796: 
                    797: struct WEBP_VP8_Chunk {
                    798:        uchar size[4];
                    799:        char tag[3];
                    800:        uchar signature[3];    // 0x9D 0x01 0x2A
                    801:        uchar width[2];        // 14 bits each
                    802:        uchar height[2];       // 14 bits each
                    803: };
                    804: 
                    805: struct WEBP_VP8L_Chunk {
                    806:        uchar size[4];
                    807:        char signature;        // 0x2F
                    808:        uchar width_height[4]; // 14 bits each
                    809: };
                    810: 
                    811: struct WEBP_X_Chunk {
                    812:        uchar size[4];
                    813:        char reserved[4];
                    814:        uchar width[3];
                    815:        uchar height[3];
                    816: };
                    817: 
1.168     moko      818: static void measure_webp(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    819:        const char* buf;
                    820: 
                    821:        if(reader.read(buf, sizeof(WEBP_Header))<sizeof(WEBP_Header))
                    822:                throw Exception(IMAGE_FORMAT, &origin_string, "not WEBP file - too small");
                    823: 
                    824:        WEBP_Header *head=(WEBP_Header *)buf;
                    825: 
                    826:        if(strncmp(head->signature_riff, "RIFF", 4)!=0 || strncmp(head->signature, "WEBP", 4)!=0)
                    827:                throw Exception(IMAGE_FORMAT, &origin_string, "not WEBP file - wrong signature");
                    828: 
                    829:        if(strncmp(head->format, "VP8 ", 4)==0){
                    830:                if(reader.read(buf, sizeof(WEBP_VP8_Chunk))<sizeof(WEBP_VP8_Chunk))
                    831:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - too small VP8 chunk");
                    832: 
                    833:                WEBP_VP8_Chunk *chunk=(WEBP_VP8_Chunk *)buf;
                    834:                if (chunk->signature[0] != 0x9D || chunk->signature[1] != 0x01 || chunk->signature[2] != 0x2A)
                    835:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - wrong VP8 chunk signature");
                    836: 
                    837:                width=endian_to_ushort(false, chunk->width) & 0x3FFF;
                    838:                height=endian_to_ushort(false, chunk->height) & 0x3FFF;
                    839:        } else if(strncmp(head->format, "VP8L", 4)==0){
                    840:                if(reader.read(buf, sizeof(WEBP_VP8L_Chunk))<sizeof(WEBP_VP8L_Chunk))
                    841:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - too small VP8L chunk");
                    842: 
                    843:                WEBP_VP8L_Chunk *chunk=(WEBP_VP8L_Chunk *)buf;
                    844:                if(chunk->signature != 0x2F)
                    845:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - wrong VP8L chunk signature");
                    846: 
                    847:                uint wh=endian_to_uint(false, chunk->width_height);
                    848:                width=(wh & 0x3FFF) + 1;
                    849:                height=((wh >> 14) & 0x3FFF) + 1;
                    850:        } else if (strncmp(head->format, "VP8X", 4)==0){
                    851:                if(reader.read(buf, sizeof(WEBP_X_Chunk))<sizeof(WEBP_X_Chunk))
                    852:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - too small VP8X chunk");
                    853: 
                    854:                WEBP_X_Chunk *chunk=(WEBP_X_Chunk *)buf;
                    855: 
                    856:                width=endian_to_ushort(false, chunk->width) + 1;   // we ignore third byte to simplify code
                    857:                height=endian_to_ushort(false, chunk->height) + 1; // we ignore third byte to simplify code
                    858:        } else throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - invalid chunk signature");
                    859: }
                    860: 
1.170     moko      861: 
                    862: ///*********************************************** MP4
                    863: 
                    864: struct MP4_Header {
                    865:        uchar size[4];
                    866:        char signature[4];   // 'ftyp' in first chunk
                    867: };
                    868: 
1.173     moko      869: struct MP4_ExtSize {
                    870:        uchar high[4];
                    871:        uchar low[4];
                    872: };
                    873: 
                    874: struct MP4_Tkhd {
                    875:        uchar width[4];
                    876:        uchar height[4];
                    877: };
                    878: 
1.174     moko      879: static bool measure_mp4(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height, uint64_t anext, const char* lastTkhd=NULL) {
1.170     moko      880:        for(bool first=anext==0;;){
                    881:                const char* buf;
1.174     moko      882:                uint64_t next=reader.tell();
1.173     moko      883: 
                    884:                if(reader.read(buf, sizeof(MP4_Header))<sizeof(MP4_Header))
1.172     moko      885:                        throw Exception(IMAGE_FORMAT, &origin_string, first ? "not MP4 file - too small" : "broken MP4 file - truncated chunk header");
1.170     moko      886: 
                    887:                MP4_Header *head=(MP4_Header *)buf;
1.174     moko      888:                uint64_t size=endian_to_uint(true, head->size);
1.170     moko      889: 
1.173     moko      890:                if(size==1){
                    891:                        if(reader.read(buf, sizeof(MP4_ExtSize))<sizeof(MP4_ExtSize))
                    892:                                throw Exception(IMAGE_FORMAT, &origin_string, "broken MP4 file - truncated chunk extended size header");
                    893:                        MP4_ExtSize *ext_size=(MP4_ExtSize *)buf;
1.174     moko      894:                        size=((uint64_t)endian_to_uint(true, ext_size->high) << 32) + endian_to_uint(true, ext_size->low);
1.173     moko      895:                }
                    896:                next+=size;
1.170     moko      897: 
                    898:                if(first){
                    899:                        if(strncmp(head->signature, "ftyp", 4)!=0)
                    900:                                throw Exception(IMAGE_FORMAT, &origin_string, "not MP4 file - wrong signature");
                    901:                        first=false;
1.174     moko      902:                        anext=reader.length(); // to avoid reading beyond EOF
1.170     moko      903:                } else if(strncmp(head->signature, "moov", 4)==0 || strncmp(head->signature, "mdia", 4)==0 || strncmp(head->signature, "trak", 4)==0) {
                    904:                        if(measure_mp4(origin_string, reader, width, height, next, lastTkhd))
                    905:                                return true;
                    906:                } else if(strncmp(head->signature, "tkhd", 4)==0) {
                    907:                        if(size>8){
1.174     moko      908:                                reader.seek(next-8);
1.173     moko      909:                                if(reader.read(lastTkhd, sizeof(MP4_Tkhd))<sizeof(MP4_Tkhd))
1.170     moko      910:                                        throw Exception(IMAGE_FORMAT, &origin_string, "broken MP4 file - bad tkhd chunk");
                    911:                        }
                    912:                } else if (strncmp(head->signature, "hdlr", 4)==0) {
                    913:                        if(size>12){
                    914:                                const char* hdlr;
                    915:                                if(reader.read(hdlr, 12)<12)
                    916:                                        throw Exception(IMAGE_FORMAT, &origin_string, "broken MP4 file - bad hdlr chunk");
1.173     moko      917:                                if(lastTkhd && strncmp(hdlr+8, "vide", 4)==0) {
                    918:                                        MP4_Tkhd *tkhd=(MP4_Tkhd *)lastTkhd;
                    919:                                        width=endian_to_ushort(true, tkhd->width);
                    920:                                        height=endian_to_ushort(true, tkhd->height);
1.170     moko      921:                                        return true;
                    922:                                }
                    923:                        }
                    924:                }
                    925:                if(anext && next>=anext)
                    926:                        break;
1.174     moko      927:                reader.seek(next);
1.170     moko      928:        }
                    929:        return false;
                    930: }
                    931: 
                    932: static void measure_mp4(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    933:        if(!measure_mp4(origin_string, reader, width, height, 0))
                    934:                throw Exception(IMAGE_FORMAT, &origin_string, "unsupported MP4 file - size not found");
                    935: }
                    936: 
1.169     moko      937: ///*********************************************** measure center
1.1       paf       938: 
1.162     moko      939: static void measure(const String& file_name, Measure_reader& reader, Measure_info &info) {
1.128     misha     940:        const char* file_name_cstr=file_name.taint_cstr(String::L_FILE_SPEC);
1.91      paf       941:        if(const char* cext=strrchr(file_name_cstr, '.')) {
1.1       paf       942:                cext++;
                    943:                if(strcasecmp(cext, "GIF")==0)
1.162     moko      944:                        measure_gif(file_name, reader, info.width, info.height);
1.165     moko      945:                else if(strcasecmp(cext, "JPG")==0 || strcasecmp(cext, "JPEG")==0)
1.162     moko      946:                        measure_jpeg(file_name, reader, info);
1.72      paf       947:                else if(strcasecmp(cext, "PNG")==0)
1.162     moko      948:                        measure_png(file_name, reader, info.width, info.height);
1.164     moko      949:                else if(strcasecmp(cext, "BMP")==0)
                    950:                        measure_bmp(file_name, reader, info.width, info.height);
1.168     moko      951:                else if(strcasecmp(cext, "WEBP")==0)
                    952:                        measure_webp(file_name, reader, info.width, info.height);
1.165     moko      953:                else if(strcasecmp(cext, "TIF")==0 || strcasecmp(cext, "TIFF")==0)
                    954:                        measure_tiff(file_name, reader, info);
1.171     moko      955:                else if(strcasecmp(cext, "MP4")==0 || strcasecmp(cext, "MOV")==0)
1.181     moko      956:                        if(info.video)
                    957:                                measure_mp4(file_name, reader, info.width, info.height);
                    958:                        else
                    959:                                throw Exception(IMAGE_FORMAT, &file_name, "handling disabled for file name extension '%s'", cext);
1.1       paf       960:                else
1.181     moko      961:                        throw Exception(IMAGE_FORMAT, &file_name, "unhandled file name extension '%s'", cext);
1.1       paf       962:        } else
1.181     moko      963:                throw Exception(IMAGE_FORMAT, &file_name, "can not determine file type - no file name extension");
1.1       paf       964: }
                    965: 
1.77      paf       966: // methods
1.1       paf       967: 
1.152     moko      968: static void file_measure_action(struct stat& /*finfo*/, int f, const String& file_spec, void *context) {
                    969:        Measure_file_reader reader(f, file_spec);
1.162     moko      970:        measure(file_spec, reader, *static_cast<Measure_info *>(context));
1.1       paf       971: }
                    972: 
1.91      paf       973: static void _measure(Request& r, MethodParams& params) {
                    974:        Value& data=params.as_no_junction(0, "data must not be code");
1.1       paf       975: 
1.91      paf       976:        Value* exif=0;
1.162     moko      977:        Value* xmp=0;
1.181     moko      978:        Measure_info info={ 0, 0, 0, 0, &pa_UTF8_charset, false };
1.163     moko      979: 
                    980:        if(params.count()>1)
                    981:                if(HashStringValue* options=params.as_hash(1, "methods options")) {
                    982:                        int valid_options=0;
                    983:                        for(HashStringValue::Iterator i(*options); i; i.next() ){
                    984:                                String::Body key=i.key();
                    985:                                Value* value=i.value();
                    986:                                if(key == "exif") {
                    987:                                        if(r.process(*value).as_bool())
                    988:                                                info.exif=&exif;
                    989:                                        valid_options++;
                    990:                                }
                    991:                                if(key == "xmp") {
                    992:                                        if(r.process(*value).as_bool())
                    993:                                                info.xmp=&xmp;
                    994:                                        valid_options++;
                    995:                                }
                    996:                                if(key == "xmp-charset") {
                    997:                                        info.xmp_charset=&pa_charsets.get(value->as_string());
                    998:                                        valid_options++;
                    999:                                }
1.181     moko     1000:                                if(key == "video") {
                   1001:                                        info.video=r.process(*value).as_bool();
                   1002:                                        valid_options++;
                   1003:                                }
1.163     moko     1004:                        }
                   1005:                        if(valid_options!=options->count())
                   1006:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                   1007:                }
1.162     moko     1008: 
1.91      paf      1009:        const String* file_name;
1.162     moko     1010: 
                   1011:        if(file_name=data.get_string()) {
1.167     moko     1012:                file_read_action_under_lock(r.full_disk_path(*file_name), "measure", file_measure_action, &info);
1.1       paf      1013:        } else {
1.182     moko     1014:                VFile* vfile=data.as_vfile();
1.91      paf      1015:                file_name=&vfile->fields().get(name_name)->as_string();
1.162     moko     1016:                Measure_buf_reader reader(vfile->value_ptr(), vfile->value_size(), *file_name);
                   1017:                measure(*file_name, reader, info);
1.1       paf      1018:        }
                   1019: 
1.162     moko     1020:        GET_SELF(r, VImage).set(file_name, info.width, info.height, 0, exif, xmp);
1.1       paf      1021: }
                   1022: 
1.161     moko     1023: static void append_attrib_pair(String &tag, String::Body key, Value* value){
                   1024:        // skip border attribute with empty value
                   1025:        if(key=="border" && !value->is_defined())
1.4       paf      1026:                return;
                   1027: 
1.133     misha    1028:        // src="a.gif" width="123" ismap[=-1]
1.161     moko     1029:        tag << " " << key;
1.91      paf      1030:        if(value->is_string() || value->as_int()>=0)
1.161     moko     1031:                tag << "=\"" << value->as_string() << "\"";
1.3       paf      1032: }
1.161     moko     1033: 
1.91      paf      1034: static void _html(Request& r, MethodParams& params) {
                   1035:        String tag;
1.3       paf      1036:        tag << "<img";
1.4       paf      1037: 
1.91      paf      1038:        const HashStringValue& fields=GET_SELF(r, VImage).fields();
                   1039:        HashStringValue* attribs=0;
1.4       paf      1040: 
1.91      paf      1041:        if(params.count()) {
1.69      paf      1042:                // for backward compatibility: someday was ^html{}
1.154     moko     1043:                Value& vattribs=r.process(params[0]);
1.145     moko     1044:                if(!vattribs.is_string()) { // allow empty
1.100     paf      1045:                        if((attribs=vattribs.get_hash())) {
1.161     moko     1046:                                for(HashStringValue::Iterator i(*attribs); i; i.next() )
                   1047:                                        append_attrib_pair(tag, i.key(), i.value());
1.39      parser   1048:                        } else
1.155     moko     1049:                                throw Exception(PARSER_RUNTIME, 0, "attributes must be hash");
1.145     moko     1050:                }
1.39      parser   1051:        }
1.4       paf      1052: 
1.161     moko     1053:        for(HashStringValue::Iterator i(fields); i; i.next() ){
                   1054:                String::Body key=i.key();
                   1055:                // skip user-specified attributes
                   1056:                if(attribs && attribs->get(key))
                   1057:                        continue;
                   1058:                // allow only html attributes (to exclude exif, line-*)
                   1059:                if(key=="src" || key=="width" || key=="height" || key=="border")
                   1060:                        append_attrib_pair(tag, key, i.value());
1.91      paf      1061:        }
1.161     moko     1062: 
1.6       paf      1063:        tag << " />";
1.157     moko     1064:        r.write(tag);
1.3       paf      1065: }
1.8       paf      1066: 
1.68      paf      1067: /// @test wrap FILE to auto-object
1.155     moko     1068: static gdImage* load(Request& r, const String& file_name){
1.167     moko     1069:        const char* file_name_cstr=r.full_disk_path(file_name).taint_cstr(String::L_FILE_SPEC);
1.159     moko     1070:        if(FILE *f=pa_fopen(file_name_cstr, "rb")) {
1.91      paf      1071:                gdImage* image=new gdImage;
                   1072:                bool ok=image->CreateFromGif(f);
1.16      paf      1073:                fclose(f);
1.23      paf      1074:                if(!ok)
1.155     moko     1075:                        throw Exception(IMAGE_FORMAT, &file_name, "is not in GIF format");
1.91      paf      1076:                return image;
1.16      paf      1077:        } else {
1.155     moko     1078:                throw Exception("file.missing", 0, "can not open '%s'", file_name_cstr);
1.16      paf      1079:        }
                   1080: }
                   1081: 
                   1082: 
1.91      paf      1083: static void _load(Request& r, MethodParams& params) {
1.116     misha    1084:        const String& file_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.6       paf      1085: 
1.91      paf      1086:        gdImage* image=load(r, file_name);
                   1087:        GET_SELF(r, VImage).set(&file_name, image->SX(), image->SY(), image);
1.6       paf      1088: }
                   1089: 
1.91      paf      1090: static void _create(Request& r, MethodParams& params) {
                   1091:        int width=params.as_int(0, "width must be int", r);
                   1092:        int height=params.as_int(1, "height must be int", r);
1.8       paf      1093:        int bgcolor_value=0xffFFff;
1.91      paf      1094:        if(params.count()>2)
                   1095:                bgcolor_value=params.as_int(2, "color must be int", r);
                   1096:        gdImage* image=new gdImage;
                   1097:        image->Create(width, height);
                   1098:        image->FilledRectangle(0, 0, width-1, height-1, image->Color(bgcolor_value));
                   1099:        GET_SELF(r, VImage).set(0, width, height, image);
1.6       paf      1100: }
                   1101: 
1.91      paf      1102: static void _gif(Request& r, MethodParams& params) {
1.108     paf      1103:        gdImage& image=GET_SELF(r, VImage).image();
1.6       paf      1104: 
1.138     misha    1105:        const String *file_name=params.count()>0?&params.as_string(0, FILE_NAME_MUST_BE_STRING):0;
1.10      paf      1106: 
1.108     paf      1107:        gdBuf buf=image.Gif();
1.6       paf      1108:        
1.91      paf      1109:        VFile& vfile=*new VFile;
1.137     misha    1110: 
1.142     moko     1111:        vfile.set_binary(false/*not tainted*/, (const char *)buf.ptr, buf.size, file_name, new VString(*new String("image/gif")));
1.137     misha    1112: 
1.157     moko     1113:        r.write(vfile);
1.6       paf      1114: }
                   1115: 
1.91      paf      1116: static void _line(Request& r, MethodParams& params) {
1.108     paf      1117:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf      1118: 
1.108     paf      1119:        image.Line(
1.91      paf      1120:                params.as_int(0, "x0 must be int", r), 
                   1121:                params.as_int(1, "y0 must be int", r), 
                   1122:                params.as_int(2, "x1 must be int", r), 
                   1123:                params.as_int(3, "y1 must be int", r), 
1.108     paf      1124:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf      1125: }
                   1126: 
1.91      paf      1127: static void _fill(Request& r, MethodParams& params) {
1.108     paf      1128:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf      1129: 
1.108     paf      1130:        image.Fill(
1.91      paf      1131:                params.as_int(0, "x must be int", r), 
                   1132:                params.as_int(1, "y must be int", r), 
1.108     paf      1133:                image.Color(params.as_int(2, "color must be int", r)));
1.13      paf      1134: }
                   1135: 
1.91      paf      1136: static void _rectangle(Request& r, MethodParams& params) {
1.108     paf      1137:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1138: 
1.108     paf      1139:        image.Rectangle(
1.91      paf      1140:                params.as_int(0, "x0 must be int", r), 
                   1141:                params.as_int(1, "y0 must be int", r), 
                   1142:                params.as_int(2, "x1 must be int", r), 
                   1143:                params.as_int(3, "y1 must be int", r), 
1.108     paf      1144:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf      1145: }
                   1146: 
1.91      paf      1147: static void _bar(Request& r, MethodParams& params) {
1.108     paf      1148:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1149: 
1.108     paf      1150:        image.FilledRectangle(
1.91      paf      1151:                params.as_int(0, "x0 must be int", r), 
                   1152:                params.as_int(1, "y0 must be int", r), 
                   1153:                params.as_int(2, "x1 must be int", r), 
                   1154:                params.as_int(3, "y1 must be int", r), 
1.108     paf      1155:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf      1156: }
                   1157: 
1.44      parser   1158: #ifndef DOXYGEN
1.155     moko     1159: static void add_point(Table::element_type row, gdImage::Point **p) {
1.110     paf      1160:        if(row->count()!=2)
1.155     moko     1161:                throw Exception(0, 0, "coordinates table must contain two columns: x and y values");
1.91      paf      1162:        (**p).x=row->get(0)->as_int();
                   1163:        (**p).y=row->get(1)->as_int();
1.44      parser   1164:        (*p)++;
                   1165: }
                   1166: #endif
1.135     misha    1167: #ifndef DOXYGEN
1.155     moko     1168: static void add_point(int x, int y, gdImage::Point **p) {
1.135     misha    1169:        (**p).x=x;
                   1170:        (**p).y=y;
                   1171:        (*p)++;
                   1172: }
                   1173: #endif
1.91      paf      1174: static void _replace(Request& r, MethodParams& params) {
1.135     misha    1175:        int src_color=params.as_int(0, "src color must be int", r);
                   1176:        int dest_color=params.as_int(1, "dest color must be int", r);
                   1177: 
1.108     paf      1178:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1179: 
1.135     misha    1180:        gdImage::Point* all_p=0;
                   1181:        size_t count=0;
                   1182:        if(params.count() == 3){
1.180     moko     1183:                if(Table* table=params.as_table(2, "coordinates")){
                   1184:                        count=table->count();
                   1185:                        all_p=new(PointerFreeGC) gdImage::Point[count];
                   1186:                        gdImage::Point* add_p=all_p;
                   1187:                        table->for_each(add_point, &add_p);
                   1188:                }
1.135     misha    1189:        } else {
                   1190:                int max_x=image.SX()-1;
                   1191:                int max_y=image.SY()-1;
                   1192:                if(max_x > 0 && max_y > 0){
                   1193:                        count=4;
                   1194:                        all_p=new(PointerFreeGC) gdImage::Point[count];
                   1195:                        gdImage::Point* add_p=all_p;
                   1196:                        add_point(0, 0, &add_p);
                   1197:                        add_point(max_x, 0, &add_p);
                   1198:                        add_point(max_x, max_y, &add_p);
                   1199:                        add_point(0, max_y, &add_p);
                   1200:                }
                   1201:        }
1.13      paf      1202: 
1.135     misha    1203:        if(count)
                   1204:                image.FilledPolygonReplaceColor(all_p, count, image.Color(src_color), image.Color(dest_color));
1.13      paf      1205: }
                   1206: 
1.91      paf      1207: static void _polyline(Request& r, MethodParams& params) {
1.108     paf      1208:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1209: 
1.180     moko     1210:        if(Table* table=params.as_table(1, "coordinates")){
                   1211:                gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
                   1212:                gdImage::Point *add_p=all_p;
                   1213:                table->for_each(add_point, &add_p);
                   1214:                image.Polygon(all_p, table->count(), image.Color(params.as_int(0, "color must be int", r)), false/*not closed*/);
                   1215:        }
1.44      parser   1216: }
                   1217: 
1.91      paf      1218: static void _polygon(Request& r, MethodParams& params) {
1.108     paf      1219:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1220: 
1.180     moko     1221:        if(Table* table=(Table*)params.as_table(1, "coordinates")){
                   1222:                gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
                   1223:                gdImage::Point *add_p=all_p;
                   1224:                table->for_each(add_point, &add_p);
                   1225:                image.Polygon(all_p, table->count(), image.Color(params.as_int(0, "color must be int", r)));
                   1226:        }
1.13      paf      1227: }
                   1228: 
1.91      paf      1229: static void _polybar(Request& r, MethodParams& params) {
1.108     paf      1230:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1231: 
1.180     moko     1232:        if(Table* table=(Table*)params.as_table(1, "coordinates")){
                   1233:                gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
                   1234:                gdImage::Point *add_p=all_p;
                   1235:                table->for_each(add_point, &add_p);
                   1236:                image.FilledPolygon(all_p, table->count(), image.Color(params.as_int(0, "color must be int", r)));
                   1237:        }
1.12      paf      1238: }
                   1239: 
1.16      paf      1240: // font
                   1241: 
1.85      paf      1242: #define Y(y)(y+index*height)
1.21      paf      1243: 
1.91      paf      1244: // Font class
                   1245: 
1.155     moko     1246: Font::Font(Charset& asource_charset, const String& aalphabet, gdImage* aifont, int aheight, int amonospace, int aspacebarspace, int aletterspacing):
1.158     moko     1247:        letterspacing(aletterspacing),
1.132     misha    1248:        height(aheight),
                   1249:        monospace(amonospace),
                   1250:        spacebarspace(aspacebarspace),
1.100     paf      1251:        ifont(aifont),
1.158     moko     1252:        alphabet(aalphabet),
                   1253:        fsource_charset(asource_charset){
1.132     misha    1254: 
                   1255:        if(fsource_charset.isUTF8()){
                   1256:                size_t index=0;
                   1257:                for(UTF8_string_iterator i(alphabet); i.has_next(); )
                   1258:                        fletter2index.put_dont_replace(i.next(), index++);
                   1259:        }
1.91      paf      1260: }
                   1261: 
                   1262: /* ******************************** char ********************************** */
                   1263: 
                   1264: size_t Font::index_of(char ch) {
                   1265:        if(ch==' ') return STRING_NOT_FOUND;
                   1266:        return alphabet.pos(ch);
                   1267: }
                   1268: 
1.132     misha    1269: size_t Font::index_of(XMLCh ch) {
                   1270:        if(ch==' ') return STRING_NOT_FOUND;
                   1271:        return fletter2index.get(ch);
                   1272: }
                   1273: 
1.91      paf      1274: int Font::index_width(size_t index) {
                   1275:        if(index==STRING_NOT_FOUND)
                   1276:                return spacebarspace;
                   1277:        int tr=ifont->GetTransparent();
                   1278:        for(int x=ifont->SX()-1; x>=0; x--) {
                   1279:                for(int y=0; y<height; y++)
                   1280:                        if(ifont->GetPixel(x, Y(y))!=tr) 
                   1281:                                return x+1;
1.16      paf      1282:        }
1.91      paf      1283:        return 0;
                   1284: }
                   1285: 
1.108     paf      1286: void Font::index_display(gdImage& image, int x, int y, size_t index){
1.91      paf      1287:        if(index!=STRING_NOT_FOUND) 
1.108     paf      1288:                ifont->Copy(image, x, y, 0, Y(0), index_width(index), height);
1.91      paf      1289: }
                   1290: 
                   1291: /* ******************************** string ********************************** */
                   1292: 
                   1293: int Font::step_width(int index) {
1.125     misha    1294:        return letterspacing + (monospace ? monospace : index_width(index));
1.91      paf      1295: }
                   1296: 
                   1297: // counts trailing letter_spacing, consider this OK. useful for contiuations
                   1298: int Font::string_width(const String& s){
                   1299:        const char* cstr=s.cstr();
                   1300:        int result=0;
1.132     misha    1301: 
                   1302:        if(fsource_charset.isUTF8()){
                   1303:                for(UTF8_string_iterator i(s); i.has_next(); )
                   1304:                        result+=step_width(index_of(i.next()));
                   1305:        } else {
                   1306:                for(const char* current=cstr; *current; current++)
                   1307:                        result+=step_width(index_of(*current));
                   1308:        }
                   1309: 
1.91      paf      1310:        return result;
                   1311: }
                   1312: 
1.108     paf      1313: void Font::string_display(gdImage& image, int x, int y, const String& s){
1.91      paf      1314:        const char* cstr=s.cstr();
1.132     misha    1315: 
                   1316:        if(fsource_charset.isUTF8()){
                   1317:                for(UTF8_string_iterator i(s); i.has_next(); ){
                   1318:                        size_t index=index_of(i.next());
                   1319:                        index_display(image, x, y, index);
                   1320:                        x+=step_width(index);
                   1321:                }
                   1322:        } else {
                   1323:                for(const char* current=cstr; *current; current++) {
                   1324:                        size_t index=index_of(*current);
                   1325:                        index_display(image, x, y, index);
                   1326:                        x+=step_width(index);
                   1327:                }
1.87      paf      1328:        }
1.91      paf      1329: }
1.87      paf      1330: 
1.91      paf      1331: //
1.35      parser   1332: 
1.16      paf      1333: 
1.91      paf      1334: static void _font(Request& r, MethodParams& params) {
                   1335:        const String& alphabet=params.as_string(0, "alphabet must not be code");
1.131     misha    1336:        size_t alphabet_length=alphabet.length(r.charsets.source());
                   1337:        if(!alphabet_length)
1.155     moko     1338:                throw Exception(PARSER_RUNTIME, 0, "alphabet must not be empty");
1.84      paf      1339: 
1.125     misha    1340:        gdImage* image=load(r, params.as_string(1, FILE_NAME_MUST_NOT_BE_CODE));
                   1341: 
1.126     misha    1342:        int spacebar_width=image->SX();
1.125     misha    1343:        int monospace_width=0; // proportional
                   1344:        int letter_spacing=1;
                   1345:        if(params.count()>2){
1.144     moko     1346:                if(HashStringValue* options=params[2].get_hash()){
1.125     misha    1347:                        // third option is hash
                   1348:                        if(params.count()>3)
1.144     moko     1349:                                throw Exception(PARSER_RUNTIME, 0, "too many params were specified");
1.125     misha    1350:                        int valid_options=0;
                   1351:                        if(Value* vspacebar_width=options->get(spacebar_width_name)){
                   1352:                                valid_options++;
1.153     moko     1353:                                spacebar_width=r.process(*vspacebar_width).as_int();
1.125     misha    1354:                        }
                   1355:                        if(Value* vmonospace_width=options->get(monospace_width_name)){
                   1356:                                valid_options++;
1.153     moko     1357:                                monospace_width=r.process(*vmonospace_width).as_int();
1.125     misha    1358:                                if(!monospace_width)
                   1359:                                        monospace_width=image->SX();
                   1360:                        }
                   1361:                        if(Value* vletter_spacing=options->get(letter_spacing_name)){
                   1362:                                valid_options++;
1.153     moko     1363:                                letter_spacing=r.process(*vletter_spacing).as_int();
1.125     misha    1364:                        }
                   1365:                        if(valid_options!=options->count())
1.134     misha    1366:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.125     misha    1367:                } else {
                   1368:                        // backward
1.144     moko     1369:                        spacebar_width=params.as_int(2, "param must be int or hash", r);
1.125     misha    1370:                        if(params.count()>3) {
                   1371:                                monospace_width=params.as_int(3, "monospace_width must be int", r);
                   1372:                                if(!monospace_width)
                   1373:                                        monospace_width=image->SX();
                   1374:                        }
                   1375:                }
                   1376:        }
                   1377: 
1.131     misha    1378:        if(int remainder=image->SY() % alphabet_length)
1.155     moko     1379:                throw Exception(PARSER_RUNTIME, 0, "font-file height(%d) not divisable by alphabet size(%d), remainder=%d", image->SY(), alphabet_length, remainder);
1.37      parser   1380:        
1.155     moko     1381:        GET_SELF(r, VImage).set_font(new Font(r.charsets.source(), alphabet, image, image->SY() / alphabet_length, monospace_width, spacebar_width, letter_spacing));
1.16      paf      1382: }
                   1383: 
1.91      paf      1384: static void _text(Request& r, MethodParams& params) {
                   1385:        int x=params.as_int(0, "x must be int", r);
                   1386:        int y=params.as_int(1, "y must be int", r);
                   1387:        const String& s=params.as_string(2, "text must not be code");
1.16      paf      1388: 
1.91      paf      1389:        VImage& vimage=GET_SELF(r, VImage);
1.108     paf      1390:        vimage.font().string_display(vimage.image(), x, y, s);
1.16      paf      1391: }
                   1392: 
1.91      paf      1393: static void _length(Request& r, MethodParams& params) {
                   1394:        const String& s=params.as_string(0, "text must not be code");
1.47      parser   1395: 
1.91      paf      1396:        VImage& vimage=GET_SELF(r, VImage);
1.157     moko     1397:        r.write(*new VInt(vimage.font().string_width(s)));
1.47      parser   1398: }
                   1399: 
1.91      paf      1400: static void _arc(Request& r, MethodParams& params) {
1.108     paf      1401:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1402: 
1.108     paf      1403:        image.Arc(
1.91      paf      1404:                params.as_int(0, "center_x must be int", r), 
                   1405:                params.as_int(1, "center_y must be int", r), 
                   1406:                params.as_int(2, "width must be int", r), 
                   1407:                params.as_int(3, "height must be int", r), 
                   1408:                params.as_int(4, "start degrees must be int", r), 
                   1409:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1410:                image.Color(params.as_int(6, "cx must be int", r)));
1.48      parser   1411: }
                   1412: 
1.91      paf      1413: static void _sector(Request& r, MethodParams& params) {
1.108     paf      1414:        gdImage& image=GET_SELF(r, VImage).image();
1.49      parser   1415: 
1.108     paf      1416:        image.Sector(
1.91      paf      1417:                params.as_int(0, "center_x must be int", r), 
                   1418:                params.as_int(1, "center_y must be int", r), 
                   1419:                params.as_int(2, "width must be int", r), 
                   1420:                params.as_int(3, "height must be int", r), 
                   1421:                params.as_int(4, "start degrees must be int", r), 
                   1422:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1423:                image.Color(params.as_int(6, "color must be int", r)));
1.49      parser   1424: }
                   1425: 
1.91      paf      1426: static void _circle(Request& r, MethodParams& params) {
1.108     paf      1427:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1428: 
1.91      paf      1429:        int size=params.as_int(2, "radius must be int", r)*2;
1.108     paf      1430:        image.Arc(
1.91      paf      1431:                params.as_int(0, "center_x must be int", r), 
                   1432:                params.as_int(1, "center_y must be int", r), 
1.50      parser   1433:                size, //w
                   1434:                size, //h
1.48      parser   1435:                0, //s
                   1436:                360, //e
1.108     paf      1437:                image.Color(params.as_int(3, "color must be int", r)));
1.48      parser   1438: }
                   1439: 
1.108     paf      1440: gdImage& as_image(MethodParams& params, int index, const char* msg) {
1.91      paf      1441:        Value& value=params.as_no_junction(index, msg);
1.53      parser   1442: 
1.186   ! moko     1443:        if(VImage* vimage=dynamic_cast<VImage *>(&value)) {
        !          1444:                return vimage->image();
1.75      paf      1445:        } else
1.155     moko     1446:                throw Exception(PARSER_RUNTIME, 0, msg);
1.53      parser   1447: }
                   1448: 
1.91      paf      1449: static void _copy(Request& r, MethodParams& params) {
1.108     paf      1450:        gdImage& dest=GET_SELF(r, VImage).image();
1.53      parser   1451: 
1.108     paf      1452:        gdImage& src=as_image(params, 0, "src must be image");
1.53      parser   1453: 
1.91      paf      1454:        int sx=params.as_int(1, "src_x must be int", r);
                   1455:        int sy=params.as_int(2, "src_y must be int", r);
                   1456:        int sw=params.as_int(3, "src_w must be int", r);
                   1457:        int sh=params.as_int(4, "src_h must be int", r);
                   1458:        int dx=params.as_int(5, "dest_x must be int", r);
                   1459:        int dy=params.as_int(6, "dest_y must be int", r);
                   1460:        if(params.count()>1+2+2+2) {
                   1461:                int dw=params.as_int(1+2+2+2, "dest_w must be int", r);
                   1462:                int dh=(int)(params.count()>1+2+2+2+1?
                   1463:                        params.as_int(1+2+2+2+1, "dest_h must be int", r):sh*(((double)dw)/((double)sw)));
                   1464:                int tolerance=params.count()>1+2+2+2+2?
                   1465:                        params.as_int(1+2+2+2+2, "tolerance must be int", r):150;
1.53      parser   1466: 
1.108     paf      1467:                src.CopyResampled(dest, dx, dy, sx, sy, dw, dh, sw, sh, tolerance);
1.53      parser   1468:        } else
1.108     paf      1469:                src.Copy(dest, dx, dy, sx, sy, sw, sh);
                   1470: }
                   1471: 
                   1472: static void _pixel(Request& r, MethodParams& params) {
                   1473:        gdImage& image=GET_SELF(r, VImage).image();
                   1474: 
1.109     paf      1475:        int x=params.as_int(0, "x must be int", r); 
                   1476:        int y=params.as_int(1, "y must be int", r);
                   1477: 
                   1478:        if(params.count()>2) {
                   1479:                image.SetPixel(x, y, 
                   1480:                        image.Color(params.as_int(2, "color must be int", r)));
                   1481:        } else 
1.157     moko     1482:                r.write(*new VInt(image.DecodeColor(image.GetPixel(x, y))));
1.53      parser   1483: }
                   1484: 
                   1485: 
1.22      paf      1486: // constructor
                   1487: 
1.91      paf      1488: MImage::MImage(): Methoded("image") {
1.1       paf      1489:        // ^image:measure[DATA]
1.163     moko     1490:        // ^image:measure[DATA; $.exif(false) $.xmp(false) $.xmp-charset[UTF-8] ]
                   1491:        add_native_method("measure", Method::CT_DYNAMIC, _measure, 1, 2);
1.3       paf      1492: 
1.25      paf      1493:        // ^image.html[]
                   1494:        // ^image.html[hash]
1.22      paf      1495:        add_native_method("html", Method::CT_DYNAMIC, _html, 0, 1);
1.6       paf      1496: 
1.25      paf      1497:        // ^image.load[background.gif]
1.22      paf      1498:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 1);
1.6       paf      1499: 
1.25      paf      1500:        // ^image.create[width;height] bgcolor=white
                   1501:        // ^image.create[width;height;bgcolor]
1.22      paf      1502:        add_native_method("create", Method::CT_DYNAMIC, _create, 2, 3);
1.6       paf      1503: 
1.25      paf      1504:        // ^image.gif[]
1.95      paf      1505:        add_native_method("gif", Method::CT_DYNAMIC, _gif, 0, 1);
1.12      paf      1506: 
1.25      paf      1507:        // ^image.line(x0;y0;x1;y1;color)
1.22      paf      1508:        add_native_method("line", Method::CT_DYNAMIC, _line, 5, 5);
1.13      paf      1509: 
1.25      paf      1510:        // ^image.fill(x;y;color)
1.22      paf      1511:        add_native_method("fill", Method::CT_DYNAMIC, _fill, 3, 3);
1.13      paf      1512: 
1.25      paf      1513:        // ^image.rectangle(x0;y0;x1;y1;color)
1.22      paf      1514:        add_native_method("rectangle", Method::CT_DYNAMIC, _rectangle, 5, 5);
1.13      paf      1515: 
1.25      paf      1516:        // ^image.bar(x0;y0;x1;y1;color)
1.22      paf      1517:        add_native_method("bar", Method::CT_DYNAMIC, _bar, 5, 5);
1.13      paf      1518: 
1.44      parser   1519:        // ^image.replace(color-source;color-dest)[table x:y]
1.135     misha    1520:        // ^image.replace(color-source;color-dest)
                   1521:        add_native_method("replace", Method::CT_DYNAMIC, _replace, 2, 3);
1.44      parser   1522: 
                   1523:        // ^image.polyline(color)[table x:y]
                   1524:        add_native_method("polyline", Method::CT_DYNAMIC, _polyline, 2, 2);
1.13      paf      1525: 
1.44      parser   1526:        // ^image.polygon(color)[table x:y]
                   1527:        add_native_method("polygon", Method::CT_DYNAMIC, _polygon, 2, 2);
1.13      paf      1528: 
1.44      parser   1529:        // ^image.polybar(color)[table x:y]
                   1530:        add_native_method("polybar", Method::CT_DYNAMIC, _polybar, 2, 2);
1.13      paf      1531: 
1.125     misha    1532:        // ^image.font[alPHAbet;font-file-name.gif]
                   1533:        // ^image.font[alPHAbet;font-file-name.gif](spacebar_width)
                   1534:        // ^image.font[alPHAbet;font-file-name.gif](spacebar_width;letter_width)
                   1535:        // ^image.font[alPHAbet;font-file-name.gif][$.space-width(.) $.letter-width(.) $.letter-space(.)]
                   1536:        add_native_method("font", Method::CT_DYNAMIC, _font, 2, 4);
1.16      paf      1537: 
1.125     misha    1538:        // ^image.text(x;y)[text]
1.22      paf      1539:        add_native_method("text", Method::CT_DYNAMIC, _text, 3, 3);
1.47      parser   1540:        
1.125     misha    1541:        // ^image.length[text]
1.47      parser   1542:        add_native_method("length", Method::CT_DYNAMIC, _length, 1, 1);
1.16      paf      1543:        
1.48      parser   1544:        // ^image.arc(center x;center y;width;height;start in degrees;end in degrees;color)
                   1545:        add_native_method("arc", Method::CT_DYNAMIC, _arc, 7, 7);
1.49      parser   1546: 
                   1547:        // ^image.sector(center x;center y;width;height;start in degrees;end in degrees;color)
                   1548:        add_native_method("sector", Method::CT_DYNAMIC, _sector, 7, 7);
1.48      parser   1549: 
                   1550:        // ^image.circle(center x;center y;r;color)
                   1551:        add_native_method("circle", Method::CT_DYNAMIC, _circle, 4, 4);
                   1552: 
1.56      parser   1553:        // ^image.copy[source](src x;src y;src w;src h;dst x;dst y[;dest w[;dest h[;tolerance]]])
                   1554:        add_native_method("copy", Method::CT_DYNAMIC, _copy, 1+2+2+2, (1+2+2+2)+2+1);
1.108     paf      1555: 
                   1556:        // ^image.pixel(x;y)[(color)]
1.109     paf      1557:        add_native_method("pixel", Method::CT_DYNAMIC, _pixel, 2, 3);
1.1       paf      1558: }

E-mail: