-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathHuffmanCoding.cpp
350 lines (299 loc) · 7.61 KB
/
HuffmanCoding.cpp
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
#include <queue>
#include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <unistd.h>
#include <pthread.h>
#include "bitChar.h"
#include "timer.h"
using namespace std;
// Used to store characters and their frequencies
const int asciiLength = 256;
int letterCount[asciiLength];
string codes[asciiLength];
// Used to tell how much memory compression saves
long long originalSize = 0, compressedSize = 0;
// Threading variables
int numThreads;
pthread_mutex_t mutex;
pthread_cond_t conditional;
// Structure used to make a tree
struct node
{
long long value;
char letter;
struct node *left, *right;
};
// Compare class used to compare node values. Used for the priority queue
class compare
{
public:
bool operator()(const node *left, const node *right) const
{
return left->value > right->value;
}
};
// Priority queue used to make the tree
typedef std::priority_queue<node*, vector<node*>, compare> nodeTree;
// Builds the huffman tree by finding the two smallest nodes and summing their values
// to create a parent node for the two cild nodes
void buildTree(nodeTree &tree)
{
while(tree.size() > 1)
{
node *current = new node;
current->left = tree.top();
tree.pop();
current->right = tree.top();
tree.pop();
current->value = current->left->value + current->right->value;
current->letter = -1;
tree.push(current);
}
return;
}
// Traverse the tree to create the codes. Add 0 for left and 1 for right
void createCode(node *tree)
{
static string bitCode = "";
// Add a 1 to the code for nodes on the right
if(tree->right != NULL)
{
bitCode += "1";
createCode(tree->right);
bitCode = bitCode.substr(0, bitCode.size() - 1);
}
// Add a 0 to the code for nodes on the left
if(tree->left != NULL)
{
bitCode += "0";
createCode(tree->left);
bitCode = bitCode.substr(0, bitCode.size() - 1);
}
// Assign the code for the leaf's letter once we reach a leaf node
if(!tree->left && !tree->right)
{
codes[tree->letter] = bitCode;
}
return;
}
// Gets the frequency of each character in the file
void countLetters(string file, long long &count)
{
char letter;
ifstream inFile(file.c_str());
inFile >> noskipws;
for(int i = 0; i < asciiLength; i++)
{
letterCount[i] = 0;
}
while(inFile >> letter)
{
if(letter >= 0 && letter < asciiLength)
{
++letterCount[letter];
++count;
}
}
inFile.close();
return;
}
// Compresses the file in serial or parallel
void* compressFile (void *threadId)
{
// Thread id
long id = (long) threadId;
// Used to get the size of a partition and where to start and end the partition
long long partition = originalSize / numThreads;
long long start = id * partition;
long long end;
// Character and file reading variables
char input;
ofstream outf;
bitChar bChar;
string bits = "";
string inFile = "original.txt";
char outFile[16];
sprintf(outFile, "compressed-%i.mpc", (int) id);
// If its the last thread, the end of the file is always the end of the partition
if(numThreads - 1 == id)
{
end = originalSize;
}
else // otherwise find the correct partition
{
end = (id + 1) * partition;
}
// Read in the original file
ifstream inf(inFile.c_str());
inf.seekg(start);
inf >> noskipws;
while(inf >> input && start <= end)
{
start++;
bits += codes[input];
}
inf.close();
// Prepare to write to the compressed file
bChar.setBits(bits);
outf.open(outFile);
outf << noskipws;
// Write to the compressed file and increase the bit count
// Need mutual exclusion here to not overwrite compressedSize
pthread_mutex_lock(&mutex);
compressedSize += bChar.insertBits(outf);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main()
{
int compress;
long long i;
unsigned char inChar;
string inFile = "", outFile = "", bits = "", bitsSub = "";
ofstream outf;
ifstream inf;
nodeTree tree;
bitChar bChar;
float memorySaved = 0;
node *temp;
double startTime, endTime, elapsedTime;
long thread;
pthread_mutex_init (&mutex, NULL);
pthread_cond_init (&conditional, NULL);
// Decide whether to compress or decompress it
printf("Type 0 to decompress or 1 to compress >");
scanf("%i", &compress);
// If the user decides to compress the file
if( compress == 1)
{
//initialize threading variables
printf("How many threads would you like to use? >");
scanf("%i", &numThreads);
pthread_t threads[numThreads];
// Set up input and output files
inFile = "original.txt";
outFile = "compressed.mpc";
outf.open(outFile.c_str());
// Get lettter frequencies
countLetters(inFile, originalSize);
// Make sure to add an EOT character
if(letterCount[3] == 0)
{
letterCount[3] = 1;
}
// Output the frequency of each character at the top of the file to use when decoding the file
for(i = 0; i < asciiLength; i++)
{
outf << letterCount[i] << " ";
}
outf << endl;
outf << '#';
// Make a node for each symbol in the file
for (i = 0; i < asciiLength; i++)
{
if(letterCount[i] > 0)
{
temp = (node*) malloc(sizeof(node));
temp->value = letterCount[i];
temp->letter = i;
temp->left = NULL;
temp->right = NULL;
tree.push(temp);
}
}
// Build the tree and make the code table
printf("Building tree...\n");
buildTree(tree);
printf("Creating codes...\n");
createCode(tree.top());
printf("Starting compression timer...\n");
GET_TIME(startTime);
// Launch the threads to compress the file
for(thread = 0; thread < numThreads; thread++)
{
pthread_create(&threads[(int)thread], NULL, compressFile, (void*) thread);
}
printf("Compressing...\n");
// Wait for threads to finish
for(thread = 0; thread < numThreads; thread++)
{
pthread_join(threads[(int)thread], NULL);
pthread_detach(threads[thread]);
}
// Combine the individual partitions
printf("Combining partitions...\n");
system("./combine.sh");
// Print an EOT character at the end of the file
outf << codes[3];
printf("Stopping compression timer...\n");
GET_TIME(endTime);
elapsedTime = endTime - startTime;
// Get the amount of memory saved and how much time compression took
memorySaved = 100 - ((float)compressedSize / ((float)originalSize * 8.0) * 100.0);
printf("File successfully compressed!\n");
printf("Saved %.2f%% of space\n", memorySaved);
printf("Compression took %f seconds with %d threads\n", elapsedTime, numThreads);
}
else // Otherwise decompress the file
{
inFile = "compressed.mpc";
outFile = "decompressed.txt";
inf.open(inFile.c_str());
outf.open(outFile.c_str());
// Create a node for each character
for(i = 0; i < asciiLength; i++)
{
inf >> letterCount[i];
if(letterCount[i] > 0)
{
temp = (node*) malloc(sizeof(node));
temp->value = letterCount[i];
temp->letter = i;
temp->left = NULL;
temp->right = NULL;
tree.push(temp);
}
}
// Build a tree and codes
printf("building tree...\n");
buildTree(tree);
printf("creating codes...\n");
createCode(tree.top());
// Read the header of the file (frequencies of the characters)
while(inChar != '#')
{
inf >> inChar;
}
// Convert the bits in the file to character 1's and 0's
inf >> noskipws;
while(inf >> inChar)
{
bits += bChar.getBits(inChar);
}
inf.close();
// Convert the character 1's and 0's into actual characters after finding a matching code
for(i = 0; i < bits.length(); i++)
{
bitsSub += bits[i];
for(int j = 0; j < asciiLength; j++)
{
if(bitsSub == codes[j])
{
if(j == 3)
{
outf << "\n";
i = bits.length();
break;
}
outf << (char)j;
bitsSub = "";
break;
}
}
}
}
outf.close();
return 0;
}