GPL을 따르는 MCM의 소스를 보고 일부 분석할려고 한다.


 여기서 HPP에 설정된 일부 소스만 작성할려고 한다.


 전체 소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*    MCM file compressor
    Copyright (C) 2013, Google Inc.
    Authors: Mathieu Chartier
    LICENSE
    This file is part of the MCM file compressor.
    MCM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    MCM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with MCM.  If not, see <http://www.gnu.org/licenses/>.
*/
 
#ifndef _UTIL_HPP_
#define _UTIL_HPP_
 
#include <cassert>
#include <ctime>
#include <emmintrin.h>
#include <iostream>
#include <mmintrin.h>
#include <mutex>
#include <ostream>
#include <stdint.h>
#include <sstream>
#include <string>
#include <vector>
 
#ifdef WIN32
#define forceinline __forceinline
#else
#define forceinline inline __attribute__((always_inline))
#endif
#define ALWAYS_INLINE forceinline
 
#define no_alias __restrict
 
#ifndef BYTE_DEFINED
#define BYTE_DEFINED
typedef unsigned char byte;
#endif
 
#ifndef UINT_DEFINED
#define UINT_DEFINED
typedef unsigned int uint;
#endif
 
#ifndef WORD_DEFINED
#define WORD_DEFINED
typedef unsigned short word;
#endif
 
// TODO: Implement these.
#define LIKELY(x) x
#define UNLIKELY(x) x
 
#ifdef _DEBUG
static const bool kIsDebugBuild = true;
#else
static const bool kIsDebugBuild = false;
#endif
 
#ifdef _MSC_VER
#define ASSUME(x) __assume(x)
#else
#define ASSUME(x)
#endif
    
typedef uint32_t hash_t;
 
static const uint64_t KB = 1024;
static const uint64_t MB = KB * KB;
static const uint64_t GB = KB * MB;
static const uint32_t kCacheLineSize = 64// Sandy bridge.
static const uint32_t kPageSize = 4 * KB;
static const uint32_t kBitsPerByte = 8;
 
forceinline void prefetch(const void* ptr) {
#ifdef WIN32
    _mm_prefetch((char*)ptr, _MM_HINT_T0);
#else
    __builtin_prefetch(ptr);
#endif
}
 
forceinline static bool isUpperCase(int c) {
    return c >= 'A' && c <= 'Z';
}
forceinline static bool isLowerCase(int c) {
    return c >= 'a' && c <= 'z';
}
forceinline static bool isWordChar(int c) {
    return isLowerCase(c) || isUpperCase(c) || c >= 128;
}
forceinline static int makeLowerCase(int c) {
    assert(isUpperCase(c));
    return c - 'A' + 'a';
}
forceinline static int makeUpperCase(int c) {
    assert(isLowerCase(c));
    return c - 'a' + 'A';
}
 
// Trust in the compiler
forceinline uint32_t rotate_left(uint32_t h, uint32_t bits) {
    return (h << bits) | (h >> (sizeof(h) * 8 - bits));
}
 
forceinline uint32_t rotate_right(uint32_t h, uint32_t bits) {
    return (h << (sizeof(h) * 8 - bits)) | (h >> bits);
}
 
#define check(c) while (!(c)) { std::cerr << "check failed " << #c << std::endl*reinterpret_cast<int*>(1234= 4321;}
#define dcheck(c) assert(c)
 
template <const uint32_t A, const uint32_t B, const uint32_t C, const uint32_t D>
struct shuffle {
    enum {
        value = (D << 6| (C << 4| (B << 2| A,
    };
};
 
forceinline bool isPowerOf2(uint32_t n) {
    return (n & (n - 1)) == 0;
}
 
forceinline uint bitSize(uint Value) {
    uint Total = 0;
    for (;Value;Value >>= 1, Total++);
    return Total;
}
 
template <typename T>
void printIndexedArray(const std::string& str, const T& arr) {
    uint32_t index = 0;
    std::cout << str << std::endl;
    for (const auto& it : arr) {
        if (it) {
            std::cout << index << ":" << it << std::endl;
        }
        index++;
    }
}
 
template <const uint64_t n>
struct _bitSize {static const uint64_t value = 1 + _bitSize</ 2>::value;};
 
template <>
struct _bitSize<0> {static const uint64_t value = 0;};
 
inline void fatalError(const std::string& message) {
    std::cerr << "Fatal error: " << message << std::endl;
    *reinterpret_cast<uint32_t*>(1234= 0;
}
 
inline void unimplementedError(const char* function) {
    std::ostringstream oss;
    oss << "Calling implemented function " << function;
    fatalError(oss.str());
}
 
inline uint32_t rand32() {
    return rand() ^ (rand() << 16);
}
 
forceinline int fastAbs(int n) {
    int mask = n >> 31;
    return (n ^ mask) - mask;
}
 
bool fileExists(const char* name);
 
class Closure {
public:
    virtual void run() = 0;
};
 
template <typename Container>
void deleteValues(Container& container) {
    for (auto* p : container) {
        delete p;
    }
    container.clear();
}
 
class ScopedLock {
public:
    ScopedLock(std::mutex& mutex) : mutex_(mutex) {
        mutex_.lock();
    }
 
    ~ScopedLock() {
        mutex_.unlock();
    }
 
private:
    std::mutex& mutex_;
};
 
forceinline void copy16bytes(byte* no_alias out, const byte* no_alias in, const byte* limit) {
    _mm_storeu_ps(reinterpret_cast<float*>(out), _mm_loadu_ps(reinterpret_cast<const float*>(in)));
}
 
forceinline static void memcpy16(void* dest, const void* src, size_t len) {
    uint8_t* no_alias dest_ptr = reinterpret_cast<uint8_t* no_alias>(dest);
    const uint8_t* no_alias src_ptr = reinterpret_cast<const uint8_t* no_alias>(src);
    const uint8_t* no_alias limit = dest_ptr + len;
    *dest_ptr++ = *src_ptr++;
    if (len >= sizeof(__m128)) {
        const byte* no_alias limit2 = limit - sizeof(__m128);
        do {
            copy16bytes(dest_ptr, src_ptr, limit);
            src_ptr += sizeof(__m128);
            dest_ptr += sizeof(__m128);
        } while (dest_ptr < limit2);
    }
    while (dest_ptr < limit) {
        *dest_ptr++ = *src_ptr++;
    }
}
 
template<typename CopyUnit>
forceinline void fastcopy(byte* no_alias out, const byte* no_alias in, const byte* limit) {
    do {
        *reinterpret_cast<CopyUnit* no_alias>(out) = *reinterpret_cast<const CopyUnit* no_alias>(in);
        out += sizeof(CopyUnit);
        in += sizeof(CopyUnit);
    } while (in < limit);
}
 
forceinline void memcpy16unsafe(byte* no_alias out, const byte* no_alias in, const byte* limit) {
    do {
        copy16bytes(out, in, limit);
        out += 16;
        in += 16;
    } while (out < limit);
}
 
template<uint32_t kMaxSize>
class FixedSizeByteBuffer {
public:
    uint32_t getMaxSize() const {
        return kMaxSize;
    }
 
protected:
    byte buffer_[kMaxSize];
};
 
// Move to front.
template <typename T>
class MTF {
    std::vector<T> data_;
public:
    void init(size_t n) {
        data_.resize(n);
        for (size_t i = 0; i < n; ++i) {
            data_[i] = static_cast<T>(n - 1 - i);
        }
    }
    size_t find(T value) {
        for (size_t i = 0; i < data_.size(); ++i) {
            if (data_[i] == value) {
                return i;
            }
        }
        return data_.size();
    }
    forceinline T back() const {
        return data_.back();
    }
    size_t size() const {
        return data_.size();
    }
    void moveToFront(size_t index) {
        auto old = data_[index];
        while (index) {
            data_[index] = data_[index - 1];
            --index;
        }
        data_[0= old;
    }
};
 
template <class T, size_t kSize>
class StaticArray {
public:
    StaticArray() {
    }
    ALWAYS_INLINE const T& operator[](size_t i) const {
        return data_[i];
    }
    ALWAYS_INLINE T& operator[](size_t i) {
        return data_[i];
    }
    ALWAYS_INLINE size_t size() const {
        return kSize;
    }
 
private:
    T data_[kSize];
};
 
template <class T, uint32_t kCapacity>
class StaticBuffer {
public:
    StaticBuffer() : pos_(0), size_(0) {
    }
    ALWAYS_INLINE const T& operator[](size_t i) const {
        return data_[i];
    }
    ALWAYS_INLINE T& operator[](size_t i) {
        return data_[i];
    }
    ALWAYS_INLINE size_t pos() const {
        return pos_;
    }
    ALWAYS_INLINE size_t size() const {
        return size_;
    }
    ALWAYS_INLINE size_t capacity() const {
        return kCapacity;
    }
    ALWAYS_INLINE size_t reamainCapacity() const {
        return capacity() - size();
    }
    ALWAYS_INLINE T get() {
        (pos_ < size_);
        return data_[pos_++];
    }
    ALWAYS_INLINE void read(T* ptr, size_t len) {
        dcheck(pos_ + len <= size_);
        std::copy(&data_[pos_], &data_[pos_ + len], &ptr[0]);
        pos_ += len;
    }
    ALWAYS_INLINE void put(T c) {
        dcheck(pos_ < size_);
        data_[pos_++= c;
    }
    ALWAYS_INLINE void write(const T* ptr, size_t len) {
        dcheck(pos_ + len <= size_);
        std::copy(&ptr[0], &ptr[len], &data_[pos_]);
        pos_ += len;
    }
    ALWAYS_INLINE size_t remain() const {
        return size_ - pos_;
    }
    void erase(size_t chars) {
        dcheck(chars <= pos());
        std::move(&data_[chars], &data_[size()], &data_[0]);
        pos_ -= std::min(pos_, chars);
        size_ -= std::min(size_, chars);
    }
    void addPos(size_t n) {
        pos_ += n;
        dcheck(pos_ <= size());
    }
    void addSize(size_t n) {
        size_ += n;
        dcheck(size_ <= capacity());
    }
    T* begin() {
        return &operator[](0);
    }
    T* end() {
        return &operator[](size_);
    }
    T* limit() {
        return &operator[](capacity());
    }
 
private:
    size_t pos_;
    size_t size_;
    T data_[kCapacity];
};
 
std::string prettySize(uint64_t size);
std::string formatNumber(uint64_t n);
double clockToSeconds(clock_t c);
std::string errstr(int err);
std::vector<byte> randomArray(size_t size);
uint64_t computeRate(uint64_t size, uint64_t delta_time);
std::vector<byte> loadFile(const std::string& name, uint32_t max_size = 0xFFFFFFF);
std::string trimExt(const std::string& str);
 
#endif
 
cs


 여기서 일부 자주 사용될 듯한 간단한 소스가 구현이 되어 있어서 설명을 넣을려고 한다.


1
2
3
static const uint64_t KB = 1024;
static const uint64_t MB = KB * KB;
static const uint64_t GB = KB * MB;
cs


 윗 소스는 메모리 크기의 KB및 MB, GB를 정의내리는 것이다.

 static이자 const이기 때문에, 매크로랑 유사하다. 라고 봐도 무관하다.


 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
forceinline static bool isUpperCase(int c) {
    return c >= 'A' && c <= 'Z';
}
forceinline static bool isLowerCase(int c) {
    return c >= 'a' && c <= 'z';
}
forceinline static bool isWordChar(int c) {
    return isLowerCase(c) || isUpperCase(c) || c >= 128;
}
forceinline static int makeLowerCase(int c) {
    assert(isUpperCase(c));
    return c - 'A' + 'a';
}
forceinline static int makeUpperCase(int c) {
    assert(isLowerCase(c));
    return c - 'a' + 'A';
}
 
// Trust in the compiler
forceinline uint32_t rotate_left(uint32_t h, uint32_t bits) {
    return (h << bits) | (h >> (sizeof(h) * 8 - bits));
}
 
forceinline uint32_t rotate_right(uint32_t h, uint32_t bits) {
    return (h << (sizeof(h) * 8 - bits)) | (h >> bits);
}
cs



 isUpperCase라는 것은 함수명에 설명 되어있듯, 대문자인지를 확인하는 소스이다.

 isLowerCase라는 것은 함수명에 설명 되어있듯, 소문자인지를 확인하는 소스이다.

 isWordChar라는 것은 함수명에 설명 되어있듯, 문자인지를 확인하는 소스이다.


 makeLowerCase라는 것은 함수명에 설명 되어있듯, 대문자를 소문자로 바꾸는 소스이다.

 makeUpperCase라는 것은 함수명에 설명 되어있듯, 소문자를 대문자로 바꾸는 소스이다.


rotate_left라는 것은 함수명에 설명 되어있듯, 왼쪽으로 회전, right는 오른쪽으로 회전 소스이다. 

Posted by JunkMam
,

 현재 인공지능을 이용해서 파일을 압축하는 프로그램이 나왔다.

 대표적인 방법으로는 paq라는 프로그램이다.[각주:1]



 paq를 개량해서 lite paq, fast paq 등 경량화 및 속도를 올린 paq 프로그램들이 나왔고, 혹은 paq 방식의 알고리즘인 CM(Context Mixing)을 이용해서 만든 프로그램이 있다.


 여기서 MCM또한 CM 알고리즘을 이용해서 만들어낸 프로그램이다.


 MCM를 사용하는 방법을 작성할려고한다.


 MCM은 일단, 폴더를 제작해서 압축하는 방식이 없다.(단일 파일만 압축할 수 있다는 뜻이다.)


 일단, 각각의 파일을 압축해서 합치는 방식은 오히려 파일 용량의 압축이 적으니 단일 파일을 압축시키는 것이 좋은 경우가 많이 발견되었다.


 MCM을 사용할려면 기본적으로 기준 환경을 맞춰줘야지 속도가 잘 나온다.


 환경

 Memory 최대 8G 이상.


 최고 압축을 사용할려면, Memory가 최대 8G 이상이 아니라면, 오히려 설명이 되어 있는 파일보다 속도가 제대로 안나온다.(페이징 작업에 의해서 속도가 감소하는 걸 느낄 수 있다.)


 paq보다 mcm가 메모리 사용량과 속도명에서 좀 더 좋은 점이 있다.(drt|lpaq을 이용하면 더 낫다 라는 설명이 되어 있지만, drt랑 lpaq가 제대로 안 돌아갔다.)


 아직까진 미완성이지만, mcm를 잘만 사용한다면, 용량을 줄여서 들고 다닐 수 있을 것이라고 나는 생각하고 있다.


 그럼, 이제 MCM을 사용하는 방법을 설명할려고 한다.


 mcm을 친다면, 다음과 같은 문장이 나오는 걸 알 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Error, input or output files missing
======================================================================
mcm compressor v0.83, by Mathieu Chartier (c)2015 Google Inc.
Experimental, may contain bugs. Contact mathieu.a.chartier@gmail.com
Special thanks to: Matt Mahoney, Stephan Busch, Christopher Mattern.
======================================================================
Caution: Experimental, use only for testing!
Usage: mcm.exe [command] [options] <infile> <outfile>
Options: d for decompress
-{t|f|m|h|x}{1 .. 11} compression option
t is turbo, f is fast, m is mid, h is high, x is max (default mid)
0 .. 11 specifies memory with 32mb .. 5gb per thread (default 6)
10 and 11 are only supported on 64 bits
-test tests the file after compression is done
Examples:
Compress: mcm.exe -m9 enwik8 enwik8.mcm
Decompress: mcm.exe d enwik8.mcm enwik8.ref
Failed to parse arguments
cs


 MCM은 총 4가지의 설정과 0~11까지 설정하는 것이 있다.


 t는 turbo, f는 fast, m는 mid, h는 high, x는 Max이다.(기본적으로 mid로 설정되어 있다.)


 t에서 x로 가면 갈 수록 속도가 느리고, 압축률이 높아진다.


 0~11의 설정이 되는데, 이것은 32Mb에서 5~6GByte까지 사용이 된다.


 여기서 10과 11은 64Bit에서만 지원이 가능하므로, 주의를 요한다. 라고 되어있다.


 그리고 압축을 풀려면, d을 사용하면, decompression이라고 할 수 있다.


 압축/풀기 예제

1
2
mcm -x11 enwik8 enwik8.mcm
mcm d enwik8.mcm enwki8
cs

 

 이렇게 해서 사용을 할 수 있게 된다.


 이것이 조금 더 발전을 해서 압축율이 높은 프로그램이 완성이 되었으면 한다.

  1. 참조 : https://en.wikipedia.org/wiki/PAQ(2016-07-08) [본문으로]
Posted by JunkMam
,