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

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

E-mail: