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

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

E-mail: