⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 inflatelib.c

📁 VXWORKS源代码
💻 C
📖 第 1 页 / 共 5 页
字号:
/* inflateLib.c - inflate code using public domain zlib functions *//*modification history--------------------01g,26oct01,cyr  doc: correct SPR 22609 url link01f,19oct01,dat  Documentation formatting01e,23mar99,fle  doc : fixed INTERNAL handling01d,27aug98,fle  doc : documented inflate_codes_new routine header01c,01may98,cdp  fix bzero; fix storage allocator overwriting memory.01b,07nov96,dgp  doc: final formatting01a,18aug96,ms   written based on public domain zlib code.*//*                                                                            DESCRIPTIONThis library is used to inflate a compressed data stream, primarilyfor boot ROM decompression.Compressed boot ROMs contain a compressed executable in the data segmentbetween the symbols `binArrayStart' and `binArrayEnd' (the compresseddata is generated by deflate() and `binToAsm').The boot ROM startup code (in target/src/config/all/bootInit.c) callsinflate() to decompress the executable and then jump to it.This library is based on the public domain zlib code, which has beenmodified by Wind River Systems.  For more information, seethe zlib home page at `http://www.gzip.org/zlib/'.INTERNALQuestions about zlib should be sent to <zlib@quest.jpl.nasa.gov> or,if this fails, to the addresses given below in the Copyright section..SH The following copyright notice is part of the zlib source distribution.Copyright notice: (C) 1995-1996 Jean-loup Gailly and Mark Adler  This software is provided 'as-is', without any express or implied  warranty.  In no event will the authors be held liable for any damages  arising from the use of this software.  Permission is granted to anyone to use this software for any purpose,  including commercial applications, and to alter it and redistribute it  freely, subject to the following restrictions:  1. The origin of this software must not be misrepresented; you must not     claim that you wrote the original software. If you use this software     in a product, an acknowledgment in the product documentation would be     appreciated but is not required.  2. Altered source versions must be plainly marked as such, and must not be     misrepresented as being the original software.  3. This notice may not be removed or altered from any source distribution.  Jean-loup Gailly        Mark Adler  gzip@prep.ai.mit.edu    madler@alumni.caltech.edu.SH Overview of the compression/decompression1. Compression algorithm (deflate)The deflation algorithm used by zlib (also zip and gzip) is a variation ofLZ77 (Lempel-Ziv 1977, see reference below). It finds duplicated strings inthe input data.  The second occurrence of a string is replaced by apointer to the previous string, in the form of a pair (distance,length).  Distances are limited to 32K bytes, and lengths are limitedto 258 bytes. When a string does not occur anywhere in the previous32K bytes, it is emitted as a sequence of literal bytes.  (In thisdescription, `string' must be taken as an arbitrary sequence of bytes,and is not restricted to printable characters.)Literals or match lengths are compressed with one Huffman tree, andmatch distances are compressed with another tree. The trees are storedin a compact form at the start of each block. The blocks can have anysize (except that the compressed data for one block must fit inavailable memory). A block is terminated when deflate() determines thatit would be useful to start another block with fresh trees. (This issomewhat similar to the behavior of LZW-based _compress_.)Duplicated strings are found using a hash table. All input strings oflength 3 are inserted in the hash table. A hash index is computed forthe next 3 bytes. If the hash chain for this index is not empty, allstrings in the chain are compared with the current input string, andthe longest match is selected.The hash chains are searched starting with the most recent strings, tofavor small distances and thus take advantage of the Huffman encoding.The hash chains are singly linked. There are no deletions from thehash chains, the algorithm simply discards matches that are too old.To avoid a worst-case situation, very long hash chains are arbitrarilytruncated at a certain length, determined by a runtime option (levelparameter of deflateInit). So deflate() does not always find the longestpossible match but generally finds a match which is long enough.deflate() also defers the selection of matches with a lazy evaluationmechanism. After a match of length N has been found, deflate() searches for alonger match at the next input byte. If a longer match is found, theprevious match is truncated to a length of one (thus producing a singleliteral byte) and the longer match is emitted afterwards.  Otherwise,the original match is kept, and the next match search is attempted onlyN steps later.The lazy match evaluation is also subject to a runtime parameter. Ifthe current match is long enough, deflate() reduces the search for a longermatch, thus speeding up the whole process. If compression ratio is moreimportant than speed, deflate() attempts a complete second search even ifthe first match is already long enough.The lazy match evaluation is not performed for the fastest compressionmodes (level parameter 1 to 3). For these fast modes, new stringsare inserted in the hash table only when no match was found, orwhen the match is not too long. This degrades the compression ratiobut saves time since there are both fewer insertions and fewer searches.2. Decompression algorithm (zinflate)The real question is, given a Huffman tree, how to decode fast.  The mostimportant realization is that shorter codes are much more common thanlonger codes, so pay attention to decoding the short codes fast, and letthe long codes take longer to decode.zinflate() sets up a first level table that covers some number of bits ofinput less than the length of longest code.  It gets that many bits from thestream, and looks it up in the table.  The table will tell if the nextcode is that many bits or less and how many, and if it is, it will tellthe value, else it will point to the next level table for which zinflate()grabs more bits and tries to decode a longer code.How many bits to make the first lookup is a tradeoff between the time ittakes to decode and the time it takes to build the table.  If building thetable took no time (and if you had infinite memory), then there would onlybe a first level table to cover all the way to the longest code.  However,building the table ends up taking a lot longer for more bits since shortcodes are replicated many times in such a table.  What zinflate() does issimply to make the number of bits in the first table a variable, and set itfor the maximum speed.zinflate() sends new trees relatively often, so it is possibly set for asmaller first level table than an application that has only one tree forall the data.  For zinflate, which has 286 possible codes for theliteral/length tree, the size of the first table is nine bits.  Also thedistance trees have 30 possible values, and the size of the first table issix bits.  Note that for each of those cases, the table ended up one bitlonger than the `average' code length, i.e. the code length of anapproximately flat code which would be a little more than eight bits for286 symbols and a little less than five bits for 30 symbols.  It would beinteresting to see if optimizing the first level table for otherapplications gave values within a bit or two of the flat code size.Jean-loup Gailly        Mark Adlergzip@prep.ai.mit.edu    madler@alumni.caltech.eduReferences:[LZ77] Ziv J., Lempel A., `A Universal Algorithm for Sequential DataCompression,' IEEE Transactions on Information Theory, Vol. 23, No. 3,pp. 337-343.`DEFLATE Compressed Data Format Specification' available inftp://ds.internic.net/rfc/rfc1951.txt.SH More internal detailsHuffman code decoding is performed using a multi-level table lookup.The fastest way to decode is to simply build a lookup table whosesize is determined by the longest code.  However, the time it takesto build this table can also be a factor if the data being decodedis not very long.  The most common codes are necessarily theshortest codes, so those codes dominate the decoding time, and hencethe speed.  The idea is you can have a shorter table that decodes theshorter, more probable codes, and then point to subsidiary tables forthe longer codes.  The time it costs to decode the longer codes isthen traded against the time it takes to make longer tables.This results of this trade are in the variables lbits and dbitsbelow.  lbits is the number of bits the first level table for literal/length codes can decode in one step, and dbits is the same thing forthe distance codes.  Subsequent tables are also less than or equal tothose sizes.  These values may be adjusted either when all of thecodes are shorter than that, in which case the longest code length inbits is used, or when the shortest code is *longer* than the requestedtable size, in which case the length of the shortest code in bits isused.There are two different values for the two tables, since they code adifferent number of possibilities each.  The literal/length tablecodes 286 possible values, or in a flat code, a little over eightbits.  The distance table codes 30 possible values, or a little lessthan five bits, flat.  The optimum values for speed end up beingabout one bit more than those, so lbits is 8+1 and dbits is 5+1.The optimum values may differ though from machine to machine, andpossibly even between compilers.  Your mileage may vary.Notes beyond the 1.93a appnote.txt:1. Distance pointers never point before the beginning of the output   stream.2. Distance pointers can point back across blocks, up to 32k away.3. There is an implied maximum of 7 bits for the bit length table and   15 bits for the actual data.4. If only one code exists, then it is encoded using one bit.  (Zero   would be more efficient, but perhaps a little confusing.)  If two   codes exist, they are coded using one bit each (0 and 1).5. There is no way of sending zero distance codes--a dummy must be   sent if there are none.  (History: a pre 2.0 version of PKZIP would   store blocks with no distance codes, but this was discovered to be   too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow   zero distance codes, which is sent as one code of zero bits in   length.6. There are up to 286 literal/length codes.  Code 256 represents the   end-of-block.  Note however that the static length tree defines   288 codes just to fill out the Huffman codes.  Codes 286 and 287   cannot be used though, since there is no length base or extra bits   defined for them.  Similarily, there are up to 30 distance codes.   However, static trees define 32 codes (all 5 bits) to fill out the   Huffman codes, but the last two had better not show up in the data.7. Unzip can check dynamic Huffman blocks for complete code sets.   The exception is that a single code would not be complete (see #4).8. The five bits following the block type is really the number of   literal codes sent minus 257.9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits   (1+6+6).  Therefore, to output three times the length, you output   three codes (1+1+1), whereas to output four times the same length,   you only need two codes (1+3).  Hmm.0. In the tree reconstruction algorithm, Code = Code + Increment   only if BitLength(i) is not zero.  (Pretty obvious.)1. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)2. Note: length code 284 can represent 227-258, but length code 285   really is 258.  The last length deserves its own, short code   since it gets used a lot in very redundant files.  The length   258 is special since 258 - 3 (the min match length) is 255.3. The literal/length and distance code bit lengths are read as a   single stream of lengths.  It is possible (and advantageous) for   a repeat code (16, 17, or 18) to go across the boundary between   the two sets of lengths.*//* includes */#include "types/vxCpu.h"/* definitions *//* Maximum value for windowBits in deflateInit2 and inflateInit */#define DEF_WBITS   15 /* 32K LZ77 window */#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */                        /* Type declarations */#ifndef OF /* function prototypes */#  ifdef STDC#    define OF(args)  args#  else#    define OF(args)  ()#  endif#endif#define Z_OK            0#define Z_STREAM_END    1#define Z_NEED_DICT     2#define Z_ERRNO        (-1)#define Z_STREAM_ERROR (-2)#define Z_DATA_ERROR   (-3)#define Z_MEM_ERROR    (-4)#define Z_BUF_ERROR    (-5)#define Z_VERSION_ERROR (-6)/* Return codes for the compression/decompression functions. Negative * values are errors, positive values are used for special but normal events. */#define Z_DEFLATED   8/* The deflate compression method (the only one supported in this version) */#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */#define BASE 65521L /* largest prime smaller than 65536 */#define NMAX 5552/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */#define ZALLOC(strm, items, size) \           (*((strm)->zalloc))((strm)->opaque, (items), (size))#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidp)(addr))#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}/* =========================================================================== * Internal compression state. */#define LENGTH_CODES 29/* number of length codes, not counting the special END_BLOCK code */#define LITERALS  256/* number of literal bytes 0..255 */#define L_CODES (LITERALS+1+LENGTH_CODES)/* number of Literal or Length codes, including the END_BLOCK code */#define D_CODES   30/* number of distance codes */#define BL_CODES  19/* number of codes used to transfer the bit lengths */#define HEAP_SIZE (2*L_CODES+1)/* maximum heap size */#define MAX_BITS 15/* All codes must not exceed MAX_BITS bits */#define INIT_STATE    42#define BUSY_STATE   113#define FINISH_STATE 666/* Stream status */#define Freq fc.freq#define Code fc.code#define Dad  dl.dad#define Len  dl.len/* defines for inflate input/output *//*   update pointers and return */#define UPDBITS {s->bitb=b;s->bitk=k;}#define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}#define UPDOUT {s->write=q;}#define UPDATE {UPDBITS UPDIN UPDOUT}#define LEAVE {UPDATE return inflate_flush(s,z,r);}/*   get bytes and bits */#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}#define NEXTBYTE (n--,*p++)#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}#define DUMPBITS(j) {b>>=(j);k-=(j);}/*   output bytes */#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)#define LOADOUT {q=s->write;m=(uInt)WAVAIL;}#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}#define OUTBYTE(a) {*q++=(Byte)(a);m--;}/*   load local pointers */#define LOAD {LOADIN LOADOUT}/* Output a byte on the stream. * IN assertion: there is enough room in pending_buf. */#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}#define DO1(buf,i)  {s1 += buf[i]; s2 += s1;}#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);#define DO16(buf)   DO8(buf,0); DO8(buf,8);/* simplify the use of the inflate_huft type with some defines */#define base more.Base#define next more.Next#define exop word.what.Exop#define bits word.what.Bits/* If BMAX needs to be larger than 16, then h and x[] should be uLong. */#define BMAX 15         /* maximum bit length of any code */#define N_MAX 288       /* maximum number of codes in any set */#define C0 *p++ = 0;#define C2 C0 C0 C0 C0#define C4 C2 C2 C2 C2#define FIXEDH 530      /* number of hufts used by fixed tables */#define	BUF_SIZE	100000#define	MEM_ALIGN	4#define	BLK_ALIGN	sizeof(int)#define	ROUND_UP(n)	((n + BLK_ALIGN - 1) & (~(BLK_ALIGN - 1)))#define	BLK_HDR_SIZE	(2 * sizeof(int))#define	BLK_NEXT(b)	(*(((int *)(b)) - 1))#define	BLK_PREV(b)	(*(((int *)(b)) - 2))#define	BLK_HDRS_LINK(this,next)		\		{				\		BLK_NEXT(this) = (int)(next);	\		BLK_PREV(next) = (int)(this);	\		}#define	BLK_IS_FREE(b)	(BLK_NEXT(b) & 1)#define	BLK_FREE_SET(b)	(BLK_NEXT(b) |= 1)#define	BLK_IS_VALID(b)	(((char *)b == buf)	\		|| (BLK_PREV(BLK_NEXT(b)) == (int)(b)))/* simplify the use of the inflate_huft type with some defines */#define base more.Base#define next more.Next#define exop word.what.Exop#define bits word.what.Bits/* macros for bit input with no checking and for returning unused bytes */#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}#define UNGRAB {n+=(c=k>>3);p-=c;k&=7;}/* Diagnostic functions */#ifdef DEBUG#  include <stdio.h>#  ifndef verbose#    define verbose 0#  endif#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}#  define Trace(x) fprintf x#  define Tracev(x) {if (verbose) fprintf x ;}#  define Tracevv(x) {if (verbose>1) fprintf x ;}#  define Tracec(c,x) {if (verbose && (c)) fprintf x ;}#  define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}#  define DBG_PUT(a,b)	fprintf (stderr, a, (unsigned int)b);#else#  define Assert(cond,msg)#  define Trace(x)#  define Tracev(x)#  define Tracevv(x)#  define Tracec(c,x)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -