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

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

E-mail: