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

1.1       paf         1: /** @file
                      2:        Parser: @b image parser class.
                      3: 
1.179   ! moko        4:        Copyright (c) 2001-2020 Art. Lebedev Studio (http://www.artlebedev.com)
1.66      paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://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.179   ! moko       29: volatile const char * IDENT_IMAGE_C="$Id: image.C,v 1.178 2020/12/07 23:18:40 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.72      paf       311: };
                    312: 
1.164     moko      313: 
1.169     moko      314: inline ushort x_endian_to_ushort(uchar b0, uchar b1) {
                    315:        return (ushort)((b1<<8) + b0);
                    316: }
                    317: 
                    318: inline uint x_endian_to_uint(uchar b0, uchar b1, uchar b2, uchar b3) {
                    319:        return (uint)(((((b3<<8) + b2)<<8)+b1)<<8)+b0;
                    320: }
                    321: 
                    322: inline ushort endian_to_ushort(bool is_big, const uchar *b/* [2] */) {
                    323:        return is_big ? x_endian_to_ushort(b[1], b[0]) : x_endian_to_ushort(b[0], b[1]);
                    324: }
                    325: 
                    326: inline uint endian_to_uint(bool is_big, const uchar *b /* [4] */) {
                    327:        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]);
                    328: }
1.1       paf       329: 
1.170     moko      330: 
1.169     moko      331: ///*********************************************** JPEG
1.170     moko      332: 
1.31      parser    333: struct JPG_Segment_head {
1.80      paf       334:        uchar marker;
                    335:        uchar code;
                    336:        uchar length[2];
1.1       paf       337: };
1.21      paf       338: /// JPEG frame header
1.31      parser    339: struct JPG_Size_segment_body {
1.164     moko      340:        char data;              //< data precision of bits/sample
                    341:        uchar height[2];        //< image height
                    342:        uchar width[2];         //< image width
                    343:        char numComponents;     //< number of color components
1.1       paf       344: };
                    345: 
1.80      paf       346: /// JPEG Exif TIFF Header
                    347: struct JPG_Exif_TIFF_header {
1.165     moko      348:        char byte_align_identifier[2];
                    349:        uchar signature[2]; // always 000A [or 0A00]
1.80      paf       350:        uchar first_IFD_offset[4]; // Usually the first IFD starts immediately next to TIFF header, so this offset has value '0x00000008'.
                    351: };
                    352: 
                    353: // JPEG Exif IFD start
1.91      paf       354: struct JPG_Exif_IFD_begin {
1.80      paf       355:        uchar directory_entry_count[2]; // the number of directory entry contains in this IFD
                    356: };
                    357: 
                    358: // TTTT ffff NNNNNNNN DDDDDDDD 
                    359: struct JPG_Exif_IFD_entry {
                    360:        uchar tag[2]; // Tag number, this shows a kind of data
                    361:        uchar format[2]; // data format
                    362:        uchar components_count[4]; // number of components
                    363:        uchar value_or_offset_to_it[4]; // data value or offset to data value
                    364: };
                    365: 
                    366: #define JPG_IFD_TAG_EXIF_OFFSET 0x8769
                    367: 
1.118     misha     368: #define JPG_IFD_TAG_EXIF_GPS_OFFSET 0x8825
                    369: 
1.89      paf       370: #define JPEG_EXIF_DATE_CHARS 20
                    371: 
1.155     moko      372: static Value* parse_IFD_entry_formatted_one_value(bool is_big, ushort format, size_t component_size, const uchar *value) {
1.80      paf       373:        switch(format) {
                    374:        case 1: // unsigned byte
1.91      paf       375:                return new VInt((uchar)value[0]);
1.80      paf       376:        case 3: // unsigned short
1.91      paf       377:                return new VInt(endian_to_ushort(is_big, value));
1.80      paf       378:        case 4: // unsigned long
                    379:                 // 'double' because parser's Int is signed
1.91      paf       380:                return new VDouble(endian_to_uint(is_big, value));
1.80      paf       381:        case 5: // unsigned rational
                    382:                {
                    383:                        uint numerator=endian_to_uint(is_big, value); value+=component_size/2;
                    384:                        uint denominator=endian_to_uint(is_big, value);
                    385:                        if(!denominator)
                    386:                                return 0;
1.91      paf       387:                        return new VDouble(((double)numerator)/denominator);
1.80      paf       388:                }
                    389:        case 6: // signed byte
1.91      paf       390:                return new VInt((signed char)value[0]);
1.80      paf       391:        case 8: // signed short
1.91      paf       392:                return new VInt((signed short)endian_to_ushort(is_big, value));
1.80      paf       393:        case 9: // signed long
1.91      paf       394:                return new VInt((signed int)endian_to_uint(is_big, value));
1.80      paf       395:        case 10: // signed rational
                    396:                {
                    397:                        signed int numerator=(signed int)endian_to_uint(is_big, value); value+=component_size/2;
                    398:                        uint denominator=endian_to_uint(is_big, value);
                    399:                        if(!denominator)
                    400:                                return 0;
1.91      paf       401:                        return new VDouble(numerator/denominator);
1.80      paf       402:                }
                    403:                /*
                    404:        case 11: // single float
1.120     misha     405:                @todo
1.80      paf       406:        case 12: // double float
1.120     misha     407:                @todo
1.80      paf       408:                */
                    409:        };      
                    410:        
                    411:        return 0;
                    412: }
                    413: 
1.89      paf       414: // date.C
1.147     moko      415: tm cstr_to_time_t(char *, const char **);
1.89      paf       416: 
1.155     moko      417: 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       418:        if(format==2) { // ascii string, exception: the only type with varying size
1.91      paf       419:                const char* cstr=(const char* )value;
                    420:                size_t length=components_count;
1.89      paf       421:                // Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes
1.155     moko      422:                if(length==JPEG_EXIF_DATE_CHARS && isdigit((unsigned char)cstr[0]) && cstr[length-1]==0) {
                    423:                        char cstr_writable[JPEG_EXIF_DATE_CHARS];
1.89      paf       424:                        strcpy(cstr_writable, cstr);
                    425: 
1.106     paf       426:                        try {
1.147     moko      427:                                tm tmIn=cstr_to_time_t(cstr_writable, 0);
1.146     moko      428:                                return new VDate(tmIn);
1.106     paf       429:                        }
                    430:                        catch(...) { /*ignore bad date times*/ }
1.89      paf       431:                }
                    432: 
1.123     misha     433:                return new VString(*new String(cstr, String::L_TAINTED));
1.80      paf       434:        }
                    435: 
                    436:        if(components_count==1)
1.91      paf       437:                return parse_IFD_entry_formatted_one_value(is_big, format, component_size, value);
1.80      paf       438: 
1.91      paf       439:        VHash* result=new VHash;
                    440:        HashStringValue& hash=result->hash();
1.80      paf       441:        for(uint i=0; i<components_count; i++, value+=component_size) {
1.91      paf       442:                hash.put(
1.93      paf       443:                        String::Body::Format(i),
1.91      paf       444:                        parse_IFD_entry_formatted_one_value(is_big, format, component_size, value));
1.80      paf       445:        }
                    446: 
1.91      paf       447:        return result;
1.80      paf       448: }
                    449: 
1.176     moko      450: static Value* parse_IFD_entry_value(bool is_big, Measure_reader& reader, uint64_t tiff_base, JPG_Exif_IFD_entry& entry) {
1.80      paf       451:        size_t format2component_size[]={
                    452:                0, // undefined
                    453:                1, // unsigned byte
                    454:                1, // ascii string
                    455:                2, // unsigned short
                    456:                4, // unsigned long
                    457:                8, // unsigned rational
                    458:                1, // signed byte
                    459:                0, // undefined
                    460:                2, // signed short
                    461:                4, // signed long
                    462:                8, // signed rational
                    463:                /*
                    464:                4, // single float
                    465:                8, // double float
                    466:                */
                    467:        };
                    468: 
                    469:        ushort format=endian_to_ushort(is_big, entry.format);
                    470:        if(format>=sizeof(format2component_size)/sizeof(format2component_size[0]))
                    471:                return 0; // format out of range, ignoring
                    472: 
                    473:        size_t component_size=format2component_size[format];
                    474:        if(component_size==0)
                    475:                return 0; // undefined format
                    476: 
                    477:        // You can get the total data byte length by multiplies 
                    478:        // a 'bytes/components' value (see above chart) by number of components stored 'NNNNNNNN' area
                    479:        uint components_count=endian_to_uint(is_big, entry.components_count);
1.121     misha     480:        uint value_size=component_size*components_count;
1.80      paf       481:        // If its size is over 4bytes, 'DDDDDDDD' contains the offset to data stored address
1.91      paf       482:        Value* result;
1.80      paf       483: 
                    484:        if(value_size<=4)
1.155     moko      485:                result=parse_IFD_entry_formatted_value(is_big, format, component_size, components_count, entry.value_or_offset_to_it);
1.80      paf       486:        else {
1.174     moko      487:                uint64_t remembered=reader.tell();
1.80      paf       488:                {
1.174     moko      489:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it));
1.91      paf       490:                        const char* value;
1.156     moko      491:                        if(reader.read(value, value_size)<value_size)
1.80      paf       492:                                return 0;
1.155     moko      493:                        result=parse_IFD_entry_formatted_value(is_big, format, component_size, components_count, (const uchar*)value);
1.80      paf       494:                }
1.174     moko      495:                reader.seek(remembered);
1.80      paf       496:        }
                    497: 
                    498:        return result;
                    499: }
                    500: 
1.176     moko      501: static void parse_IFD(HashStringValue& hash, bool is_big, Measure_reader& reader, uint64_t tiff_base, bool gps=false);
1.91      paf       502: 
1.176     moko      503: 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       504:        ushort tag=endian_to_ushort(is_big, entry.tag);
1.118     misha     505: 
                    506:        if(tag==JPG_IFD_TAG_EXIF_OFFSET || tag==JPG_IFD_TAG_EXIF_GPS_OFFSET){
1.174     moko      507:                uint64_t remembered=reader.tell();
1.80      paf       508:                {
1.174     moko      509:                        reader.seek(tiff_base+endian_to_uint(is_big, entry.value_or_offset_to_it));
1.118     misha     510:                        parse_IFD(hash, is_big, reader, tiff_base, (tag==JPG_IFD_TAG_EXIF_GPS_OFFSET)?true:gps);
1.80      paf       511:                }
1.174     moko      512:                reader.seek(remembered);
1.80      paf       513:                return;
                    514:        }
1.118     misha     515: 
1.91      paf       516:        if(Value* value=parse_IFD_entry_value(is_big, reader, tiff_base, entry)) {
1.118     misha     517:                if(const char* name=(gps)?exif_gps_tag_value2name.get(tag):exif_tag_value2name.get(tag))
1.148     moko      518:                        hash.put(name, value);
1.80      paf       519:                else
1.93      paf       520:                        hash.put(String::Body::Format(tag), value);
1.80      paf       521:        }
1.1       paf       522: }
                    523: 
1.176     moko      524: static void parse_IFD(HashStringValue& hash, bool is_big, Measure_reader& reader, uint64_t tiff_base, bool gps) {
1.91      paf       525:        const char* buf;
                    526:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
1.80      paf       527:                return;
1.91      paf       528:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
1.80      paf       529: 
                    530:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    531:        for(int i=0; i<directory_entry_count; i++) {
                    532:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    533:                        return;
                    534: 
1.118     misha     535:                parse_IFD_entry(hash, is_big, reader, tiff_base, *(JPG_Exif_IFD_entry *)buf, gps);
1.80      paf       536:        }
                    537:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    538: }
                    539: 
1.162     moko      540: static Value* parse_exif(Measure_reader& reader) {
1.91      paf       541:        const char* buf;
1.80      paf       542: 
1.175     moko      543:        uint64_t tiff_base=reader.tell();
1.80      paf       544:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    545:                return 0;
                    546: 
                    547:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    548:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    549: 
                    550:        uint first_IFD_offset=endian_to_uint(is_big, head->first_IFD_offset);
1.174     moko      551:        reader.seek(tiff_base+first_IFD_offset);
1.80      paf       552: 
1.91      paf       553:        VHash* vhash=new VHash;
1.80      paf       554: 
                    555:        // IFD
1.91      paf       556:        parse_IFD(vhash->hash(), is_big, reader, tiff_base);
1.80      paf       557: 
1.91      paf       558:        return vhash;
1.80      paf       559: }
                    560: 
1.163     moko      561: static Value* parse_xmp(Measure_reader& reader, ushort xmp_length, Measure_info &info) {
1.162     moko      562:        const char* buf;
                    563:        if(reader.read(buf, xmp_length)<xmp_length)
                    564:                return 0;
1.163     moko      565: 
                    566:        String::C xmp = Charset::transcode(String::C(pa_strdup(buf, xmp_length), xmp_length), *info.xmp_charset, pa_thread_request().charsets.source());
                    567:        return new VString(*new String(xmp, String::L_TAINTED));
1.162     moko      568: }
                    569: 
                    570: static void measure_jpeg(const String& origin_string, Measure_reader& reader, Measure_info &info) {
1.2       paf       571:        // JFIF format markers
1.80      paf       572:        const uchar MARKER=0xFF;
                    573:        const uchar CODE_SIZE_A=0xC0;
                    574:        const uchar CODE_SIZE_B=0xC1;
                    575:        const uchar CODE_SIZE_C=0xC2;
                    576:        const uchar CODE_SIZE_D=0xC3;
1.162     moko      577:        const uchar CODE_APP1=0xE1;
1.2       paf       578: 
1.91      paf       579:        const char* buf;
1.18      paf       580:        const size_t prefix_size=2;
1.31      parser    581:        if(reader.read(buf, prefix_size)<prefix_size)
1.155     moko      582:                throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - too small");
1.80      paf       583:        uchar *signature=(uchar *)buf;
1.1       paf       584:        
1.31      parser    585:        if(!(signature[0]==0xFF && signature[1]==0xD8)) 
1.155     moko      586:                throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - wrong signature");
1.31      parser    587: 
                    588:        while(true) {
1.177     moko      589:                uint64_t segment_base=reader.tell()+2/*marker,code*/;
1.31      parser    590:                if(reader.read(buf, sizeof(JPG_Segment_head))<sizeof(JPG_Segment_head))
1.79      paf       591:                        break;
1.31      parser    592:                JPG_Segment_head *head=(JPG_Segment_head *)buf;
                    593: 
1.162     moko      594:                // Verify that it's a valid segment.
1.31      parser    595:                if(head->marker!=MARKER)
1.155     moko      596:                        throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - marker not found");
1.79      paf       597: 
1.162     moko      598:                ushort segment_length=endian_to_ushort(true, head->length);
                    599: 
1.79      paf       600:                switch(head->code) {
1.162     moko      601:                // http://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_JPEG_files
                    602:                case CODE_APP1:
                    603:                        {
                    604:                                const size_t EXIF_SIG_LEN=6; // Exif\0\0
                    605:                                const size_t XMP_SIG_LEN=29; // http://ns.adobe.com/xap/1.0/\0
                    606: 
                    607:                                if(segment_length<EXIF_SIG_LEN+2 || reader.read(buf, EXIF_SIG_LEN)<EXIF_SIG_LEN)
                    608:                                        break;
                    609:                                if(memcmp(buf, "Exif\0\0", EXIF_SIG_LEN)==0){
                    610:                                        if(info.exif && !*info.exif) // backward compatibility: using first segment
                    611:                                                *info.exif=parse_exif(reader);
                    612:                                        break;
                    613:                                }
                    614: 
                    615:                                if(memcmp(buf, "http:/", EXIF_SIG_LEN))
                    616:                                        break;
                    617:                                if(segment_length<XMP_SIG_LEN+2 || reader.read(buf, XMP_SIG_LEN-EXIF_SIG_LEN)<XMP_SIG_LEN-EXIF_SIG_LEN)
                    618:                                        break;
                    619:                                if(memcmp(buf, "/ns.adobe.com/xap/1.0/\0", XMP_SIG_LEN-EXIF_SIG_LEN)==0){
                    620:                                        if(info.xmp && !*info.xmp) // backward compatibility: using first segment
1.163     moko      621:                                                *info.xmp=parse_xmp(reader, segment_length - XMP_SIG_LEN - 2 /* segment_length */, info);
1.162     moko      622:                                }
                    623: 
                    624:                        }
1.1       paf       625:                        break;
1.31      parser    626: 
1.79      paf       627:                case CODE_SIZE_A:
                    628:                case CODE_SIZE_B:
                    629:                case CODE_SIZE_C:
                    630:                case CODE_SIZE_D:
                    631:                        {
                    632:                                // Segments that contain size info
                    633:                                if(reader.read(buf, sizeof(JPG_Size_segment_body))<sizeof(JPG_Size_segment_body))
1.155     moko      634:                                        throw Exception(IMAGE_FORMAT, &origin_string, "not JPEG file - can not fully read Size segment");
1.79      paf       635:                                JPG_Size_segment_body *body=(JPG_Size_segment_body *)buf;
                    636:                                
1.162     moko      637:                                info.width=endian_to_ushort(true, body->width);
                    638:                                info.height=endian_to_ushort(true, body->height);
                    639:                        }
1.80      paf       640:                        return;
1.79      paf       641:                };
                    642: 
1.174     moko      643:                reader.seek(segment_base + segment_length);
1.31      parser    644:        }
                    645: 
1.155     moko      646:        throw Exception(IMAGE_FORMAT, &origin_string, "broken JPEG file - size frame not found");
1.1       paf       647: }
                    648: 
1.169     moko      649: ///*********************************************** TIFF
                    650: 
1.165     moko      651: static bool parse_tiff_IFD(bool is_big, Measure_reader& reader, Measure_info &info) {
                    652:        const char* buf;
                    653:        if(reader.read(buf, sizeof(JPG_Exif_IFD_begin))<sizeof(JPG_Exif_IFD_begin))
                    654:                return false;
                    655:        JPG_Exif_IFD_begin *start=(JPG_Exif_IFD_begin *)buf;
                    656: 
                    657:        ushort directory_entry_count=endian_to_ushort(is_big, start->directory_entry_count);
                    658:        for(int i=0; i<directory_entry_count; i++) {
                    659:                if(reader.read(buf, sizeof(JPG_Exif_IFD_entry))<sizeof(JPG_Exif_IFD_entry))
                    660:                        return false;
                    661: 
                    662:                JPG_Exif_IFD_entry *entry=(JPG_Exif_IFD_entry *)buf;
                    663:                ushort entry_tag=endian_to_ushort(is_big, entry->tag);
                    664: 
                    665:                if(entry_tag == 256 || entry_tag == 257){
                    666:                        ushort entry_format=endian_to_ushort(is_big, entry->format);
                    667:                        if(entry_format != 3 && entry_format != 4 || endian_to_uint(is_big, entry->components_count) != 1)
                    668:                                return false;
                    669:                        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      670:                        (entry_tag == 256) ? info.width=(short)value : info.height=(short)value;
1.165     moko      671:                        if(info.width && info.height)
                    672:                                return true;
                    673:                }
                    674:        }
                    675: 
                    676:        return false;
                    677:        // then goes: LLLLLLLL Offset to next IFD [not going there]
                    678: }
                    679: 
                    680: static void measure_tiff(const String& origin_string, Measure_reader& reader, Measure_info &info) {
                    681:        const char* buf;
                    682: 
                    683:        if(reader.read(buf, sizeof(JPG_Exif_TIFF_header))<sizeof(JPG_Exif_TIFF_header))
                    684:                throw Exception(IMAGE_FORMAT, &origin_string, "not TIFF file - too small");
                    685: 
                    686:        JPG_Exif_TIFF_header *head=(JPG_Exif_TIFF_header *)buf;
                    687: 
                    688:        if(strncmp(head->byte_align_identifier, "II", 2)!=0 && strncmp(head->byte_align_identifier, "MM", 2)!=0)
                    689:                throw Exception(IMAGE_FORMAT, &origin_string, "not TIFF file - wrong signature");
                    690: 
                    691:        bool is_big=head->byte_align_identifier[0]=='M'; // [M]otorola vs [I]ntel
                    692: 
                    693:        if(endian_to_ushort(is_big, head->signature) != 42)
                    694:                throw Exception(IMAGE_FORMAT, &origin_string, "not TIFF file - wrong signature");
                    695: 
1.174     moko      696:        reader.seek(endian_to_uint(is_big, head->first_IFD_offset));
1.165     moko      697:        if(!parse_tiff_IFD(is_big, reader, info))
                    698:                throw Exception(IMAGE_FORMAT, &origin_string, "broken TIFF file - size field entry not found");
                    699: }
                    700: 
1.169     moko      701: 
                    702: ///*********************************************** GIF
                    703: 
                    704: struct GIF_Header {
                    705:        char    signature[3];   // 'GIF'
                    706:        char    version[3];
                    707:        uchar   width[2];
                    708:        uchar   height[2];
                    709:        char    dif;
                    710:        char    fonColor;
                    711:        char    nulls;
                    712: };
                    713: 
1.164     moko      714: static void measure_gif(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    715: 
                    716:        const char* buf;
                    717:        const size_t head_size=sizeof(GIF_Header);
                    718:        if(reader.read(buf, head_size)<head_size)
                    719:                throw Exception(IMAGE_FORMAT, &origin_string, "not GIF file - too small");
                    720:        GIF_Header *head=(GIF_Header *)buf;
                    721: 
                    722:        if(strncmp(head->signature, "GIF", 3)!=0)
                    723:                throw Exception(IMAGE_FORMAT, &origin_string, "not GIF file - wrong signature");
                    724: 
                    725:        width=endian_to_ushort(false, head->width);
                    726:        height=endian_to_ushort(false, head->height);
                    727: }
                    728: 
1.169     moko      729: 
                    730: ///*********************************************** PNG
                    731: 
                    732: struct PNG_Header {
                    733:        char    dummy[12];
                    734:        char    signature[4];   //< must be "IHDR"
                    735:        uchar   high_width[2];  //< image width high bytes [we ignore for now]
                    736:        uchar   width[2];       //< image width low bytes
                    737:        uchar   high_height[2]; //< image height high bytes [we ignore for now]
                    738:        uchar   height[4];      //< image height
                    739: };
                    740: 
1.152     moko      741: static void measure_png(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
1.72      paf       742: 
1.91      paf       743:        const char* buf;
1.102     paf       744:        const size_t head_size=sizeof(PNG_Header);
                    745:        if(reader.read(buf, head_size)<head_size)
1.152     moko      746:                throw Exception(IMAGE_FORMAT, &origin_string, "not PNG file - too small");
1.72      paf       747:        PNG_Header *head=(PNG_Header *)buf;
                    748: 
                    749:        if(strncmp(head->signature, "IHDR", 4)!=0)
1.152     moko      750:                throw Exception(IMAGE_FORMAT, &origin_string, "not PNG file - wrong signature");
1.72      paf       751: 
1.80      paf       752:        width=endian_to_ushort(true, head->width);
                    753:        height=endian_to_ushort(true, head->height);
1.72      paf       754: }
                    755: 
1.169     moko      756: 
                    757: ///*********************************************** BMP
                    758: 
                    759: struct BMP_Header {
                    760:        char    signature[2];   // 'BM'
                    761:        uchar   file_size[4];
                    762:        uchar   reserved[4];
                    763:        uchar   bitmap_offset[4];
                    764:        uchar   header_size[4];
                    765:        uchar   width[2];
                    766:        uchar   high_width[2];  //< image width high bytes [we ignore for now]
                    767:        uchar   height[2];
                    768:        uchar   high_height[2]; //< image height high bytes [we ignore for now]
                    769: };
                    770: 
1.164     moko      771: static void measure_bmp(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    772: 
                    773:        const char* buf;
                    774:        const size_t head_size=sizeof(BMP_Header);
                    775:        if(reader.read(buf, head_size)<head_size)
                    776:                throw Exception(IMAGE_FORMAT, &origin_string, "not BMP file - too small");
                    777:        BMP_Header *head=(BMP_Header *)buf;
                    778: 
                    779:        if(strncmp(head->signature, "BM", 2)!=0)
                    780:                throw Exception(IMAGE_FORMAT, &origin_string, "not BMP file - wrong signature");
                    781: 
1.174     moko      782:        if((uint)reader.length() != endian_to_uint(false, head->file_size))
1.164     moko      783:                throw Exception(IMAGE_FORMAT, &origin_string, "not BMP file - length header and file size do not match");
                    784: 
                    785:        width=endian_to_ushort(false, head->width);
                    786:        height=endian_to_ushort(false, head->height);
                    787: }
                    788: 
1.168     moko      789: 
1.169     moko      790: ///*********************************************** WEBP
                    791: 
                    792: struct WEBP_Header {
                    793:        char signature_riff[4]; // 'RIFF'
                    794:        uchar file_size[4];
                    795:        char signature[4];      // 'WEBP'
                    796:        char format[4];         // 'VP8 ' or 'VP8L' or 'VP8X'
                    797: };
                    798: 
                    799: struct WEBP_VP8_Chunk {
                    800:        uchar size[4];
                    801:        char tag[3];
                    802:        uchar signature[3];    // 0x9D 0x01 0x2A
                    803:        uchar width[2];        // 14 bits each
                    804:        uchar height[2];       // 14 bits each
                    805: };
                    806: 
                    807: struct WEBP_VP8L_Chunk {
                    808:        uchar size[4];
                    809:        char signature;        // 0x2F
                    810:        uchar width_height[4]; // 14 bits each
                    811: };
                    812: 
                    813: struct WEBP_X_Chunk {
                    814:        uchar size[4];
                    815:        char reserved[4];
                    816:        uchar width[3];
                    817:        uchar height[3];
                    818: };
                    819: 
1.168     moko      820: static void measure_webp(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    821:        const char* buf;
                    822: 
                    823:        if(reader.read(buf, sizeof(WEBP_Header))<sizeof(WEBP_Header))
                    824:                throw Exception(IMAGE_FORMAT, &origin_string, "not WEBP file - too small");
                    825: 
                    826:        WEBP_Header *head=(WEBP_Header *)buf;
                    827: 
                    828:        if(strncmp(head->signature_riff, "RIFF", 4)!=0 || strncmp(head->signature, "WEBP", 4)!=0)
                    829:                throw Exception(IMAGE_FORMAT, &origin_string, "not WEBP file - wrong signature");
                    830: 
                    831:        if(strncmp(head->format, "VP8 ", 4)==0){
                    832:                if(reader.read(buf, sizeof(WEBP_VP8_Chunk))<sizeof(WEBP_VP8_Chunk))
                    833:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - too small VP8 chunk");
                    834: 
                    835:                WEBP_VP8_Chunk *chunk=(WEBP_VP8_Chunk *)buf;
                    836:                if (chunk->signature[0] != 0x9D || chunk->signature[1] != 0x01 || chunk->signature[2] != 0x2A)
                    837:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - wrong VP8 chunk signature");
                    838: 
                    839:                width=endian_to_ushort(false, chunk->width) & 0x3FFF;
                    840:                height=endian_to_ushort(false, chunk->height) & 0x3FFF;
                    841:        } else if(strncmp(head->format, "VP8L", 4)==0){
                    842:                if(reader.read(buf, sizeof(WEBP_VP8L_Chunk))<sizeof(WEBP_VP8L_Chunk))
                    843:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - too small VP8L chunk");
                    844: 
                    845:                WEBP_VP8L_Chunk *chunk=(WEBP_VP8L_Chunk *)buf;
                    846:                if(chunk->signature != 0x2F)
                    847:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - wrong VP8L chunk signature");
                    848: 
                    849:                uint wh=endian_to_uint(false, chunk->width_height);
                    850:                width=(wh & 0x3FFF) + 1;
                    851:                height=((wh >> 14) & 0x3FFF) + 1;
                    852:        } else if (strncmp(head->format, "VP8X", 4)==0){
                    853:                if(reader.read(buf, sizeof(WEBP_X_Chunk))<sizeof(WEBP_X_Chunk))
                    854:                        throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - too small VP8X chunk");
                    855: 
                    856:                WEBP_X_Chunk *chunk=(WEBP_X_Chunk *)buf;
                    857: 
                    858:                width=endian_to_ushort(false, chunk->width) + 1;   // we ignore third byte to simplify code
                    859:                height=endian_to_ushort(false, chunk->height) + 1; // we ignore third byte to simplify code
                    860:        } else throw Exception(IMAGE_FORMAT, &origin_string, "broken WEBP file - invalid chunk signature");
                    861: }
                    862: 
1.170     moko      863: 
                    864: ///*********************************************** MP4
                    865: 
                    866: struct MP4_Header {
                    867:        uchar size[4];
                    868:        char signature[4];   // 'ftyp' in first chunk
                    869: };
                    870: 
1.173     moko      871: struct MP4_ExtSize {
                    872:        uchar high[4];
                    873:        uchar low[4];
                    874: };
                    875: 
                    876: struct MP4_Tkhd {
                    877:        uchar width[4];
                    878:        uchar height[4];
                    879: };
                    880: 
1.174     moko      881: 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      882:        for(bool first=anext==0;;){
                    883:                const char* buf;
1.174     moko      884:                uint64_t next=reader.tell();
1.173     moko      885: 
                    886:                if(reader.read(buf, sizeof(MP4_Header))<sizeof(MP4_Header))
1.172     moko      887:                        throw Exception(IMAGE_FORMAT, &origin_string, first ? "not MP4 file - too small" : "broken MP4 file - truncated chunk header");
1.170     moko      888: 
                    889:                MP4_Header *head=(MP4_Header *)buf;
1.174     moko      890:                uint64_t size=endian_to_uint(true, head->size);
1.170     moko      891: 
1.173     moko      892:                if(size==1){
                    893:                        if(reader.read(buf, sizeof(MP4_ExtSize))<sizeof(MP4_ExtSize))
                    894:                                throw Exception(IMAGE_FORMAT, &origin_string, "broken MP4 file - truncated chunk extended size header");
                    895:                        MP4_ExtSize *ext_size=(MP4_ExtSize *)buf;
1.174     moko      896:                        size=((uint64_t)endian_to_uint(true, ext_size->high) << 32) + endian_to_uint(true, ext_size->low);
1.173     moko      897:                }
                    898:                next+=size;
1.170     moko      899: 
                    900:                if(first){
                    901:                        if(strncmp(head->signature, "ftyp", 4)!=0)
                    902:                                throw Exception(IMAGE_FORMAT, &origin_string, "not MP4 file - wrong signature");
                    903:                        first=false;
1.174     moko      904:                        anext=reader.length(); // to avoid reading beyond EOF
1.170     moko      905:                } else if(strncmp(head->signature, "moov", 4)==0 || strncmp(head->signature, "mdia", 4)==0 || strncmp(head->signature, "trak", 4)==0) {
                    906:                        if(measure_mp4(origin_string, reader, width, height, next, lastTkhd))
                    907:                                return true;
                    908:                } else if(strncmp(head->signature, "tkhd", 4)==0) {
                    909:                        if(size>8){
1.174     moko      910:                                reader.seek(next-8);
1.173     moko      911:                                if(reader.read(lastTkhd, sizeof(MP4_Tkhd))<sizeof(MP4_Tkhd))
1.170     moko      912:                                        throw Exception(IMAGE_FORMAT, &origin_string, "broken MP4 file - bad tkhd chunk");
                    913:                        }
                    914:                } else if (strncmp(head->signature, "hdlr", 4)==0) {
                    915:                        if(size>12){
                    916:                                const char* hdlr;
                    917:                                if(reader.read(hdlr, 12)<12)
                    918:                                        throw Exception(IMAGE_FORMAT, &origin_string, "broken MP4 file - bad hdlr chunk");
1.173     moko      919:                                if(lastTkhd && strncmp(hdlr+8, "vide", 4)==0) {
                    920:                                        MP4_Tkhd *tkhd=(MP4_Tkhd *)lastTkhd;
                    921:                                        width=endian_to_ushort(true, tkhd->width);
                    922:                                        height=endian_to_ushort(true, tkhd->height);
1.170     moko      923:                                        return true;
                    924:                                }
                    925:                        }
                    926:                }
                    927:                if(anext && next>=anext)
                    928:                        break;
1.174     moko      929:                reader.seek(next);
1.170     moko      930:        }
                    931:        return false;
                    932: }
                    933: 
                    934: static void measure_mp4(const String& origin_string, Measure_reader& reader, ushort& width, ushort& height) {
                    935:        if(!measure_mp4(origin_string, reader, width, height, 0))
                    936:                throw Exception(IMAGE_FORMAT, &origin_string, "unsupported MP4 file - size not found");
                    937: }
                    938: 
1.169     moko      939: ///*********************************************** measure center
1.1       paf       940: 
1.162     moko      941: static void measure(const String& file_name, Measure_reader& reader, Measure_info &info) {
1.128     misha     942:        const char* file_name_cstr=file_name.taint_cstr(String::L_FILE_SPEC);
1.91      paf       943:        if(const char* cext=strrchr(file_name_cstr, '.')) {
1.1       paf       944:                cext++;
                    945:                if(strcasecmp(cext, "GIF")==0)
1.162     moko      946:                        measure_gif(file_name, reader, info.width, info.height);
1.165     moko      947:                else if(strcasecmp(cext, "JPG")==0 || strcasecmp(cext, "JPEG")==0)
1.162     moko      948:                        measure_jpeg(file_name, reader, info);
1.72      paf       949:                else if(strcasecmp(cext, "PNG")==0)
1.162     moko      950:                        measure_png(file_name, reader, info.width, info.height);
1.164     moko      951:                else if(strcasecmp(cext, "BMP")==0)
                    952:                        measure_bmp(file_name, reader, info.width, info.height);
1.168     moko      953:                else if(strcasecmp(cext, "WEBP")==0)
                    954:                        measure_webp(file_name, reader, info.width, info.height);
1.165     moko      955:                else if(strcasecmp(cext, "TIF")==0 || strcasecmp(cext, "TIFF")==0)
                    956:                        measure_tiff(file_name, reader, info);
1.171     moko      957:                else if(strcasecmp(cext, "MP4")==0 || strcasecmp(cext, "MOV")==0)
1.170     moko      958:                        measure_mp4(file_name, reader, info.width, info.height);
1.1       paf       959:                else
1.152     moko      960:                        throw Exception(IMAGE_FORMAT, &file_name, "unhandled image file name extension '%s'", cext);
1.1       paf       961:        } else
1.152     moko      962:                throw Exception(IMAGE_FORMAT, &file_name, "can not determine image type - no file name extension");
1.1       paf       963: }
                    964: 
1.77      paf       965: // methods
1.1       paf       966: 
1.152     moko      967: static void file_measure_action(struct stat& /*finfo*/, int f, const String& file_spec, void *context) {
                    968:        Measure_file_reader reader(f, file_spec);
1.162     moko      969:        measure(file_spec, reader, *static_cast<Measure_info *>(context));
1.1       paf       970: }
                    971: 
1.91      paf       972: static void _measure(Request& r, MethodParams& params) {
                    973:        Value& data=params.as_no_junction(0, "data must not be code");
1.1       paf       974: 
1.91      paf       975:        Value* exif=0;
1.162     moko      976:        Value* xmp=0;
1.163     moko      977:        Measure_info info={ 0, 0, 0, 0, &pa_UTF8_charset };
                    978: 
                    979:        if(params.count()>1)
                    980:                if(HashStringValue* options=params.as_hash(1, "methods options")) {
                    981:                        int valid_options=0;
                    982:                        for(HashStringValue::Iterator i(*options); i; i.next() ){
                    983:                                String::Body key=i.key();
                    984:                                Value* value=i.value();
                    985:                                if(key == "exif") {
                    986:                                        if(r.process(*value).as_bool())
                    987:                                                info.exif=&exif;
                    988:                                        valid_options++;
                    989:                                }
                    990:                                if(key == "xmp") {
                    991:                                        if(r.process(*value).as_bool())
                    992:                                                info.xmp=&xmp;
                    993:                                        valid_options++;
                    994:                                }
                    995:                                if(key == "xmp-charset") {
                    996:                                        info.xmp_charset=&pa_charsets.get(value->as_string());
                    997:                                        valid_options++;
                    998:                                }
                    999:                        }
                   1000:                        if(valid_options!=options->count())
                   1001:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                   1002:                }
1.162     moko     1003: 
1.91      paf      1004:        const String* file_name;
1.162     moko     1005: 
                   1006:        if(file_name=data.get_string()) {
1.167     moko     1007:                file_read_action_under_lock(r.full_disk_path(*file_name), "measure", file_measure_action, &info);
1.1       paf      1008:        } else {
1.129     misha    1009:                VFile* vfile=data.as_vfile(String::L_AS_IS);
1.91      paf      1010:                file_name=&vfile->fields().get(name_name)->as_string();
1.162     moko     1011:                Measure_buf_reader reader(vfile->value_ptr(), vfile->value_size(), *file_name);
                   1012:                measure(*file_name, reader, info);
1.1       paf      1013:        }
                   1014: 
1.162     moko     1015:        GET_SELF(r, VImage).set(file_name, info.width, info.height, 0, exif, xmp);
1.1       paf      1016: }
                   1017: 
1.161     moko     1018: static void append_attrib_pair(String &tag, String::Body key, Value* value){
                   1019:        // skip border attribute with empty value
                   1020:        if(key=="border" && !value->is_defined())
1.4       paf      1021:                return;
                   1022: 
1.133     misha    1023:        // src="a.gif" width="123" ismap[=-1]
1.161     moko     1024:        tag << " " << key;
1.91      paf      1025:        if(value->is_string() || value->as_int()>=0)
1.161     moko     1026:                tag << "=\"" << value->as_string() << "\"";
1.3       paf      1027: }
1.161     moko     1028: 
1.91      paf      1029: static void _html(Request& r, MethodParams& params) {
                   1030:        String tag;
1.3       paf      1031:        tag << "<img";
1.4       paf      1032: 
1.91      paf      1033:        const HashStringValue& fields=GET_SELF(r, VImage).fields();
                   1034:        HashStringValue* attribs=0;
1.4       paf      1035: 
1.91      paf      1036:        if(params.count()) {
1.69      paf      1037:                // for backward compatibility: someday was ^html{}
1.154     moko     1038:                Value& vattribs=r.process(params[0]);
1.145     moko     1039:                if(!vattribs.is_string()) { // allow empty
1.100     paf      1040:                        if((attribs=vattribs.get_hash())) {
1.161     moko     1041:                                for(HashStringValue::Iterator i(*attribs); i; i.next() )
                   1042:                                        append_attrib_pair(tag, i.key(), i.value());
1.39      parser   1043:                        } else
1.155     moko     1044:                                throw Exception(PARSER_RUNTIME, 0, "attributes must be hash");
1.145     moko     1045:                }
1.39      parser   1046:        }
1.4       paf      1047: 
1.161     moko     1048:        for(HashStringValue::Iterator i(fields); i; i.next() ){
                   1049:                String::Body key=i.key();
                   1050:                // skip user-specified attributes
                   1051:                if(attribs && attribs->get(key))
                   1052:                        continue;
                   1053:                // allow only html attributes (to exclude exif, line-*)
                   1054:                if(key=="src" || key=="width" || key=="height" || key=="border")
                   1055:                        append_attrib_pair(tag, key, i.value());
1.91      paf      1056:        }
1.161     moko     1057: 
1.6       paf      1058:        tag << " />";
1.157     moko     1059:        r.write(tag);
1.3       paf      1060: }
1.8       paf      1061: 
1.68      paf      1062: /// @test wrap FILE to auto-object
1.155     moko     1063: static gdImage* load(Request& r, const String& file_name){
1.167     moko     1064:        const char* file_name_cstr=r.full_disk_path(file_name).taint_cstr(String::L_FILE_SPEC);
1.159     moko     1065:        if(FILE *f=pa_fopen(file_name_cstr, "rb")) {
1.91      paf      1066:                gdImage* image=new gdImage;
                   1067:                bool ok=image->CreateFromGif(f);
1.16      paf      1068:                fclose(f);
1.23      paf      1069:                if(!ok)
1.155     moko     1070:                        throw Exception(IMAGE_FORMAT, &file_name, "is not in GIF format");
1.91      paf      1071:                return image;
1.16      paf      1072:        } else {
1.155     moko     1073:                throw Exception("file.missing", 0, "can not open '%s'", file_name_cstr);
1.16      paf      1074:        }
                   1075: }
                   1076: 
                   1077: 
1.91      paf      1078: static void _load(Request& r, MethodParams& params) {
1.116     misha    1079:        const String& file_name=params.as_string(0, FILE_NAME_MUST_NOT_BE_CODE);
1.6       paf      1080: 
1.91      paf      1081:        gdImage* image=load(r, file_name);
                   1082:        GET_SELF(r, VImage).set(&file_name, image->SX(), image->SY(), image);
1.6       paf      1083: }
                   1084: 
1.91      paf      1085: static void _create(Request& r, MethodParams& params) {
                   1086:        int width=params.as_int(0, "width must be int", r);
                   1087:        int height=params.as_int(1, "height must be int", r);
1.8       paf      1088:        int bgcolor_value=0xffFFff;
1.91      paf      1089:        if(params.count()>2)
                   1090:                bgcolor_value=params.as_int(2, "color must be int", r);
                   1091:        gdImage* image=new gdImage;
                   1092:        image->Create(width, height);
                   1093:        image->FilledRectangle(0, 0, width-1, height-1, image->Color(bgcolor_value));
                   1094:        GET_SELF(r, VImage).set(0, width, height, image);
1.6       paf      1095: }
                   1096: 
1.91      paf      1097: static void _gif(Request& r, MethodParams& params) {
1.108     paf      1098:        gdImage& image=GET_SELF(r, VImage).image();
1.6       paf      1099: 
1.138     misha    1100:        const String *file_name=params.count()>0?&params.as_string(0, FILE_NAME_MUST_BE_STRING):0;
1.10      paf      1101: 
1.108     paf      1102:        gdBuf buf=image.Gif();
1.6       paf      1103:        
1.91      paf      1104:        VFile& vfile=*new VFile;
1.137     misha    1105: 
1.142     moko     1106:        vfile.set_binary(false/*not tainted*/, (const char *)buf.ptr, buf.size, file_name, new VString(*new String("image/gif")));
1.137     misha    1107: 
1.157     moko     1108:        r.write(vfile);
1.6       paf      1109: }
                   1110: 
1.91      paf      1111: static void _line(Request& r, MethodParams& params) {
1.108     paf      1112:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf      1113: 
1.108     paf      1114:        image.Line(
1.91      paf      1115:                params.as_int(0, "x0 must be int", r), 
                   1116:                params.as_int(1, "y0 must be int", r), 
                   1117:                params.as_int(2, "x1 must be int", r), 
                   1118:                params.as_int(3, "y1 must be int", r), 
1.108     paf      1119:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf      1120: }
                   1121: 
1.91      paf      1122: static void _fill(Request& r, MethodParams& params) {
1.108     paf      1123:        gdImage& image=GET_SELF(r, VImage).image();
1.12      paf      1124: 
1.108     paf      1125:        image.Fill(
1.91      paf      1126:                params.as_int(0, "x must be int", r), 
                   1127:                params.as_int(1, "y must be int", r), 
1.108     paf      1128:                image.Color(params.as_int(2, "color must be int", r)));
1.13      paf      1129: }
                   1130: 
1.91      paf      1131: static void _rectangle(Request& r, MethodParams& params) {
1.108     paf      1132:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1133: 
1.108     paf      1134:        image.Rectangle(
1.91      paf      1135:                params.as_int(0, "x0 must be int", r), 
                   1136:                params.as_int(1, "y0 must be int", r), 
                   1137:                params.as_int(2, "x1 must be int", r), 
                   1138:                params.as_int(3, "y1 must be int", r), 
1.108     paf      1139:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf      1140: }
                   1141: 
1.91      paf      1142: static void _bar(Request& r, MethodParams& params) {
1.108     paf      1143:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1144: 
1.108     paf      1145:        image.FilledRectangle(
1.91      paf      1146:                params.as_int(0, "x0 must be int", r), 
                   1147:                params.as_int(1, "y0 must be int", r), 
                   1148:                params.as_int(2, "x1 must be int", r), 
                   1149:                params.as_int(3, "y1 must be int", r), 
1.108     paf      1150:                image.Color(params.as_int(4, "color must be int", r)));
1.13      paf      1151: }
                   1152: 
1.44      parser   1153: #ifndef DOXYGEN
1.155     moko     1154: static void add_point(Table::element_type row, gdImage::Point **p) {
1.110     paf      1155:        if(row->count()!=2)
1.155     moko     1156:                throw Exception(0, 0, "coordinates table must contain two columns: x and y values");
1.91      paf      1157:        (**p).x=row->get(0)->as_int();
                   1158:        (**p).y=row->get(1)->as_int();
1.44      parser   1159:        (*p)++;
                   1160: }
                   1161: #endif
1.135     misha    1162: #ifndef DOXYGEN
1.155     moko     1163: static void add_point(int x, int y, gdImage::Point **p) {
1.135     misha    1164:        (**p).x=x;
                   1165:        (**p).y=y;
                   1166:        (*p)++;
                   1167: }
                   1168: #endif
1.91      paf      1169: static void _replace(Request& r, MethodParams& params) {
1.135     misha    1170:        int src_color=params.as_int(0, "src color must be int", r);
                   1171:        int dest_color=params.as_int(1, "dest color must be int", r);
                   1172: 
1.108     paf      1173:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1174: 
1.135     misha    1175:        gdImage::Point* all_p=0;
                   1176:        size_t count=0;
                   1177:        if(params.count() == 3){
1.140     misha    1178:                Table* table=params.as_table(2, "coordinates");
1.135     misha    1179:                count=table->count();
                   1180:                all_p=new(PointerFreeGC) gdImage::Point[count];
                   1181:                gdImage::Point* add_p=all_p;
                   1182:                table->for_each(add_point, &add_p);
                   1183:        } else {
                   1184:                int max_x=image.SX()-1;
                   1185:                int max_y=image.SY()-1;
                   1186:                if(max_x > 0 && max_y > 0){
                   1187:                        count=4;
                   1188:                        all_p=new(PointerFreeGC) gdImage::Point[count];
                   1189:                        gdImage::Point* add_p=all_p;
                   1190:                        add_point(0, 0, &add_p);
                   1191:                        add_point(max_x, 0, &add_p);
                   1192:                        add_point(max_x, max_y, &add_p);
                   1193:                        add_point(0, max_y, &add_p);
                   1194:                }
                   1195:        }
1.13      paf      1196: 
1.135     misha    1197:        if(count)
                   1198:                image.FilledPolygonReplaceColor(all_p, count, image.Color(src_color), image.Color(dest_color));
1.13      paf      1199: }
                   1200: 
1.91      paf      1201: static void _polyline(Request& r, MethodParams& params) {
1.108     paf      1202:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1203: 
1.140     misha    1204:        Table* table=params.as_table(1, "coordinates");
1.44      parser   1205: 
1.92      paf      1206:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1207:        gdImage::Point *add_p=all_p;    
                   1208:        table->for_each(add_point, &add_p);
1.108     paf      1209:        image.Polygon(all_p, table->count(), 
                   1210:                image.Color(params.as_int(0, "color must be int", r)),
1.44      parser   1211:                false/*not closed*/);
                   1212: }
                   1213: 
1.91      paf      1214: static void _polygon(Request& r, MethodParams& params) {
1.108     paf      1215:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1216: 
1.140     misha    1217:        Table* table=(Table*)params.as_table(1, "coordinates");
1.44      parser   1218: 
1.92      paf      1219:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1220:        gdImage::Point *add_p=all_p;    
                   1221:        table->for_each(add_point, &add_p);
1.108     paf      1222:        image.Polygon(all_p, table->count(), 
                   1223:                image.Color(params.as_int(0, "color must be int", r)));
1.13      paf      1224: }
                   1225: 
1.91      paf      1226: static void _polybar(Request& r, MethodParams& params) {
1.108     paf      1227:        gdImage& image=GET_SELF(r, VImage).image();
1.13      paf      1228: 
1.140     misha    1229:        Table* table=(Table*)params.as_table(1, "coordinates");
1.13      paf      1230: 
1.92      paf      1231:        gdImage::Point* all_p=new(PointerFreeGC) gdImage::Point[table->count()];
1.44      parser   1232:        gdImage::Point *add_p=all_p;    
                   1233:        table->for_each(add_point, &add_p);
1.108     paf      1234:        image.FilledPolygon(all_p, table->count(), 
                   1235:                image.Color(params.as_int(0, "color must be int", r)));
1.12      paf      1236: }
                   1237: 
1.16      paf      1238: // font
                   1239: 
1.85      paf      1240: #define Y(y)(y+index*height)
1.21      paf      1241: 
1.91      paf      1242: // Font class
                   1243: 
1.155     moko     1244: Font::Font(Charset& asource_charset, const String& aalphabet, gdImage* aifont, int aheight, int amonospace, int aspacebarspace, int aletterspacing):
1.158     moko     1245:        letterspacing(aletterspacing),
1.132     misha    1246:        height(aheight),
                   1247:        monospace(amonospace),
                   1248:        spacebarspace(aspacebarspace),
1.100     paf      1249:        ifont(aifont),
1.158     moko     1250:        alphabet(aalphabet),
                   1251:        fsource_charset(asource_charset){
1.132     misha    1252: 
                   1253:        if(fsource_charset.isUTF8()){
                   1254:                size_t index=0;
                   1255:                for(UTF8_string_iterator i(alphabet); i.has_next(); )
                   1256:                        fletter2index.put_dont_replace(i.next(), index++);
                   1257:        }
1.91      paf      1258: }
                   1259: 
                   1260: /* ******************************** char ********************************** */
                   1261: 
                   1262: size_t Font::index_of(char ch) {
                   1263:        if(ch==' ') return STRING_NOT_FOUND;
                   1264:        return alphabet.pos(ch);
                   1265: }
                   1266: 
1.132     misha    1267: size_t Font::index_of(XMLCh ch) {
                   1268:        if(ch==' ') return STRING_NOT_FOUND;
                   1269:        return fletter2index.get(ch);
                   1270: }
                   1271: 
1.91      paf      1272: int Font::index_width(size_t index) {
                   1273:        if(index==STRING_NOT_FOUND)
                   1274:                return spacebarspace;
                   1275:        int tr=ifont->GetTransparent();
                   1276:        for(int x=ifont->SX()-1; x>=0; x--) {
                   1277:                for(int y=0; y<height; y++)
                   1278:                        if(ifont->GetPixel(x, Y(y))!=tr) 
                   1279:                                return x+1;
1.16      paf      1280:        }
1.91      paf      1281:        return 0;
                   1282: }
                   1283: 
1.108     paf      1284: void Font::index_display(gdImage& image, int x, int y, size_t index){
1.91      paf      1285:        if(index!=STRING_NOT_FOUND) 
1.108     paf      1286:                ifont->Copy(image, x, y, 0, Y(0), index_width(index), height);
1.91      paf      1287: }
                   1288: 
                   1289: /* ******************************** string ********************************** */
                   1290: 
                   1291: int Font::step_width(int index) {
1.125     misha    1292:        return letterspacing + (monospace ? monospace : index_width(index));
1.91      paf      1293: }
                   1294: 
                   1295: // counts trailing letter_spacing, consider this OK. useful for contiuations
                   1296: int Font::string_width(const String& s){
                   1297:        const char* cstr=s.cstr();
                   1298:        int result=0;
1.132     misha    1299: 
                   1300:        if(fsource_charset.isUTF8()){
                   1301:                for(UTF8_string_iterator i(s); i.has_next(); )
                   1302:                        result+=step_width(index_of(i.next()));
                   1303:        } else {
                   1304:                for(const char* current=cstr; *current; current++)
                   1305:                        result+=step_width(index_of(*current));
                   1306:        }
                   1307: 
1.91      paf      1308:        return result;
                   1309: }
                   1310: 
1.108     paf      1311: void Font::string_display(gdImage& image, int x, int y, const String& s){
1.91      paf      1312:        const char* cstr=s.cstr();
1.132     misha    1313: 
                   1314:        if(fsource_charset.isUTF8()){
                   1315:                for(UTF8_string_iterator i(s); i.has_next(); ){
                   1316:                        size_t index=index_of(i.next());
                   1317:                        index_display(image, x, y, index);
                   1318:                        x+=step_width(index);
                   1319:                }
                   1320:        } else {
                   1321:                for(const char* current=cstr; *current; current++) {
                   1322:                        size_t index=index_of(*current);
                   1323:                        index_display(image, x, y, index);
                   1324:                        x+=step_width(index);
                   1325:                }
1.87      paf      1326:        }
1.91      paf      1327: }
1.87      paf      1328: 
1.91      paf      1329: //
1.35      parser   1330: 
1.16      paf      1331: 
1.91      paf      1332: static void _font(Request& r, MethodParams& params) {
                   1333:        const String& alphabet=params.as_string(0, "alphabet must not be code");
1.131     misha    1334:        size_t alphabet_length=alphabet.length(r.charsets.source());
                   1335:        if(!alphabet_length)
1.155     moko     1336:                throw Exception(PARSER_RUNTIME, 0, "alphabet must not be empty");
1.84      paf      1337: 
1.125     misha    1338:        gdImage* image=load(r, params.as_string(1, FILE_NAME_MUST_NOT_BE_CODE));
                   1339: 
1.126     misha    1340:        int spacebar_width=image->SX();
1.125     misha    1341:        int monospace_width=0; // proportional
                   1342:        int letter_spacing=1;
                   1343:        if(params.count()>2){
1.144     moko     1344:                if(HashStringValue* options=params[2].get_hash()){
1.125     misha    1345:                        // third option is hash
                   1346:                        if(params.count()>3)
1.144     moko     1347:                                throw Exception(PARSER_RUNTIME, 0, "too many params were specified");
1.125     misha    1348:                        int valid_options=0;
                   1349:                        if(Value* vspacebar_width=options->get(spacebar_width_name)){
                   1350:                                valid_options++;
1.153     moko     1351:                                spacebar_width=r.process(*vspacebar_width).as_int();
1.125     misha    1352:                        }
                   1353:                        if(Value* vmonospace_width=options->get(monospace_width_name)){
                   1354:                                valid_options++;
1.153     moko     1355:                                monospace_width=r.process(*vmonospace_width).as_int();
1.125     misha    1356:                                if(!monospace_width)
                   1357:                                        monospace_width=image->SX();
                   1358:                        }
                   1359:                        if(Value* vletter_spacing=options->get(letter_spacing_name)){
                   1360:                                valid_options++;
1.153     moko     1361:                                letter_spacing=r.process(*vletter_spacing).as_int();
1.125     misha    1362:                        }
                   1363:                        if(valid_options!=options->count())
1.134     misha    1364:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.125     misha    1365:                } else {
                   1366:                        // backward
1.144     moko     1367:                        spacebar_width=params.as_int(2, "param must be int or hash", r);
1.125     misha    1368:                        if(params.count()>3) {
                   1369:                                monospace_width=params.as_int(3, "monospace_width must be int", r);
                   1370:                                if(!monospace_width)
                   1371:                                        monospace_width=image->SX();
                   1372:                        }
                   1373:                }
                   1374:        }
                   1375: 
1.131     misha    1376:        if(int remainder=image->SY() % alphabet_length)
1.155     moko     1377:                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   1378:        
1.155     moko     1379:        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      1380: }
                   1381: 
1.91      paf      1382: static void _text(Request& r, MethodParams& params) {
                   1383:        int x=params.as_int(0, "x must be int", r);
                   1384:        int y=params.as_int(1, "y must be int", r);
                   1385:        const String& s=params.as_string(2, "text must not be code");
1.16      paf      1386: 
1.91      paf      1387:        VImage& vimage=GET_SELF(r, VImage);
1.108     paf      1388:        vimage.font().string_display(vimage.image(), x, y, s);
1.16      paf      1389: }
                   1390: 
1.91      paf      1391: static void _length(Request& r, MethodParams& params) {
                   1392:        const String& s=params.as_string(0, "text must not be code");
1.47      parser   1393: 
1.91      paf      1394:        VImage& vimage=GET_SELF(r, VImage);
1.157     moko     1395:        r.write(*new VInt(vimage.font().string_width(s)));
1.47      parser   1396: }
                   1397: 
1.91      paf      1398: static void _arc(Request& r, MethodParams& params) {
1.108     paf      1399:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1400: 
1.108     paf      1401:        image.Arc(
1.91      paf      1402:                params.as_int(0, "center_x must be int", r), 
                   1403:                params.as_int(1, "center_y must be int", r), 
                   1404:                params.as_int(2, "width must be int", r), 
                   1405:                params.as_int(3, "height must be int", r), 
                   1406:                params.as_int(4, "start degrees must be int", r), 
                   1407:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1408:                image.Color(params.as_int(6, "cx must be int", r)));
1.48      parser   1409: }
                   1410: 
1.91      paf      1411: static void _sector(Request& r, MethodParams& params) {
1.108     paf      1412:        gdImage& image=GET_SELF(r, VImage).image();
1.49      parser   1413: 
1.108     paf      1414:        image.Sector(
1.91      paf      1415:                params.as_int(0, "center_x must be int", r), 
                   1416:                params.as_int(1, "center_y must be int", r), 
                   1417:                params.as_int(2, "width must be int", r), 
                   1418:                params.as_int(3, "height must be int", r), 
                   1419:                params.as_int(4, "start degrees must be int", r), 
                   1420:                params.as_int(5, "end degrees must be int", r), 
1.108     paf      1421:                image.Color(params.as_int(6, "color must be int", r)));
1.49      parser   1422: }
                   1423: 
1.91      paf      1424: static void _circle(Request& r, MethodParams& params) {
1.108     paf      1425:        gdImage& image=GET_SELF(r, VImage).image();
1.48      parser   1426: 
1.91      paf      1427:        int size=params.as_int(2, "radius must be int", r)*2;
1.108     paf      1428:        image.Arc(
1.91      paf      1429:                params.as_int(0, "center_x must be int", r), 
                   1430:                params.as_int(1, "center_y must be int", r), 
1.50      parser   1431:                size, //w
                   1432:                size, //h
1.48      parser   1433:                0, //s
                   1434:                360, //e
1.108     paf      1435:                image.Color(params.as_int(3, "color must be int", r)));
1.48      parser   1436: }
                   1437: 
1.108     paf      1438: gdImage& as_image(MethodParams& params, int index, const char* msg) {
1.91      paf      1439:        Value& value=params.as_no_junction(index, msg);
1.53      parser   1440: 
1.130     misha    1441:        if(Value* vimage=value.as(VIMAGE_TYPE)) {
1.108     paf      1442:                return static_cast<VImage *>(vimage)->image();
1.75      paf      1443:        } else
1.155     moko     1444:                throw Exception(PARSER_RUNTIME, 0, msg);
1.53      parser   1445: }
                   1446: 
1.91      paf      1447: static void _copy(Request& r, MethodParams& params) {
1.108     paf      1448:        gdImage& dest=GET_SELF(r, VImage).image();
1.53      parser   1449: 
1.108     paf      1450:        gdImage& src=as_image(params, 0, "src must be image");
1.53      parser   1451: 
1.91      paf      1452:        int sx=params.as_int(1, "src_x must be int", r);
                   1453:        int sy=params.as_int(2, "src_y must be int", r);
                   1454:        int sw=params.as_int(3, "src_w must be int", r);
                   1455:        int sh=params.as_int(4, "src_h must be int", r);
                   1456:        int dx=params.as_int(5, "dest_x must be int", r);
                   1457:        int dy=params.as_int(6, "dest_y must be int", r);
                   1458:        if(params.count()>1+2+2+2) {
                   1459:                int dw=params.as_int(1+2+2+2, "dest_w must be int", r);
                   1460:                int dh=(int)(params.count()>1+2+2+2+1?
                   1461:                        params.as_int(1+2+2+2+1, "dest_h must be int", r):sh*(((double)dw)/((double)sw)));
                   1462:                int tolerance=params.count()>1+2+2+2+2?
                   1463:                        params.as_int(1+2+2+2+2, "tolerance must be int", r):150;
1.53      parser   1464: 
1.108     paf      1465:                src.CopyResampled(dest, dx, dy, sx, sy, dw, dh, sw, sh, tolerance);
1.53      parser   1466:        } else
1.108     paf      1467:                src.Copy(dest, dx, dy, sx, sy, sw, sh);
                   1468: }
                   1469: 
                   1470: static void _pixel(Request& r, MethodParams& params) {
                   1471:        gdImage& image=GET_SELF(r, VImage).image();
                   1472: 
1.109     paf      1473:        int x=params.as_int(0, "x must be int", r); 
                   1474:        int y=params.as_int(1, "y must be int", r);
                   1475: 
                   1476:        if(params.count()>2) {
                   1477:                image.SetPixel(x, y, 
                   1478:                        image.Color(params.as_int(2, "color must be int", r)));
                   1479:        } else 
1.157     moko     1480:                r.write(*new VInt(image.DecodeColor(image.GetPixel(x, y))));
1.53      parser   1481: }
                   1482: 
                   1483: 
1.22      paf      1484: // constructor
                   1485: 
1.91      paf      1486: MImage::MImage(): Methoded("image") {
1.1       paf      1487:        // ^image:measure[DATA]
1.163     moko     1488:        // ^image:measure[DATA; $.exif(false) $.xmp(false) $.xmp-charset[UTF-8] ]
                   1489:        add_native_method("measure", Method::CT_DYNAMIC, _measure, 1, 2);
1.3       paf      1490: 
1.25      paf      1491:        // ^image.html[]
                   1492:        // ^image.html[hash]
1.22      paf      1493:        add_native_method("html", Method::CT_DYNAMIC, _html, 0, 1);
1.6       paf      1494: 
1.25      paf      1495:        // ^image.load[background.gif]
1.22      paf      1496:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 1);
1.6       paf      1497: 
1.25      paf      1498:        // ^image.create[width;height] bgcolor=white
                   1499:        // ^image.create[width;height;bgcolor]
1.22      paf      1500:        add_native_method("create", Method::CT_DYNAMIC, _create, 2, 3);
1.6       paf      1501: 
1.25      paf      1502:        // ^image.gif[]
1.95      paf      1503:        add_native_method("gif", Method::CT_DYNAMIC, _gif, 0, 1);
1.12      paf      1504: 
1.25      paf      1505:        // ^image.line(x0;y0;x1;y1;color)
1.22      paf      1506:        add_native_method("line", Method::CT_DYNAMIC, _line, 5, 5);
1.13      paf      1507: 
1.25      paf      1508:        // ^image.fill(x;y;color)
1.22      paf      1509:        add_native_method("fill", Method::CT_DYNAMIC, _fill, 3, 3);
1.13      paf      1510: 
1.25      paf      1511:        // ^image.rectangle(x0;y0;x1;y1;color)
1.22      paf      1512:        add_native_method("rectangle", Method::CT_DYNAMIC, _rectangle, 5, 5);
1.13      paf      1513: 
1.25      paf      1514:        // ^image.bar(x0;y0;x1;y1;color)
1.22      paf      1515:        add_native_method("bar", Method::CT_DYNAMIC, _bar, 5, 5);
1.13      paf      1516: 
1.44      parser   1517:        // ^image.replace(color-source;color-dest)[table x:y]
1.135     misha    1518:        // ^image.replace(color-source;color-dest)
                   1519:        add_native_method("replace", Method::CT_DYNAMIC, _replace, 2, 3);
1.44      parser   1520: 
                   1521:        // ^image.polyline(color)[table x:y]
                   1522:        add_native_method("polyline", Method::CT_DYNAMIC, _polyline, 2, 2);
1.13      paf      1523: 
1.44      parser   1524:        // ^image.polygon(color)[table x:y]
                   1525:        add_native_method("polygon", Method::CT_DYNAMIC, _polygon, 2, 2);
1.13      paf      1526: 
1.44      parser   1527:        // ^image.polybar(color)[table x:y]
                   1528:        add_native_method("polybar", Method::CT_DYNAMIC, _polybar, 2, 2);
1.13      paf      1529: 
1.125     misha    1530:        // ^image.font[alPHAbet;font-file-name.gif]
                   1531:        // ^image.font[alPHAbet;font-file-name.gif](spacebar_width)
                   1532:        // ^image.font[alPHAbet;font-file-name.gif](spacebar_width;letter_width)
                   1533:        // ^image.font[alPHAbet;font-file-name.gif][$.space-width(.) $.letter-width(.) $.letter-space(.)]
                   1534:        add_native_method("font", Method::CT_DYNAMIC, _font, 2, 4);
1.16      paf      1535: 
1.125     misha    1536:        // ^image.text(x;y)[text]
1.22      paf      1537:        add_native_method("text", Method::CT_DYNAMIC, _text, 3, 3);
1.47      parser   1538:        
1.125     misha    1539:        // ^image.length[text]
1.47      parser   1540:        add_native_method("length", Method::CT_DYNAMIC, _length, 1, 1);
1.16      paf      1541:        
1.48      parser   1542:        // ^image.arc(center x;center y;width;height;start in degrees;end in degrees;color)
                   1543:        add_native_method("arc", Method::CT_DYNAMIC, _arc, 7, 7);
1.49      parser   1544: 
                   1545:        // ^image.sector(center x;center y;width;height;start in degrees;end in degrees;color)
                   1546:        add_native_method("sector", Method::CT_DYNAMIC, _sector, 7, 7);
1.48      parser   1547: 
                   1548:        // ^image.circle(center x;center y;r;color)
                   1549:        add_native_method("circle", Method::CT_DYNAMIC, _circle, 4, 4);
                   1550: 
1.56      parser   1551:        // ^image.copy[source](src x;src y;src w;src h;dst x;dst y[;dest w[;dest h[;tolerance]]])
                   1552:        add_native_method("copy", Method::CT_DYNAMIC, _copy, 1+2+2+2, (1+2+2+2)+2+1);
1.108     paf      1553: 
                   1554:        // ^image.pixel(x;y)[(color)]
1.109     paf      1555:        add_native_method("pixel", Method::CT_DYNAMIC, _pixel, 2, 3);
1.1       paf      1556: }

E-mail: