1/*
2Copyright 2013 Google Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15
16Author: lode.vandevenne@gmail.com (Lode Vandevenne)
17Author: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)
18*/
19
20#include "zlib_container.h"
21#include "util.h"
22
23#include <stdio.h>
24
25#include "deflate.h"
26
27
28/* Calculates the adler32 checksum of the data */
29static unsigned adler32(const unsigned char* data, size_t size)
30{
31  static const unsigned sums_overflow = 5550;
32  unsigned s1 = 1;
33  unsigned s2 = 1 >> 16;
34
35  while (size > 0) {
36    size_t amount = size > sums_overflow ? sums_overflow : size;
37    size -= amount;
38    while (amount > 0) {
39      s1 += (*data++);
40      s2 += s1;
41      amount--;
42    }
43    s1 %= 65521;
44    s2 %= 65521;
45  }
46
47  return (s2 << 16) | s1;
48}
49
50void ZopfliZlibCompress(const ZopfliOptions* options,
51                        const unsigned char* in, size_t insize,
52                        unsigned char** out, size_t* outsize) {
53  unsigned char bitpointer = 0;
54  unsigned checksum = adler32(in, (unsigned)insize);
55  unsigned cmf = 120;  /* CM 8, CINFO 7. See zlib spec.*/
56  unsigned flevel = 0;
57  unsigned fdict = 0;
58  unsigned cmfflg = 256 * cmf + fdict * 32 + flevel * 64;
59  unsigned fcheck = 31 - cmfflg % 31;
60  cmfflg += fcheck;
61
62  ZOPFLI_APPEND_DATA(cmfflg / 256, out, outsize);
63  ZOPFLI_APPEND_DATA(cmfflg % 256, out, outsize);
64
65  ZopfliDeflate(options, 2 /* dynamic block */, 1 /* final */,
66                in, insize, &bitpointer, out, outsize);
67
68  ZOPFLI_APPEND_DATA((checksum >> 24) % 256, out, outsize);
69  ZOPFLI_APPEND_DATA((checksum >> 16) % 256, out, outsize);
70  ZOPFLI_APPEND_DATA((checksum >> 8) % 256, out, outsize);
71  ZOPFLI_APPEND_DATA(checksum % 256, out, outsize);
72
73  if (options->verbose) {
74    fprintf(stderr,
75            "Original Size: %d, Zlib: %d, Compression: %f%% Removed\n",
76            (int)insize, (int)*outsize,
77            100.0 * (double)(insize - *outsize) / (double)insize);
78  }
79}
80