IMG_ImageIO.m
author Sam Lantinga <slouken@libsdl.org>
Tue, 01 Jan 2013 11:40:47 -0800
changeset 340 3999783ed889
parent 332 5a8a45cd54c9
child 368 8a61842d00ce
permissions -rw-r--r--
Fixed bug 1413 - Cannot load images with ImageIO enabled on Mac OS X

The attached diff fixes the library so ImageIO can be used and images are
displayed again without corruption and black screens.

(Based on http://pastebin.com/T3s15UXF and
http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html)

I suspect the matrix passed to CGColorSpaceCreateCalibratedRGB() as implemented
in r292 is invalid and the CoreGraphics framework on 10.5 doesn't reject it,
but later ones do. Unfortunately all the documentation I can find doesn't
actually specify what the valid range of values of the arguments is.
slouken@187
     1
/*
slouken@187
     2
 *  IMG_ImageIO.c
slouken@187
     3
 *  SDL_image
slouken@187
     4
 *
slouken@187
     5
 *  Created by Eric Wing on 1/1/09.
slouken@187
     6
 *  Copyright 2009 __MyCompanyName__. All rights reserved.
slouken@187
     7
 *
slouken@187
     8
 */
slouken@240
     9
slouken@240
    10
#if defined(__APPLE__) && !defined(SDL_IMAGE_USE_COMMON_BACKEND)
slouken@240
    11
slouken@187
    12
#include "SDL_image.h"
slouken@187
    13
ewing@270
    14
// Used because CGDataProviderCreate became deprecated in 10.5
ewing@270
    15
#include <AvailabilityMacros.h>
ewing@270
    16
#include <TargetConditionals.h>
slouken@279
    17
#include <Foundation/Foundation.h>
ewing@270
    18
ewing@270
    19
#if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)
slouken@279
    20
#ifdef ALLOW_UIIMAGE_FALLBACK
slouken@279
    21
#define USE_UIIMAGE_BACKEND() ([UIImage instancesRespondToSelector:@selector(initWithCGImage:scale:orientation:)] == NO)
slouken@279
    22
#else
slouken@279
    23
#define USE_UIIMAGE_BACKEND() (Internal_checkImageIOisAvailable())
slouken@279
    24
#endif
ewing@270
    25
#import <MobileCoreServices/MobileCoreServices.h> // for UTCoreTypes.h
ewing@270
    26
#import <ImageIO/ImageIO.h>
slouken@279
    27
#import <UIKit/UIImage.h>
ewing@270
    28
#else
slouken@187
    29
// For ImageIO framework and also LaunchServices framework (for UTIs)
slouken@187
    30
#include <ApplicationServices/ApplicationServices.h>
ewing@270
    31
#endif
slouken@187
    32
slouken@187
    33
/**************************************************************
slouken@187
    34
 ***** Begin Callback functions for block reading *************
slouken@187
    35
 **************************************************************/
slouken@187
    36
slouken@187
    37
// This callback reads some bytes from an SDL_rwops and copies it
slouken@187
    38
// to a Quartz buffer (supplied by Apple framework).
slouken@187
    39
static size_t MyProviderGetBytesCallback(void* rwops_userdata, void* quartz_buffer, size_t the_count)
slouken@187
    40
{
slouken@279
    41
    return (size_t)SDL_RWread((struct SDL_RWops *)rwops_userdata, quartz_buffer, 1, the_count);
slouken@187
    42
}
slouken@187
    43
slouken@187
    44
// This callback is triggered when the data provider is released
slouken@187
    45
// so you can clean up any resources.
slouken@187
    46
static void MyProviderReleaseInfoCallback(void* rwops_userdata)
slouken@187
    47
{
slouken@279
    48
    // What should I put here? 
slouken@279
    49
    // I think the user and SDL_RWops controls closing, so I don't do anything.
slouken@187
    50
}
slouken@187
    51
slouken@187
    52
static void MyProviderRewindCallback(void* rwops_userdata)
slouken@187
    53
{
slouken@279
    54
    SDL_RWseek((struct SDL_RWops *)rwops_userdata, 0, RW_SEEK_SET);
slouken@187
    55
}
slouken@187
    56
slouken@200
    57
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 // CGDataProviderCreateSequential was introduced in 10.5; CGDataProviderCreate is deprecated
slouken@200
    58
off_t MyProviderSkipForwardBytesCallback(void* rwops_userdata, off_t the_count)
slouken@200
    59
{
slouken@279
    60
    off_t start_position = SDL_RWtell((struct SDL_RWops *)rwops_userdata);
slouken@279
    61
    SDL_RWseek((struct SDL_RWops *)rwops_userdata, the_count, RW_SEEK_CUR);
slouken@200
    62
    off_t end_position = SDL_RWtell((struct SDL_RWops *)rwops_userdata);
slouken@200
    63
    return (end_position - start_position);	
slouken@200
    64
}
slouken@200
    65
#else // CGDataProviderCreate was deprecated in 10.5
slouken@187
    66
static void MyProviderSkipBytesCallback(void* rwops_userdata, size_t the_count)
slouken@187
    67
{
slouken@279
    68
    SDL_RWseek((struct SDL_RWops *)rwops_userdata, the_count, RW_SEEK_CUR);
slouken@187
    69
}
slouken@200
    70
#endif
slouken@200
    71
slouken@187
    72
/**************************************************************
slouken@187
    73
 ***** End Callback functions for block reading ***************
slouken@187
    74
 **************************************************************/
slouken@187
    75
slouken@187
    76
// This creates a CGImageSourceRef which is a handle to an image that can be used to examine information
slouken@187
    77
// about the image or load the actual image data.
slouken@187
    78
static CGImageSourceRef CreateCGImageSourceFromRWops(SDL_RWops* rw_ops, CFDictionaryRef hints_and_options)
slouken@187
    79
{
slouken@279
    80
    CGImageSourceRef source_ref;
slouken@279
    81
    
slouken@279
    82
    // Similar to SDL_RWops, Apple has their own callbacks for dealing with data streams.
slouken@279
    83
    
slouken@200
    84
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 // CGDataProviderCreateSequential was introduced in 10.5; CGDataProviderCreate is deprecated
slouken@279
    85
    CGDataProviderSequentialCallbacks provider_callbacks =
slouken@279
    86
    {
slouken@200
    87
        0,
slouken@279
    88
        MyProviderGetBytesCallback,
slouken@279
    89
        MyProviderSkipForwardBytesCallback,
slouken@279
    90
        MyProviderRewindCallback,
slouken@279
    91
        MyProviderReleaseInfoCallback
slouken@279
    92
    };
slouken@279
    93
    
slouken@279
    94
    CGDataProviderRef data_provider = CGDataProviderCreateSequential(rw_ops, &provider_callbacks);
slouken@279
    95
    
slouken@279
    96
    
slouken@200
    97
#else // CGDataProviderCreate was deprecated in 10.5
slouken@279
    98
    
slouken@279
    99
    CGDataProviderCallbacks provider_callbacks =
slouken@279
   100
    {
slouken@279
   101
        MyProviderGetBytesCallback,
slouken@279
   102
        MyProviderSkipBytesCallback,
slouken@279
   103
        MyProviderRewindCallback,
slouken@279
   104
        MyProviderReleaseInfoCallback
slouken@279
   105
    };
slouken@279
   106
    
slouken@279
   107
    CGDataProviderRef data_provider = CGDataProviderCreate(rw_ops, &provider_callbacks);
slouken@200
   108
#endif
slouken@279
   109
    // Get the CGImageSourceRef.
slouken@279
   110
    // The dictionary can be NULL or contain hints to help ImageIO figure out the image type.
slouken@279
   111
    source_ref = CGImageSourceCreateWithDataProvider(data_provider, hints_and_options);
slouken@283
   112
    CGDataProviderRelease(data_provider);
slouken@279
   113
    return source_ref;
slouken@187
   114
}
slouken@187
   115
slouken@187
   116
/* Create a CGImageSourceRef from a file. */
slouken@187
   117
/* Remember to CFRelease the created source when done. */
slouken@187
   118
static CGImageSourceRef CreateCGImageSourceFromFile(const char* the_path)
slouken@187
   119
{
slouken@187
   120
    CFURLRef the_url = NULL;
slouken@187
   121
    CGImageSourceRef source_ref = NULL;
slouken@279
   122
    CFStringRef cf_string = NULL;
slouken@279
   123
    
slouken@279
   124
    /* Create a CFString from a C string */
slouken@279
   125
    cf_string = CFStringCreateWithCString(NULL, the_path, kCFStringEncodingUTF8);
slouken@279
   126
    if (!cf_string) {
slouken@279
   127
        return NULL;
slouken@279
   128
    }
slouken@279
   129
    
slouken@279
   130
    /* Create a CFURL from a CFString */
slouken@279
   131
    the_url = CFURLCreateWithFileSystemPath(NULL, cf_string, kCFURLPOSIXPathStyle, false);
slouken@279
   132
    
slouken@279
   133
    /* Don't need the CFString any more (error or not) */
slouken@279
   134
    CFRelease(cf_string);
slouken@279
   135
    
slouken@279
   136
    if(!the_url)
slouken@279
   137
    {
slouken@279
   138
        return NULL;
slouken@279
   139
    }
slouken@279
   140
    
slouken@279
   141
    
slouken@187
   142
    source_ref = CGImageSourceCreateWithURL(the_url, NULL);
slouken@279
   143
    /* Don't need the URL any more (error or not) */
slouken@279
   144
    CFRelease(the_url);
slouken@279
   145
    
slouken@279
   146
    return source_ref;
slouken@187
   147
}
slouken@187
   148
slouken@187
   149
static CGImageRef CreateCGImageFromCGImageSource(CGImageSourceRef image_source)
slouken@187
   150
{
slouken@279
   151
    CGImageRef image_ref = NULL;
slouken@279
   152
    
slouken@279
   153
    if(NULL == image_source)
slouken@279
   154
    {
slouken@279
   155
        return NULL;
slouken@279
   156
    }
slouken@279
   157
    
slouken@279
   158
    // Get the first item in the image source (some image formats may
slouken@279
   159
    // contain multiple items).
slouken@279
   160
    image_ref = CGImageSourceCreateImageAtIndex(image_source, 0, NULL);
slouken@279
   161
    if(NULL == image_ref)
slouken@279
   162
    {
slouken@279
   163
        IMG_SetError("CGImageSourceCreateImageAtIndex() failed");
slouken@279
   164
    }
slouken@279
   165
    return image_ref;
slouken@187
   166
}
slouken@187
   167
slouken@187
   168
static CFDictionaryRef CreateHintDictionary(CFStringRef uti_string_hint)
slouken@187
   169
{
slouken@279
   170
    CFDictionaryRef hint_dictionary = NULL;
slouken@279
   171
    
slouken@279
   172
    if(uti_string_hint != NULL)
slouken@279
   173
    {
slouken@279
   174
        // Do a bunch of work to setup a CFDictionary containing the jpeg compression properties.
slouken@279
   175
        CFStringRef the_keys[1];
slouken@279
   176
        CFStringRef the_values[1];
slouken@279
   177
        
slouken@279
   178
        the_keys[0] = kCGImageSourceTypeIdentifierHint;
slouken@279
   179
        the_values[0] = uti_string_hint;
slouken@279
   180
        
slouken@279
   181
        // kCFTypeDictionaryKeyCallBacks or kCFCopyStringDictionaryKeyCallBacks?
slouken@279
   182
        hint_dictionary = CFDictionaryCreate(NULL, (const void**)&the_keys, (const void**)&the_values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
slouken@279
   183
    }
slouken@279
   184
    return hint_dictionary;
slouken@187
   185
}
slouken@187
   186
slouken@187
   187
// Once we have our image, we need to get it into an SDL_Surface
slouken@308
   188
static SDL_Surface* Create_SDL_Surface_From_CGImage_RGB(CGImageRef image_ref)
slouken@187
   189
{
slouken@279
   190
    /* This code is adapted from Apple's Documentation found here:
slouken@279
   191
     * http://developer.apple.com/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/index.html
slouken@279
   192
     * Listing 9-4††Using a Quartz image as a texture source.
slouken@279
   193
     * Unfortunately, this guide doesn't show what to do about
slouken@279
   194
     * non-RGBA image formats so I'm making the rest up.
slouken@279
   195
     * All this code should be scrutinized.
slouken@279
   196
     */
slouken@279
   197
    
slouken@279
   198
    size_t w = CGImageGetWidth(image_ref);
slouken@279
   199
    size_t h = CGImageGetHeight(image_ref);
slouken@279
   200
    CGRect rect = {{0, 0}, {w, h}};
slouken@279
   201
    
slouken@279
   202
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image_ref);
slouken@279
   203
    //size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref);
slouken@279
   204
    size_t bits_per_component = 8;
slouken@279
   205
    
slouken@279
   206
    SDL_Surface* surface;
slouken@279
   207
    Uint32 Amask;
slouken@279
   208
    Uint32 Rmask;
slouken@279
   209
    Uint32 Gmask;
slouken@279
   210
    Uint32 Bmask;
slouken@279
   211
    
slouken@279
   212
    CGContextRef bitmap_context;
slouken@279
   213
    CGBitmapInfo bitmap_info;
slouken@292
   214
slouken@292
   215
	/* This sets up a color space that results in identical values
slouken@292
   216
	 * as the image data itself, which is the same as the standalone
slouken@292
   217
	 * libpng loader.
slouken@292
   218
	 * Thanks to Allegro. :)
slouken@292
   219
	 */
slouken@340
   220
	CGFloat whitePoint[3] = { 0.950, 1.000, 1.089 };
slouken@340
   221
	CGFloat blackPoint[3] = { 0.000, 0.000, 0.000 };
slouken@292
   222
	CGFloat gamma[3] = { 2.2, 2.2, 2.2 };
slouken@292
   223
	CGFloat matrix[9] = {
slouken@340
   224
		0.412, 0.213, 0.019,
slouken@340
   225
		0.358, 0.715, 0.119,
slouken@340
   226
		0.180, 0.072, 0.950
slouken@292
   227
	};
slouken@292
   228
	CGColorSpaceRef color_space =
slouken@292
   229
		CGColorSpaceCreateCalibratedRGB(
slouken@292
   230
									whitePoint, blackPoint, gamma, matrix
slouken@292
   231
									);   
slouken@292
   232
	
slouken@279
   233
    if (alpha == kCGImageAlphaNone ||
slouken@279
   234
        alpha == kCGImageAlphaNoneSkipFirst ||
slouken@279
   235
        alpha == kCGImageAlphaNoneSkipLast) {
slouken@279
   236
        bitmap_info = kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Host; /* XRGB */
slouken@279
   237
        Amask = 0x00000000;
slouken@279
   238
    } else {
slouken@279
   239
        /* kCGImageAlphaFirst isn't supported */
slouken@279
   240
        //bitmap_info = kCGImageAlphaFirst | kCGBitmapByteOrder32Host; /* ARGB */
slouken@279
   241
        bitmap_info = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host; /* ARGB */
slouken@279
   242
        Amask = 0xFF000000;
slouken@279
   243
    }
slouken@279
   244
    
slouken@279
   245
    Rmask = 0x00FF0000;
slouken@279
   246
    Gmask = 0x0000FF00;
slouken@279
   247
    Bmask = 0x000000FF;
slouken@279
   248
    
slouken@279
   249
    surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, Rmask, Gmask, Bmask, Amask);
slouken@279
   250
    if (surface)
slouken@279
   251
    {
slouken@279
   252
        // Sets up a context to be drawn to with surface->pixels as the area to be drawn to
slouken@279
   253
        bitmap_context = CGBitmapContextCreate(
slouken@279
   254
                                               surface->pixels,
slouken@279
   255
                                               surface->w,
slouken@279
   256
                                               surface->h,
slouken@279
   257
                                               bits_per_component,
slouken@279
   258
                                               surface->pitch,
slouken@279
   259
                                               color_space,
slouken@279
   260
                                               bitmap_info
slouken@279
   261
                                               );
slouken@279
   262
        
slouken@279
   263
        // Draws the image into the context's image_data
slouken@279
   264
        CGContextDrawImage(bitmap_context, rect, image_ref);
slouken@279
   265
        
slouken@279
   266
        CGContextRelease(bitmap_context);
slouken@279
   267
        
slouken@279
   268
        // FIXME: Reverse the premultiplied alpha
slouken@279
   269
        if ((bitmap_info & kCGBitmapAlphaInfoMask) == kCGImageAlphaPremultipliedFirst) {
slouken@279
   270
            int i, j;
slouken@279
   271
            Uint8 *p = (Uint8 *)surface->pixels;
slouken@279
   272
            for (i = surface->h * surface->pitch/4; i--; ) {
slouken@240
   273
#if __LITTLE_ENDIAN__
slouken@279
   274
                Uint8 A = p[3];
slouken@279
   275
                if (A) {
slouken@279
   276
                    for (j = 0; j < 3; ++j) {
slouken@279
   277
                        p[j] = (p[j] * 255) / A;
slouken@279
   278
                    }
slouken@279
   279
                }
slouken@240
   280
#else
slouken@279
   281
                Uint8 A = p[0];
slouken@279
   282
                if (A) {
slouken@279
   283
                    for (j = 1; j < 4; ++j) {
slouken@279
   284
                        p[j] = (p[j] * 255) / A;
slouken@279
   285
                    }
slouken@279
   286
                }
slouken@240
   287
#endif /* ENDIAN */
slouken@279
   288
                p += 4;
slouken@279
   289
            }
slouken@279
   290
        }
slouken@279
   291
    }
slouken@279
   292
    
slouken@279
   293
    if (color_space)
slouken@279
   294
    {
slouken@279
   295
        CGColorSpaceRelease(color_space);			
slouken@279
   296
    }
slouken@279
   297
    
slouken@279
   298
    return surface;
slouken@187
   299
}
slouken@308
   300
static SDL_Surface* Create_SDL_Surface_From_CGImage_Index(CGImageRef image_ref)
slouken@308
   301
{
slouken@308
   302
    size_t w = CGImageGetWidth(image_ref);
slouken@308
   303
    size_t h = CGImageGetHeight(image_ref);
slouken@308
   304
    size_t bits_per_pixel = CGImageGetBitsPerPixel(image_ref);
slouken@308
   305
    size_t bytes_per_row = CGImageGetBytesPerRow(image_ref);
slouken@308
   306
slouken@308
   307
    SDL_Surface* surface;
slouken@308
   308
    SDL_Palette* palette;
slouken@308
   309
	CGColorSpaceRef color_space = CGImageGetColorSpace(image_ref);
slouken@308
   310
    CGColorSpaceRef base_color_space = CGColorSpaceGetBaseColorSpace(color_space);
slouken@308
   311
    size_t num_components = CGColorSpaceGetNumberOfComponents(base_color_space);
slouken@308
   312
    size_t num_entries = CGColorSpaceGetColorTableCount(color_space);
slouken@308
   313
    uint8_t *entry, entries[num_components * num_entries];
slouken@308
   314
slouken@308
   315
    /* What do we do if it's not RGB? */
slouken@308
   316
    if (num_components != 3) {
slouken@308
   317
        SDL_SetError("Unknown colorspace components %lu", num_components);
slouken@308
   318
        return NULL;
slouken@308
   319
    }
slouken@308
   320
    if (bits_per_pixel != 8) {
slouken@308
   321
        SDL_SetError("Unknown bits_per_pixel %lu", bits_per_pixel);
slouken@308
   322
        return NULL;
slouken@308
   323
    }
slouken@308
   324
slouken@308
   325
    CGColorSpaceGetColorTable(color_space, entries);
slouken@308
   326
    surface = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bits_per_pixel, 0, 0, 0, 0);
slouken@308
   327
    if (surface) {
slouken@308
   328
        uint8_t* pixels = (uint8_t*)surface->pixels;
slouken@308
   329
        CGDataProviderRef provider = CGImageGetDataProvider(image_ref);
slouken@308
   330
        NSData* data = (id)CGDataProviderCopyData(provider);
slouken@308
   331
        [data autorelease];
slouken@308
   332
        const uint8_t* bytes = [data bytes];
slouken@308
   333
        size_t i;
slouken@308
   334
slouken@308
   335
        palette = surface->format->palette;
slouken@308
   336
        for (i = 0, entry = entries; i < num_entries; ++i) {
slouken@308
   337
            palette->colors[i].r = entry[0];
slouken@308
   338
            palette->colors[i].g = entry[1];
slouken@308
   339
            palette->colors[i].b = entry[2];
slouken@308
   340
            entry += num_components;
slouken@308
   341
        }
slouken@308
   342
slouken@308
   343
        for (i = 0; i < h; ++i) {
slouken@308
   344
            SDL_memcpy(pixels, bytes, w);
slouken@308
   345
            pixels += surface->pitch;
slouken@308
   346
            bytes += bytes_per_row;
slouken@308
   347
        }
slouken@308
   348
    }
slouken@308
   349
    return surface;
slouken@308
   350
}
slouken@308
   351
static SDL_Surface* Create_SDL_Surface_From_CGImage(CGImageRef image_ref)
slouken@308
   352
{
slouken@308
   353
	CGColorSpaceRef color_space = CGImageGetColorSpace(image_ref);
slouken@308
   354
    if (CGColorSpaceGetModel(color_space) == kCGColorSpaceModelIndexed) {
slouken@308
   355
        return Create_SDL_Surface_From_CGImage_Index(image_ref);
slouken@308
   356
    } else {
slouken@308
   357
        return Create_SDL_Surface_From_CGImage_RGB(image_ref);
slouken@308
   358
    }
slouken@308
   359
}
slouken@187
   360
slouken@187
   361
slouken@279
   362
#pragma mark -
slouken@279
   363
#pragma mark IMG_Init stubs
slouken@279
   364
#if !defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1))
slouken@279
   365
static int Internal_checkImageIOisAvailable() {
slouken@279
   366
    // just check if we are running on ios 4 or more, else throw exception
slouken@279
   367
    if ([UIImage instancesRespondToSelector:@selector(initWithCGImage:scale:orientation:)])
slouken@279
   368
        return 0;
slouken@279
   369
    [NSException raise:@"UIImage fallback not enabled at compile time"
slouken@279
   370
                format:@"ImageIO is not available on your platform, please recompile SDL_Image with ALLOW_UIIMAGE_FALLBACK."];
slouken@279
   371
    return -1;
slouken@187
   372
}
slouken@279
   373
#endif
slouken@188
   374
slouken@233
   375
int IMG_InitJPG()
slouken@233
   376
{
slouken@279
   377
    return 0;
slouken@233
   378
}
slouken@233
   379
slouken@233
   380
void IMG_QuitJPG()
slouken@233
   381
{
slouken@233
   382
}
slouken@233
   383
slouken@233
   384
int IMG_InitPNG()
slouken@233
   385
{
slouken@279
   386
    return 0;
slouken@233
   387
}
slouken@233
   388
slouken@233
   389
void IMG_QuitPNG()
slouken@233
   390
{
slouken@233
   391
}
slouken@233
   392
slouken@233
   393
int IMG_InitTIF()
slouken@233
   394
{
slouken@279
   395
    return 0;
slouken@233
   396
}
slouken@233
   397
slouken@233
   398
void IMG_QuitTIF()
slouken@233
   399
{
slouken@233
   400
}
slouken@188
   401
slouken@279
   402
#pragma mark -
slouken@279
   403
#pragma mark Get type of image
slouken@279
   404
static int Internal_isType_UIImage (SDL_RWops *rw_ops, CFStringRef uti_string_to_test)
slouken@279
   405
{
slouken@279
   406
    int is_type = 0;
slouken@279
   407
    
slouken@279
   408
#if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1))
slouken@279
   409
    int start = SDL_RWtell(rw_ops);
slouken@279
   410
    if ((0 == CFStringCompare(uti_string_to_test, kUTTypeICO, 0)) ||
slouken@279
   411
        (0 == CFStringCompare(uti_string_to_test, CFSTR("com.microsoft.cur"), 0))) {
slouken@279
   412
        
slouken@279
   413
        // The Win32 ICO file header (14 bytes)
slouken@279
   414
        Uint16 bfReserved;
slouken@279
   415
        Uint16 bfType;
slouken@279
   416
        Uint16 bfCount;
slouken@279
   417
        int type = (0 == CFStringCompare(uti_string_to_test, kUTTypeICO, 0)) ? 1 : 2;
slouken@279
   418
        
slouken@279
   419
        bfReserved = SDL_ReadLE16(rw_ops);
slouken@279
   420
        bfType = SDL_ReadLE16(rw_ops);
slouken@279
   421
        bfCount = SDL_ReadLE16(rw_ops);
slouken@279
   422
        if ((bfReserved == 0) && (bfType == type) && (bfCount != 0)) 
slouken@279
   423
            is_type = 1;
slouken@279
   424
    } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeBMP, 0)) {
slouken@279
   425
        char magic[2];
slouken@279
   426
        
slouken@279
   427
        if ( SDL_RWread(rw_ops, magic, sizeof(magic), 1) ) {
slouken@279
   428
            if ( strncmp(magic, "BM", 2) == 0 ) {
slouken@279
   429
                is_type = 1;
slouken@279
   430
            }
slouken@279
   431
        }
slouken@279
   432
    } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeGIF, 0)) {
slouken@279
   433
        char magic[6];
slouken@279
   434
        
slouken@279
   435
        if ( SDL_RWread(rw_ops, magic, sizeof(magic), 1) ) {
slouken@279
   436
            if ( (strncmp(magic, "GIF", 3) == 0) &&
slouken@279
   437
                ((memcmp(magic + 3, "87a", 3) == 0) ||
slouken@279
   438
                 (memcmp(magic + 3, "89a", 3) == 0)) ) {
slouken@279
   439
                    is_type = 1;
slouken@279
   440
                }
slouken@279
   441
        }
slouken@279
   442
    } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeJPEG, 0)) {
slouken@279
   443
        int in_scan = 0;
slouken@279
   444
        Uint8 magic[4];
slouken@279
   445
        
slouken@279
   446
        // This detection code is by Steaphan Greene <stea@cs.binghamton.edu>
slouken@279
   447
        // Blame me, not Sam, if this doesn't work right. */
slouken@279
   448
        // And don't forget to report the problem to the the sdl list too! */
slouken@279
   449
        
slouken@279
   450
        if ( SDL_RWread(rw_ops, magic, 2, 1) ) {
slouken@279
   451
            if ( (magic[0] == 0xFF) && (magic[1] == 0xD8) ) {
slouken@279
   452
                is_type = 1;
slouken@279
   453
                while (is_type == 1) {
slouken@279
   454
                    if(SDL_RWread(rw_ops, magic, 1, 2) != 2) {
slouken@279
   455
                        is_type = 0;
slouken@279
   456
                    } else if( (magic[0] != 0xFF) && (in_scan == 0) ) {
slouken@279
   457
                        is_type = 0;
slouken@279
   458
                    } else if( (magic[0] != 0xFF) || (magic[1] == 0xFF) ) {
slouken@279
   459
                        /* Extra padding in JPEG (legal) */
slouken@279
   460
                        /* or this is data and we are scanning */
slouken@279
   461
                        SDL_RWseek(rw_ops, -1, SEEK_CUR);
slouken@279
   462
                    } else if(magic[1] == 0xD9) {
slouken@279
   463
                        /* Got to end of good JPEG */
slouken@279
   464
                        break;
slouken@279
   465
                    } else if( (in_scan == 1) && (magic[1] == 0x00) ) {
slouken@279
   466
                        /* This is an encoded 0xFF within the data */
slouken@279
   467
                    } else if( (magic[1] >= 0xD0) && (magic[1] < 0xD9) ) {
slouken@279
   468
                        /* These have nothing else */
slouken@279
   469
                    } else if(SDL_RWread(rw_ops, magic+2, 1, 2) != 2) {
slouken@279
   470
                        is_type = 0;
slouken@279
   471
                    } else {
slouken@279
   472
                        /* Yes, it's big-endian */
slouken@279
   473
                        Uint32 start;
slouken@279
   474
                        Uint32 size;
slouken@279
   475
                        Uint32 end;
slouken@279
   476
                        start = SDL_RWtell(rw_ops);
slouken@279
   477
                        size = (magic[2] << 8) + magic[3];
slouken@279
   478
                        end = SDL_RWseek(rw_ops, size-2, SEEK_CUR);
slouken@279
   479
                        if ( end != start + size - 2 ) is_type = 0;
slouken@279
   480
                        if ( magic[1] == 0xDA ) {
slouken@279
   481
                            /* Now comes the actual JPEG meat */
slouken@279
   482
#ifdef	FAST_IS_JPEG
slouken@279
   483
                            /* Ok, I'm convinced.  It is a JPEG. */
slouken@279
   484
                            break;
slouken@279
   485
#else
slouken@279
   486
                            /* I'm not convinced.  Prove it! */
slouken@279
   487
                            in_scan = 1;
slouken@279
   488
#endif
slouken@279
   489
                        }
slouken@279
   490
                    }
slouken@279
   491
                }
slouken@279
   492
            }
slouken@279
   493
        }
slouken@279
   494
    } else if (0 == CFStringCompare(uti_string_to_test, kUTTypePNG, 0)) {
slouken@279
   495
        Uint8 magic[4];
slouken@279
   496
        
slouken@279
   497
        if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) {
slouken@279
   498
            if ( magic[0] == 0x89 &&
slouken@279
   499
                magic[1] == 'P' &&
slouken@279
   500
                magic[2] == 'N' &&
slouken@279
   501
                magic[3] == 'G' ) {
slouken@279
   502
                is_type = 1;
slouken@279
   503
            }
slouken@279
   504
        }
slouken@279
   505
    } else if (0 == CFStringCompare(uti_string_to_test, CFSTR("com.truevision.tga-image"), 0)) {
slouken@279
   506
        //TODO: fill me!
slouken@279
   507
    } else if (0 == CFStringCompare(uti_string_to_test, kUTTypeTIFF, 0)) {
slouken@279
   508
        Uint8 magic[4];
slouken@279
   509
        
slouken@279
   510
        if ( SDL_RWread(rw_ops, magic, 1, sizeof(magic)) == sizeof(magic) ) {
slouken@279
   511
            if ( (magic[0] == 'I' &&
slouken@279
   512
                  magic[1] == 'I' &&
slouken@279
   513
                  magic[2] == 0x2a &&
slouken@279
   514
                  magic[3] == 0x00) ||
slouken@279
   515
                (magic[0] == 'M' &&
slouken@279
   516
                 magic[1] == 'M' &&
slouken@279
   517
                 magic[2] == 0x00 &&
slouken@279
   518
                 magic[3] == 0x2a) ) {
slouken@279
   519
                    is_type = 1;
slouken@279
   520
                }
slouken@279
   521
        }
slouken@279
   522
    }
slouken@279
   523
    
slouken@279
   524
    // reset the file descption pointer
slouken@279
   525
    SDL_RWseek(rw_ops, start, SEEK_SET);
slouken@279
   526
slouken@279
   527
#endif  /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */
slouken@279
   528
    return is_type;
slouken@279
   529
}
slouken@279
   530
slouken@279
   531
static int Internal_isType_ImageIO (SDL_RWops *rw_ops, CFStringRef uti_string_to_test)
slouken@279
   532
{
slouken@279
   533
    int is_type = 0;
slouken@279
   534
    
slouken@279
   535
    CFDictionaryRef hint_dictionary = CreateHintDictionary(uti_string_to_test);	
slouken@279
   536
    CGImageSourceRef image_source = CreateCGImageSourceFromRWops(rw_ops, hint_dictionary);
slouken@279
   537
    
slouken@279
   538
    if (hint_dictionary != NULL) {
slouken@279
   539
        CFRelease(hint_dictionary);		
slouken@279
   540
    }
slouken@279
   541
    
slouken@279
   542
    if (NULL == image_source) {
slouken@279
   543
        return 0;
slouken@279
   544
    }
slouken@279
   545
    
slouken@279
   546
    // This will get the UTI of the container, not the image itself.
slouken@279
   547
    // Under most cases, this won't be a problem.
slouken@279
   548
    // But if a person passes an icon file which contains a bmp,
slouken@279
   549
    // the format will be of the icon file.
slouken@279
   550
    // But I think the main SDL_image codebase has this same problem so I'm not going to worry about it.	
slouken@279
   551
    CFStringRef uti_type = CGImageSourceGetType(image_source);
slouken@279
   552
    //	CFShow(uti_type);
slouken@279
   553
    
slouken@279
   554
    // Unsure if we really want conformance or equality
slouken@279
   555
    is_type = (int)UTTypeConformsTo(uti_string_to_test, uti_type);
slouken@279
   556
    
slouken@279
   557
    CFRelease(image_source);
slouken@279
   558
    return is_type;
slouken@279
   559
}
slouken@279
   560
slouken@279
   561
static int Internal_isType (SDL_RWops *rw_ops, CFStringRef uti_string_to_test)
slouken@279
   562
{
slouken@279
   563
    if (rw_ops == NULL)
slouken@279
   564
        return 0;
slouken@279
   565
    
slouken@279
   566
#if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)
slouken@279
   567
    if (USE_UIIMAGE_BACKEND())
slouken@279
   568
        return Internal_isType_UIImage(rw_ops, uti_string_to_test);
slouken@279
   569
    else
slouken@279
   570
#endif
slouken@279
   571
        return Internal_isType_ImageIO(rw_ops, uti_string_to_test);
slouken@279
   572
}
slouken@279
   573
slouken@332
   574
#ifdef BMP_USES_IMAGEIO
slouken@332
   575
slouken@195
   576
int IMG_isCUR(SDL_RWops *src)
slouken@195
   577
{
slouken@279
   578
    /* FIXME: Is this a supported type? */
slouken@279
   579
    return Internal_isType(src, CFSTR("com.microsoft.cur"));
slouken@195
   580
}
slouken@195
   581
slouken@195
   582
int IMG_isICO(SDL_RWops *src)
slouken@195
   583
{
slouken@279
   584
    return Internal_isType(src, kUTTypeICO);
slouken@195
   585
}
slouken@195
   586
slouken@187
   587
int IMG_isBMP(SDL_RWops *src)
slouken@187
   588
{
slouken@279
   589
    return Internal_isType(src, kUTTypeBMP);
slouken@187
   590
}
slouken@187
   591
slouken@332
   592
#endif /* BMP_USES_IMAGEIO */
slouken@332
   593
slouken@187
   594
int IMG_isGIF(SDL_RWops *src)
slouken@187
   595
{
slouken@279
   596
    return Internal_isType(src, kUTTypeGIF);
slouken@187
   597
}
slouken@195
   598
slouken@187
   599
// Note: JPEG 2000 is kUTTypeJPEG2000
slouken@187
   600
int IMG_isJPG(SDL_RWops *src)
slouken@187
   601
{
slouken@279
   602
    return Internal_isType(src, kUTTypeJPEG);
slouken@187
   603
}
slouken@187
   604
slouken@187
   605
int IMG_isPNG(SDL_RWops *src)
slouken@187
   606
{
slouken@279
   607
    return Internal_isType(src, kUTTypePNG);
slouken@187
   608
}
slouken@187
   609
slouken@187
   610
// This isn't a public API function. Apple seems to be able to identify tga's.
slouken@187
   611
int IMG_isTGA(SDL_RWops *src)
slouken@187
   612
{
slouken@279
   613
    return Internal_isType(src, CFSTR("com.truevision.tga-image"));
slouken@187
   614
}
slouken@187
   615
slouken@187
   616
int IMG_isTIF(SDL_RWops *src)
slouken@187
   617
{
slouken@279
   618
    return Internal_isType(src, kUTTypeTIFF);
slouken@187
   619
}
slouken@187
   620
slouken@279
   621
#pragma mark -
slouken@279
   622
#pragma mark Load image engine
slouken@279
   623
static SDL_Surface *LoadImageFromRWops_UIImage (SDL_RWops* rw_ops, CFStringRef uti_string_hint)
slouken@195
   624
{
slouken@279
   625
    SDL_Surface *sdl_surface = NULL;
slouken@279
   626
slouken@279
   627
#if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1))
slouken@279
   628
    NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init];
slouken@279
   629
    UIImage *ui_image;
slouken@279
   630
    int bytes_read = 0;
slouken@279
   631
    // I don't know what a good size is. 
slouken@279
   632
    // Max recommended texture size is 1024x1024 on iPhone so maybe base it on that?
slouken@279
   633
    const int block_size = 1024*4;
slouken@279
   634
    char temp_buffer[block_size];
slouken@279
   635
    
slouken@279
   636
    NSMutableData* ns_data = [[NSMutableData alloc] initWithCapacity:1024*1024*4];
slouken@279
   637
    do {
slouken@279
   638
        bytes_read = SDL_RWread(rw_ops, temp_buffer, 1, block_size);
slouken@279
   639
        [ns_data appendBytes:temp_buffer length:bytes_read];
slouken@279
   640
    } while (bytes_read > 0);
slouken@279
   641
    
slouken@279
   642
    ui_image = [[UIImage alloc] initWithData:ns_data];
slouken@279
   643
    if (ui_image != nil)
slouken@279
   644
        sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]);
slouken@279
   645
    [ui_image release];
slouken@279
   646
    [ns_data release];          
slouken@279
   647
    [autorelease_pool drain];
slouken@279
   648
slouken@279
   649
#endif  /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */
slouken@279
   650
    return sdl_surface;
slouken@187
   651
}
slouken@187
   652
slouken@279
   653
static SDL_Surface *LoadImageFromRWops_ImageIO (SDL_RWops *rw_ops, CFStringRef uti_string_hint)
slouken@279
   654
{
slouken@279
   655
    CFDictionaryRef hint_dictionary = CreateHintDictionary(uti_string_hint);
slouken@279
   656
    CGImageSourceRef image_source = CreateCGImageSourceFromRWops(rw_ops, hint_dictionary);
slouken@279
   657
slouken@279
   658
    if (hint_dictionary != NULL)
slouken@279
   659
        CFRelease(hint_dictionary);		
slouken@279
   660
slouken@279
   661
    if (NULL == image_source)
slouken@279
   662
        return NULL;
slouken@279
   663
    
slouken@279
   664
    CGImageRef image_ref = CreateCGImageFromCGImageSource(image_source);
slouken@279
   665
    CFRelease(image_source);
slouken@279
   666
slouken@279
   667
    if (NULL == image_ref)
slouken@279
   668
        return NULL;
slouken@279
   669
    SDL_Surface *sdl_surface = Create_SDL_Surface_From_CGImage(image_ref);
slouken@279
   670
    CFRelease(image_ref);
slouken@279
   671
slouken@279
   672
    return sdl_surface;
slouken@279
   673
}
slouken@279
   674
slouken@279
   675
static SDL_Surface *LoadImageFromRWops (SDL_RWops *rw_ops, CFStringRef uti_string_hint)
slouken@279
   676
{
slouken@279
   677
#if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)
slouken@279
   678
    if (USE_UIIMAGE_BACKEND()) 
slouken@279
   679
        return LoadImageFromRWops_UIImage(rw_ops, uti_string_hint);
slouken@279
   680
    else
slouken@279
   681
#endif
slouken@279
   682
        return LoadImageFromRWops_ImageIO(rw_ops, uti_string_hint);
slouken@279
   683
}
slouken@279
   684
slouken@279
   685
static SDL_Surface* LoadImageFromFile_UIImage (const char *file)
slouken@279
   686
{
slouken@279
   687
    SDL_Surface *sdl_surface = NULL;
slouken@279
   688
slouken@279
   689
#if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1))
slouken@279
   690
    NSAutoreleasePool* autorelease_pool = [[NSAutoreleasePool alloc] init];
slouken@279
   691
    NSString *ns_string = [[NSString alloc] initWithUTF8String:file];
slouken@279
   692
    UIImage *ui_image = [[UIImage alloc] initWithContentsOfFile:ns_string];
slouken@279
   693
    if (ui_image != nil)
slouken@279
   694
        sdl_surface = Create_SDL_Surface_From_CGImage([ui_image CGImage]);
slouken@279
   695
    [ui_image release];
slouken@279
   696
    [ns_string release];
slouken@279
   697
    [autorelease_pool drain];
slouken@279
   698
slouken@279
   699
#endif  /* #if defined(ALLOW_UIIMAGE_FALLBACK) && ((TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)) */
slouken@279
   700
    return sdl_surface;	
slouken@279
   701
}
slouken@279
   702
slouken@279
   703
static SDL_Surface* LoadImageFromFile_ImageIO (const char *file)
slouken@279
   704
{
slouken@279
   705
    CGImageSourceRef image_source = NULL;
slouken@279
   706
slouken@279
   707
    image_source = CreateCGImageSourceFromFile(file);
slouken@279
   708
slouken@279
   709
    if(NULL == image_source)
slouken@279
   710
        return NULL;
slouken@279
   711
    
slouken@279
   712
    CGImageRef image_ref = CreateCGImageFromCGImageSource(image_source);
slouken@279
   713
    CFRelease(image_source);
slouken@279
   714
slouken@279
   715
    if (NULL == image_ref)
slouken@279
   716
        return NULL;
slouken@279
   717
    SDL_Surface *sdl_surface = Create_SDL_Surface_From_CGImage(image_ref);
slouken@279
   718
    CFRelease(image_ref);
slouken@279
   719
    return sdl_surface;	
slouken@279
   720
}
slouken@279
   721
slouken@279
   722
static SDL_Surface* LoadImageFromFile (const char *file)
slouken@279
   723
{
slouken@279
   724
#if (TARGET_OS_IPHONE == 1) || (TARGET_IPHONE_SIMULATOR == 1)
slouken@279
   725
    if (USE_UIIMAGE_BACKEND())
slouken@279
   726
        return LoadImageFromFile_UIImage(file);
slouken@279
   727
    else
slouken@279
   728
#endif
slouken@279
   729
        return LoadImageFromFile_ImageIO(file);
slouken@279
   730
}
slouken@279
   731
slouken@332
   732
#ifdef BMP_USES_IMAGEIO
slouken@332
   733
slouken@279
   734
SDL_Surface* IMG_LoadCUR_RW (SDL_RWops *src)
slouken@279
   735
{
slouken@279
   736
    /* FIXME: Is this a supported type? */
slouken@279
   737
    return LoadImageFromRWops(src, CFSTR("com.microsoft.cur"));
slouken@279
   738
}
slouken@279
   739
slouken@279
   740
SDL_Surface* IMG_LoadICO_RW (SDL_RWops *src)
slouken@279
   741
{
slouken@279
   742
    return LoadImageFromRWops(src, kUTTypeICO);
slouken@279
   743
}
slouken@279
   744
slouken@279
   745
SDL_Surface* IMG_LoadBMP_RW (SDL_RWops *src)
slouken@279
   746
{
slouken@279
   747
    return LoadImageFromRWops(src, kUTTypeBMP);
slouken@279
   748
}
slouken@279
   749
slouken@332
   750
#endif /* BMP_USES_IMAGEIO */
slouken@332
   751
slouken@279
   752
SDL_Surface* IMG_LoadGIF_RW (SDL_RWops *src)
slouken@279
   753
{
slouken@279
   754
    return LoadImageFromRWops (src, kUTTypeGIF);
slouken@279
   755
}
slouken@279
   756
slouken@279
   757
SDL_Surface* IMG_LoadJPG_RW (SDL_RWops *src)
slouken@279
   758
{
slouken@279
   759
    return LoadImageFromRWops (src, kUTTypeJPEG);
slouken@279
   760
}
slouken@279
   761
slouken@279
   762
SDL_Surface* IMG_LoadPNG_RW (SDL_RWops *src)
slouken@279
   763
{
slouken@279
   764
    return LoadImageFromRWops (src, kUTTypePNG);
slouken@279
   765
}
slouken@279
   766
slouken@279
   767
SDL_Surface* IMG_LoadTGA_RW (SDL_RWops *src)
slouken@279
   768
{
slouken@279
   769
    return LoadImageFromRWops(src, CFSTR("com.truevision.tga-image"));
slouken@279
   770
}
slouken@279
   771
slouken@279
   772
SDL_Surface* IMG_LoadTIF_RW (SDL_RWops *src)
slouken@279
   773
{
slouken@279
   774
    return LoadImageFromRWops(src, kUTTypeTIFF);
slouken@279
   775
}
slouken@279
   776
slouken@279
   777
// Since UIImage doesn't really support streams well, we should optimize for the file case.
slouken@187
   778
// Apple provides both stream and file loading functions in ImageIO.
slouken@187
   779
// Potentially, Apple can optimize for either case.
slouken@279
   780
SDL_Surface* IMG_Load (const char *file)
slouken@187
   781
{
slouken@279
   782
    SDL_Surface* sdl_surface = NULL;
slouken@279
   783
    
slouken@279
   784
    sdl_surface = LoadImageFromFile(file);
slouken@279
   785
    if(NULL == sdl_surface)
slouken@279
   786
    {
slouken@279
   787
        // Either the file doesn't exist or ImageIO doesn't understand the format.
slouken@279
   788
        // For the latter case, fallback to the native SDL_image handlers.
slouken@279
   789
        SDL_RWops *src = SDL_RWFromFile(file, "rb");
slouken@279
   790
        char *ext = strrchr(file, '.');
slouken@279
   791
        if (ext) {
slouken@279
   792
            ext++;
slouken@279
   793
        }
slouken@279
   794
        if (!src) {
slouken@279
   795
            /* The error message has been set in SDL_RWFromFile */
slouken@279
   796
            return NULL;
slouken@279
   797
        }
slouken@279
   798
        sdl_surface = IMG_LoadTyped_RW(src, 1, ext);
slouken@279
   799
    }
slouken@279
   800
    return sdl_surface;
slouken@187
   801
}
slouken@187
   802
slouken@240
   803
#endif /* defined(__APPLE__) && !defined(SDL_IMAGE_USE_COMMON_BACKEND) */