IMG_ImageIO.m
author Sam Lantinga <slouken@libsdl.org>
Sat, 31 Dec 2011 12:38:49 -0500
changeset 283 ec183abd5996
parent 279 e2fa9ff13b5d
child 292 5953114c0d27
permissions -rw-r--r--
Fixed bug 1236 - CreateCGImageSourceFromRWops leaks

Mike 2011-06-24 00:41:23 PDT

CGDataProviderRef must be cleaned after usage.

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