usaa24/sk1/compressor.c

208 lines
6.8 KiB
C
Raw Normal View History

2025-01-19 14:10:47 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2025-01-27 15:08:53 +00:00
#include "compressor.h"
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
#define BUFFER_SIZE 4096
#define MAX_SYMBOLS 257
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Макрос для обмена двух узлов
#define SWAP_NODES(a, b) { Node* temp = a; a = b; b = temp; }
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Определение структуры узла дерева
typedef struct Node {
int symbol;
unsigned int frequency;
struct Node *left, *right;
} Node;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Функция для создания нового узла
Node* create_node(int symbol, unsigned int frequency) {
Node* node = (Node*)malloc(sizeof(Node));
node->symbol = symbol;
2025-01-26 19:22:02 +00:00
node->frequency = frequency;
node->left = node->right = NULL;
return node;
2025-01-19 14:10:47 +00:00
}
2025-01-27 15:08:53 +00:00
// Функция для построения дерева Хаффмана
Node* build_huffman_tree(const unsigned int* frequencies) {
Node* nodes[MAX_SYMBOLS];
int node_count = 0;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Создаем узлы для всех символов с ненулевой частотой
for (int i = 0; i < MAX_SYMBOLS; i++) {
if (frequencies[i] > 0) {
nodes[node_count++] = create_node(i, frequencies[i]);
}
2025-01-19 14:10:47 +00:00
}
2025-01-27 15:08:53 +00:00
// Объединяем узлы в дерево
while (node_count > 1) {
// Сортируем узлы по частоте
for (int i = 0; i < node_count - 1; i++) {
for (int j = i + 1; j < node_count; j++) {
if (nodes[i]->frequency > nodes[j]->frequency) {
SWAP_NODES(nodes[i], nodes[j]);
}
}
}
2025-01-26 19:22:02 +00:00
2025-01-27 15:08:53 +00:00
// Объединяем два узла с наименьшей частотой
Node* left = nodes[0];
Node* right = nodes[1];
Node* parent = create_node(-1, left->frequency + right->frequency);
parent->left = left;
parent->right = right;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Заменяем объединенные узлы новым родительским узлом
nodes[0] = parent;
nodes[1] = nodes[--node_count];
2025-01-19 14:10:47 +00:00
}
2025-01-27 15:08:53 +00:00
return nodes[0];
2025-01-19 17:39:39 +00:00
}
2025-01-27 15:08:53 +00:00
// Рекурсивная функция для генерации кодов Хаффмана
void generate_huffman_codes(Node* root, char* code, int depth, char codes[MAX_SYMBOLS][MAX_SYMBOLS]) {
if (!root->left && !root->right) {
code[depth] = '\0'; // Завершаем код символа
strcpy(codes[root->symbol], code);
return;
2025-01-19 14:10:47 +00:00
}
2025-01-19 17:53:01 +00:00
if (root->left) {
2025-01-27 15:08:53 +00:00
code[depth] = '0'; // Добавляем бит '0' для левого поддерева
generate_huffman_codes(root->left, code, depth + 1, codes);
2025-01-19 17:53:01 +00:00
}
if (root->right) {
2025-01-27 15:08:53 +00:00
code[depth] = '1'; // Добавляем бит '1' для правого поддерева
generate_huffman_codes(root->right, code, depth + 1, codes);
2025-01-19 17:53:01 +00:00
}
}
2025-01-27 15:08:53 +00:00
// Функция для освобождения памяти, выделенной под дерево Хаффмана
void free_huffman_tree(Node* root) {
2025-01-26 20:02:31 +00:00
if (!root) return;
free_huffman_tree(root->left);
free_huffman_tree(root->right);
free(root);
}
2025-01-26 20:09:11 +00:00
2025-01-27 15:08:53 +00:00
// Функция сжатия данных с использованием алгоритма Хаффмана
2025-01-26 19:22:02 +00:00
int compress_1(const char* input_file, const char* output_file) {
FILE* input = fopen(input_file, "rb");
FILE* output = fopen(output_file, "wb");
2025-01-27 15:08:53 +00:00
if (!input || !output) return -1;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
unsigned int frequencies[MAX_SYMBOLS] = {0};
unsigned char buffer[BUFFER_SIZE];
size_t bytes_read;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Подсчет частот символов
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, input)) > 0) {
for (size_t i = 0; i < bytes_read; i++) {
frequencies[buffer[i]]++;
2025-01-19 14:10:47 +00:00
}
}
2025-01-27 15:08:53 +00:00
frequencies[256] = 1; // Добавляем маркер EOF
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
Node* root = build_huffman_tree(frequencies);
if (!root) return -1;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Генерация кодов Хаффмана
char codes[MAX_SYMBOLS][MAX_SYMBOLS] = {{0}};
char code[MAX_SYMBOLS] = {0};
generate_huffman_codes(root, code, 0, codes);
2025-01-26 19:22:02 +00:00
2025-01-27 15:08:53 +00:00
// Записываем частоты в выходной файл
fwrite(frequencies, sizeof(frequencies[0]), MAX_SYMBOLS, output);
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
// Сжимаем данные
rewind(input);
unsigned char current_byte = 0;
2025-01-26 19:22:02 +00:00
int bit_count = 0;
2025-01-27 15:08:53 +00:00
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, input)) > 0) {
for (size_t i = 0; i < bytes_read; i++) {
char* symbol_code = codes[buffer[i]];
for (size_t j = 0; symbol_code[j] != '\0'; j++) {
current_byte = (current_byte << 1) | (symbol_code[j] - '0');
bit_count++;
if (bit_count == 8) {
fwrite(&current_byte, 1, 1, output);
current_byte = 0;
bit_count = 0;
}
2025-01-19 14:10:47 +00:00
}
}
}
2025-01-26 19:22:02 +00:00
2025-01-27 15:08:53 +00:00
// Записываем маркер EOF
char* eof_code = codes[256];
for (size_t j = 0; eof_code[j] != '\0'; j++) {
current_byte = (current_byte << 1) | (eof_code[j] - '0');
bit_count++;
if (bit_count == 8) {
fwrite(&current_byte, 1, 1, output);
current_byte = 0;
bit_count = 0;
}
}
2025-01-26 19:22:02 +00:00
if (bit_count > 0) {
2025-01-27 15:08:53 +00:00
current_byte <<= (8 - bit_count);
fwrite(&current_byte, 1, 1, output);
2025-01-19 14:10:47 +00:00
}
2025-01-19 17:39:39 +00:00
2025-01-26 19:22:02 +00:00
fclose(input);
fclose(output);
2025-01-26 20:02:31 +00:00
free_huffman_tree(root);
2025-01-19 14:10:47 +00:00
return 0;
}
2025-01-27 15:08:53 +00:00
// Функция декомпрессии данных с использованием алгоритма Хаффмана
int decompress_1(const char* input_file, const char* output_file) {
FILE* input = fopen(input_file, "rb");
FILE* output = fopen(output_file, "wb");
if (!input || !output) return -1;
2025-01-19 14:10:47 +00:00
2025-01-27 15:08:53 +00:00
unsigned int frequencies[MAX_SYMBOLS] = {0};
fread(frequencies, sizeof(frequencies[0]), MAX_SYMBOLS, input);
Node* root = build_huffman_tree(frequencies);
if (!root) return -1;
2025-01-26 19:22:02 +00:00
2025-01-27 15:08:53 +00:00
Node* current = root;
2025-01-26 19:22:02 +00:00
unsigned char byte;
2025-01-27 15:08:53 +00:00
int bit;
2025-01-26 19:22:02 +00:00
2025-01-27 15:08:53 +00:00
// Читаем и декодируем символы
while (fread(&byte, 1, 1, input) == 1) {
for (bit = 7; bit >= 0; bit--) {
current = (byte & (1 << bit)) ? current->right : current->left;
2025-01-19 14:10:47 +00:00
2025-01-26 19:22:02 +00:00
if (!current->left && !current->right) {
2025-01-27 15:08:53 +00:00
if (current->symbol == 256) { // Маркер EOF
fclose(input);
fclose(output);
free_huffman_tree(root);
return 0;
}
fwrite(&current->symbol, 1, 1, output);
2025-01-19 14:10:47 +00:00
current = root;
}
}
}
2025-01-19 17:39:39 +00:00
2025-01-26 19:22:02 +00:00
fclose(input);
fclose(output);
2025-01-26 20:02:31 +00:00
free_huffman_tree(root);
2025-01-26 19:22:02 +00:00
return 0;
2025-01-27 15:08:53 +00:00
}
int compress_2(const char* input_file_name, const char* output_file_name){
return 0;
}
int decompress_2(const char* input_file_name, const char* output_file_name){
return 0;
}