TweetFollow Us on Twitter

Res Compression
Volume Number:9
Issue Number:1
Column Tag:Resources

Related Info: Resource Manager

Resource Compression

What it is, how it works, and how to use it in your own software

By Justin Gray, Alysis Software Corporation

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

With the release of System 7, Apple quietly introduced a powerful means of applying transparent compression to applications and other resource files that has yet to be matched by third-party schemes. While System 7 features like AppleEvents and Balloon help were highly-touted and well-documented, Apple’s resource compression scheme remains a tantalizing mystery to most Macintosh developers. In this article, we’ll explore exactly what resource compression is, how it works, and how to apply it to your own software.

What Resource Compression is

To deliver on the promise of System 7’s remarkable new features, Apple programmers had to write a significant volume of new code for both the Finder and System files. During the course of development, it became clear that the system and Finder would not be able to fit on a single high-density diskette without the application of some sort of compression. The compression applications available at the time could not be applied since they would only create archives, not compressed files that could be used in compressed form. What was needed was a compression/decompression scheme that would allow compressed files to operate while still compressed on disk and without degrading system performance. The solution was the resource compression system employed in the System File, the Finder, ResEdit, and TeachText.

Like any other coding - decoding system, resource compression consists of two basic components: a tool for compressing data, and decompression code which decodes the compressed data. While most third-party compression software comes in application form, resource compression exists in the form of an enhancement to the Resource Manager supported by decompression resources of type ‘dcmp’. After compiling the final version of his/her software, a developer uses a resource compressing application to shrink the individual resources in the application and paste in his/her ‘dcmp’ resource. When the end user launches the application, the Resource Manager handles the parsing of compressed resources and calls the appropriate decoders to transparently expand the compressed resources that it encounters.

The significant advantages to this approach are speed and compatibility. Since resources are decompressed into memory rather than to disk, their compressed contents can be accessed in a fraction of the time required by a system that decompresses to disk. Because the resources are compressed and decompressed individually, they can be accessed much more rapidly than if the entire file were expanded into memory. An application which takes up half the space on disk will require only half as much disk access to load into memory. If the decoding software can expand the compressed data more rapidly than the SCSI bus can transfer the same number of bytes, the application will actually launch faster in compressed form.

Since the decompression is done automatically by the Resource Manager and the appropriate ‘dcmp’ resource, compressed data can be accessed transparently by software that is unaware of compressed resources: the same trap calls that access ordinary resources also access compressed resources with no difference in passed parameters. Applications written before resource compression was made available will launch and run after being made smaller through resource compression. Adobe Photoshop and Aldus PageMaker 4 will each fit on and execute from 800K diskettes after being compressed by a commercially-available resource compression application.

Unfortunately resource compression applies only to resource forks. Apple does not currently provide an equally transparent scheme for manipulating compressed data forks, although several third-party publishers supply software which does. Resource compression is also currently a “one-way” compression scheme - the Resource Manager decompresses resources but does not add them to resource files in compressed form. And the compression tools which Apple uses internally are not currently available to developers. (This article will describe how to create one.) Despite these limitations, resource compression promises to deliver the most transparent and best performing means of making applications and system enhancements smaller for the forseeable future of 680x0-based Macintoshes.

How Resource Compression Works

Poking about in the System or Finder with ResEdit reveals very few visible cues that the files are compressed. Resources appear as they normally would and can be opened and edited or cut and pasted with no delays or unexplained changes in size. Because the resource manager handles compressed resources, they appear to any programs which use the resource manager as ordinary resources. The only discrepancy introduced by resource compression is the difference between the sum of the values returned by SizeResource and the total size of the resource fork. (These two numbers do not necessarily have a close correspondence even in files without compressed resources.)

The transparent decompression of these resources happens through a variation of the Resource Manager’s regular loading process. Normally, when a GetResource, Get1Resource or similar trap is executed, the Resource Manager (herein called RM) allocates a handle to a block of memory sufficiently large to hold the entire resource. It then calls the File Manager and reads the appropriate range of data from the resource fork of the file into the new handle. When the RM encounters a resource whose ‘compressed’ attribute is set, it calls an additional set of low-level routines.

Once the resource is loaded, the RM double-checks the status of the resource and exits if its header does not contain the appropriate tag bytes. If the resource passes this check, then the RM determines the kind of memory allocation required by the decompressor by checking the resource header flag bits. The RM then extracts a resource ID from the resource header, which it uses to load a system resource which employs the appropriate algorithm or algorithms to decompress the data contained in the resource. Herein is the exciting modularity of the resource compression scheme: each decompression algorithm used by the RM is held in a self-contained code resource of type ‘dcmp’. Adding new compression algorithms to the Macintosh is simply a matter of plugging new ‘dcmp’ resources into the system file or even into the file which contains compressed resources. The Macintosh System does the rest!

Once the RM is armed with a decoding routine, it allocates a buffer for use by the decoder and passes pointers to the buffer and the source and destination buffers of the decompression operation. Interestingly, the destination pointer begins before the source pointer and the difference between the two is less than the size of the decompressed resource: the decompressed data overruns the already-used compressed data as it is decoded.

The brilliance of this scheme is that it requires only a single buffer for both the compressed and decompressed data. In an ideal world the buffer would be precisely the size of the decompressed data - like Ouroboros, the mythical snake who girded the world in perpetual pursuit of its tail, the decompressed data would replace the already-used compressed data. It would grow ever closer to the unused compressed data but never overwrite it. In practice, however, compression algorithms do not provide uniform compression and may for brief instances produce output code that consumes more space than the input code that it replaces. The RM solution to this problem is to provide an expansion buffer between the decompressed and compressed data. The size of the buffer, recorded in the resource header, is equal to the maximum amount that the encoded data might grow toward the end of the decompression process. Once the data is decompressed, the handle is shrunk by the expansion buffer size, the memory buffer used by the decoder is released, and the handle is returned to the caller. Two types of ‘dcmps’ provide support for small and large expansion buffers.

Although this description is somewhat simplified, it serves to illustrate the tremendous power of Apple’s approach to handling compression. By compressing and decompressing resources at the RM level, Apple has succeeded in delivering a system that opens compressed resources more rapidly than uncompressed resources, provides rapid random access to compressed data, and provides complete transparency and backward compatibility to code which uses the RM to access data. Tapping into the power of the scheme involves nothing more difficult than running a resource compressor program and copying a dcmp resource with ResEdit.

How to Use Resource Compression in Your Own Software

While using existing resource compression tools to apply compression to applications, extensions and other resource files is trivial, building a resource compressor, designing compression algorithms, creating optimized assembly-language implementations of the codecs, and building the appropriate ‘dcmps’ code resources to allow the System to decode the compressed resources requires somewhat more effort. For those of you who are interested in tinkering with your own resource-based compression systems, here is an outline of the basic steps that you’ll have to take and some source code to get you started.

Selecting an algorithm

The first step in tapping into resource compression is to select and create a codec. The primary criteria for selecting your algorithm should be speed, efficient use of memory, and compression efficiency under limited-context conditions. Since a single ‘dcmps’ added to the system file will allow for decompression of resources in all files, size of the decompression object code is not a major consideration.

Most compression algorithms currently in commercial use employ a combination of two techniques: string-matching and frequency-based encoding of characters to variable-length bit fields. The string matching algorithm is applied first to reduce instances like the string “Resource Manager” in this article to single bytes. The second algorithm compares the frequency of the single bytes or short strings and then substitutes shorter bit-field elements for the more frequently occurring characters. Both types of algorithms are well-documented in computer journals and textbooks. Popular string-based compression algorithms include Limpel-Ziv and its derivatives. Popular frequency-based compression algorithms include Huffman coding, arithmetic coding and adaptive variations of both.

While non-adaptive frequency-based coding is fairly fast in both compressing and decompressing, string-based compression algorithms tend to operate more slowly, especially in compression. To reap the rewards of high-speed decompression, you should choose an algorithm that is inherently fast or invest some time in optimizing the performance of an already-implemented algorithm.

Since resource decompression is executed by the RM, your decoder should be frugal in its use of memory. The RM allocates buffers for decompressors in the system heap. While management of the system heap has improved considerably, the Memory Manager may not be able to free sufficient space for the more memory-hungry adaptive codecs.

Compression efficiency in a limited context environment is also of primary importance in selecting a compression algorithm. File-based compression schemes have an advantage over resource compression in that they operate on an entire file at a time, enabling the compression algorithm to acquire an extensive context or set of libraries with which to compress data efficiently. Because resources can be accessed independently, resource-based compression operates only within the context of a single resource. Many resources are quite small and will not compress well with Limpel-Ziv-derivative algorithms.

Creating a resource-compressing application

Once you’ve selected and implemented a compression algorithm that is fast, lean, and operates with limited context, you will want to incorporate the encoding portion of your codec in a resource-compressing application. Your application will need to open resource files, select resources for compression (some resources should not be compressed), compress the data contained in the selected resources, calculate and add header information to the resources, add them back to the resource fork, set the appropriate attributes for the resources and then set the appropriate attribute bits for the resource file. Except for the exact header format, described in the following structure, most of the documentation for this work can be found in Inside Macintosh.

Compressed Resource Header Format

[1]
typedef struct {
 long compressedResourceTag;
 long typeFlags;
 long uncompressedSize;
 char workingBufferFractionalSize;
 char expansionBufferSize;
 short  dcmpID;
} resourceHeader;

Here the compressedResourceTag should be 0xA89F6572. The typeFlags should be set to 0x120801. The workingBufferFractionalSize should be a fixed point fraction of the size of the uncompressed resource. The expansion buffer size should be a number from 0 to 255 which represents the greatest number of bytes that the compressed data might grow during the end of the compression process.

Once you’ve successfully compressed resources with your new application, you’ll be able to examine them in ResEdit. If your application has compressed and manipulated the resources properly, you will be able to see them in the resource map listing and get information about them. Trying to cut, copy or edit the resources will give you a “bent” resource error, -186. This simply means that the appropriate 'dcmp' resource has not been made available to the system.

Creating a decompression resource

There are several types of ‘dcmp’ resource used by the system software. The source code provided here will enable you to employ your decoder within the ‘small-expansion-buffer’ 'dcmp' format like the one used by System 7 for decompressing code resources. In combination with a good algorithm, you should be able to get significantly better compression ratios on code resources and others.

Creating the decompression resource consists of creating a code resource of type ‘dcmp’ which contains the header glue code in the following source code listing as well as the decoding portion of your codec. Since your ‘dcmp’ will be executing within a RM call, you should try to incorporate all of the code required into a single resource, rather than having a separate decoding resource loaded by your 'dcmp'.

[2]
‘dcmp’ Resource glue code listing

typedef struct {
 char unused[7];
 long dataSize;
 long workingBuffer;
 long destinationBuffer;
 long sourceBuffer;


} dcmpParameters;

main (){
 asm {
 debug
 link a6,#0 ; Grab a stack frame
 movem.ld0-d7/a0-a6,-(a7) ; Save all variables
 ; Get the input buffer
 move.l dcmpParameters.sourceBuffer(a6),a0   
 ; Get the output buffer
 move.l dcmpParameters.destinationBuffer(a6),a1     
 ; Get the working buffer
 move.l dcmpParameters.workingBuffer(a6),a2  
 move.l dcmpParameters.dataSize(a6),d0 ; How much data?

; Insert your decompression code here.

 movem.l(a7)+,d0-d7/a0-a6 ; Restore the registers
 unlk a6
 move.l (a7)+,8(a7); Move return address
 addq.l #8,a7    ; Discard the stack frame
 } /* end asm */
/* Return to Resource Mgr */
}

It is important to use the Custom Header selection from Think C for creating a 'dcmp' resource with this glue code. The register assignments used in this example were arbitrarily chosen.

Once your 'dcmp' is compiled, you can either add it to your compressed resource file or the active system file. Once the 'dcmp' is added to an open resource map, it will be executed by the RM whenever one of the corresponding compressed resources is accessed. Now double-clicking on one of the resources compressed by your application will yield the following message, “That resource is compressed. If you make changes, it will be saved uncompressed. Do you want to edit it anyway?” Pressing the Yes button will open the resource as if it were not compressed. All other accesses to the resource will open it transparently and return information about the resource as if it were not compressed. Congratulations -- You have successfully implemented a resource compression scheme.

For more information

Alysis Software Corporation

1231 31st Avenue

San Francisco, CA 94122

Voice: 415/566-2263 • Fax: 415/566-9692

AppleLink: ALYSIS

America Online: ALYSIS

CompuServe: 76500,3011

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Xcode 15.0.1 - Integrated development en...
Xcode includes everything developers need to create great applications for Mac, iPhone, iPad, and Apple Watch. Xcode provides developers a unified workflow for user interface design, coding, testing... Read more
Google Chrome 120.0.6099.62 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Dropbox 188.4.6302 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
djay Pro 5.0 - Transform your Mac into a...
djay Pro provides a complete toolkit for performing DJs. Its unique modern interface is built around a sophisticated integration with iTunes and Spotify, giving you instant access to millions of... Read more
Things 3.19.4 - Elegant personal task ma...
Things is a task management solution that helps to organize your tasks in an elegant and intuitive way. Things combines powerful features with simplicity through the use of tags and its intelligent... Read more
Sublime Text 4169 - Sophisticated text e...
Sublime Text is a sophisticated text editor for code, markup, and prose. You'll love the slick user interface, extraordinary features, and amazing performance. Features Goto Anything. Use Goto... Read more
Typinator 9.1 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
ESET Cyber Security 6.11.414.0 - Basic i...
ESET Cyber Security provides powerful protection against phishing, viruses, worms, and spyware. Offering similar functionality to ESET NOD32 Antivirus for Windows, ESET Cyber Security for Mac allows... Read more
Opera 105.0.4970.29 - High-performance W...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
Quicken 7.4.1 - Complete personal financ...
Quicken makes managing your money easier than ever. Whether paying bills, upgrading from Windows, enjoying more reliable downloads, or getting expert product help, Quicken's new and improved features... Read more

Latest Forum Discussions

See All

‘Refind Self: The Personality Test Game’...
The last two months have been so busy that I’ve not been able to make time to play many games until recently. There are still new games coming out even as we head closer to the holidays, but I finally managed to play Playism and Lizardry’s recent... | Read more »
Experience the glory of the Northern Lig...
Dinosaur Polo Club, one of the best developer names out there, have recently announced the final update of 2023 for Mini Motorways. Instead of embracing Christmas, this event is instead inspired by one of the most beautiful natural phenomena, the... | Read more »
‘Disney Dreamlight Valley Arcade Edition...
After a bit of a delay, Disney Dreamlight Valley Arcade Edition () is now available on Apple Arcade worldwide. When Disney Dreamlight Valley Arcade Edition hit early access on PC and consoles including Nintendo Switch, I always assumed it would... | Read more »
‘Devil May Cry: Peak of Combat’ Releases...
It feels like we’ve been covering Devil May Cry: Peak of Combat (), the mobile entry in the superb Devil May Cry series, for as long as we were waiting for Devil May Cry 5. After trailers revealing gameplay, characters, controller support, betas,... | Read more »
‘Marvel Snap’ Dons Its Finest in the New...
It’s been quite a year for the card battler Marvel Snap (Free), which is still one of my favorite mobile games. There have been a bunch of interestingly-themed seasons, sometimes connected to the MCU and sometimes just doing their own thing. Plenty... | Read more »
SwitchArcade Round-Up: ‘A Highland Song’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 5th, 2023. It’s a bit of a short one today since I was busy with a variety of other things, but there are several new releases for us to summarize. There are some really... | Read more »
‘Metal Slug ACA NEOGEO’ Review – Another...
Well, here we go again. The latest addition to SNK and Hamster’s mobile Arcade Archives line is none other than Metal Slug ACA NEOGEO ($3.99), a second take on a game we got a mobile version of a decade back from Dotemu. That was a fine version for... | Read more »
‘Sonic Dream Team’ Apple Arcade Review –...
What an unusual day we have arrived upon today. Now, Sonic the Hedgehog games aren’t a new thing for iOS gaming. The original Sonic the Hedgehog appeared on the classic iPod, so the Blue Blur got in the doors as fast as you would expect him to. The... | Read more »
PvP Basketball Game ‘NBA Infinite’ Annou...
Level Infinite and Lightspeed Studios just announced a new real-time PvP basketball game for mobile in the form of NBA Infinite (). NBA Infinite includes solo modes as well, collecting and upgrading current NBA players, managing teams, and more. It... | Read more »
New ‘Dysmantle’ iOS Update Adds Co-Op Mo...
We recently had a major update hit mobile for the open world survival and crafting adventure game Dysmantle ($4.99) from 10tons Ltd. Dysmantle was one of our favorite games of 2022, and with all of its paid DLC and updates, it is even better. | Read more »

Price Scanner via MacPrices.net

Apple’s 14-inch M3 MacBook Pros are on Holida...
Best Buy is offering a $150-$200 discount on Space Gray or Silver 14″ M3 MacBook Pros on their online store with prices available starting at $1449 ($1399 for premium My Best Buy members). Prices... Read more
Holiday Sale: 128GB iPhone 15 Pro, 15 Plus, o...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 Pro, 128GB iPhone 15 Plus, or 128GB & 256GB iPhone 15 for $60 per month including... Read more
Clearance 12.9-inch iPad Pros with M1 CPUs av...
Apple has Certified Refurbished, previous-generation, 12″ M1 iPad Pros available in their online store in a variety of configurations. Models start at $889 and range up to $350 off Apple’s original... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Holiday sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
B&H is offering a $150 discount on 13-inc...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock today and on Holiday sale for $150 off Apple’s MSRP, only $949. Free 1-2 day delivery is available to most US addresses.... Read more
Apple is clearing out last year’s M1-powered...
Apple has Certified Refurbished 11″ M1 iPad Pros available starting at $639 and ranging up to $310 off Apple’s original MSRP. Each iPad Pro comes with Apple’s standard one-year warranty, features a... Read more
Save $50 on these HomePods available today at...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod this... Read more
New 16-inch M3 Pro MacBook Pros are on sale f...
Holiday MacBook deals are live at B&H Photo. Apple 16″ MacBook Pros with M3 Pro CPUs are in stock and on sale for $200-$250 off MSRP. Their prices are among the lowest currently available for... Read more
Christmas Deal Alert! Apple AirPods Pro with...
Walmart has Apple’s 2023 AirPods Pro with USB-C in stock and on sale for $189.99 on their online store as part of their Holiday sale. Their price is $60 off MSRP, and it’s currently the lowest price... Read more
Apple has Certified Refurbished iPhone 12 Pro...
Apple has unlocked Certified Refurbished iPhone 12 Pro models in stock starting at $589 and ranging up to $350 off original MSRP. Apple includes a standard one-year warranty and new outer shell with... Read more

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Mobile Platform Engineer ( *Apple* /AirWatch)...
…systems, installing and maintaining certificates, navigating multiple network segments and Apple /IOS devices, Mobile Device Management systems such as AirWatch, and Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.