Beispiel #1
0
// Fetches the next huffman code from the bitstream
byte get_next_code(jpeg_huffman_table cur_table)
{
    word bit_string = 0;
    byte cur_length = 1;
    byte cur_code = 0;
    int found = 0;
    
    while (cur_length < 17)
    {
        bit_string <<= 1;
        bit_string |= fetch_bits(1);
        int code = get_huffman_code(bit_string, cur_length, cur_table);
        if (code > -1)
        {
            cur_code = code;
            found = 1;
            break;
        }
        cur_length++;
    }
    
    if (!found)
    {
        printf("No code found!\n");
        getc(stdin);
    }
    
    return cur_code;
}
Beispiel #2
0
int main(int argc, char *argv[])
{
    FILE *fp, *kmp;
    int i;
    if (argc == 3) {
        if (!(kmp = fopen(argv[1], "wb"))) {
            fprintf(stderr, "Couldn't open file %s\n", argv[1]);
            exit(EXIT_FAILURE);
        }
        if (!(fp = fopen(argv[2], "r"))) {
            fprintf(stderr, "Couldn't open file %s\n", argv[2]);
            exit(EXIT_FAILURE);
        }
    } else {
        printf("USAGE: %s <outfile.kmp> <infile.txt>\n", argv[0]);
        exit(EXIT_SUCCESS);
    }
    /* Create Huffman codebook from file */
    struct huffcode codebook[ALPHLEN];
    for (i=0; i<ALPHLEN; i++) {
        codebook[i].set = 0;
    }
    get_huffman_code(fp, codebook);
    /* Re-read input file, write each symbol's huffcode to temp file */
    rewind(fp);
    FILE *temp = tmpfile();
    struct bitstream *bs = initbitstream(temp, BS_WRITE);
    uint8_t byte;
    while (fread(&byte, sizeof(uint8_t), 1, fp) == 1) {
        if(!codebook[byte].set) {
            printf("byte: %d\n", byte);
            assert(0);
        }
        write_bitstring(bs, codebook[byte].code);
    }
    fclose(fp);
    /* Close bitstream, get padding bits in last byte */
    uint8_t padding = closebitstream(bs);
    /* Write header to the output file */
    write_header(kmp, padding, codebook);
    /* Copy bitstream from tempfile to output file */
    rewind(temp);
    while (fread(&byte, sizeof(uint8_t), 1, temp) == 1) {
        fwrite(&byte, sizeof(uint8_t), 1, kmp);
    }
    fclose(temp);
    fclose(kmp);
    return 0;
}