writing SOF header and huffman trees

This commit is contained in:
Muaz Ahmad 2023-12-05 12:34:42 +05:00
parent 4bc436d92b
commit 0a1df7feed

View file

@ -79,7 +79,7 @@ const Scan = struct {
for (0..4) |i| { for (0..4) |i| {
const huff_meta = gen_huffman(self.freqs[i]); const huff_meta = gen_huffman(self.freqs[i]);
try gen_codes(&self.huffs[i], huff_meta); try gen_codes(&self.huffs[i], huff_meta);
try dump_huffman(f, huff_meta); try dump_huffman(f, huff_meta, i);
} }
} }
}; };
@ -296,17 +296,28 @@ fn parse_block(block: *util.BlockQuantized, dc_diff: *i16, rle: *RLE_Seq, dc_fre
} }
fn write_headers(f: std.fs.File, buff: *const util.Buffers) !void { fn write_headers(f: std.fs.File, buff: *const util.Buffers) !void {
const w = buff.Y.len * 16;
const h = buff.Y[0].len * 16;
std.debug.print("{any} {any}\n", .{ w, h });
var out_buff = [6]u8{ 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84 } ++ [1]u8{0x00} ++ [_]u8{0x00} ** 64 ++ [1]u8{0x01} ++ [_]u8{0x00} ** 64; var out_buff = [6]u8{ 0xff, 0xd8, 0xff, 0xdb, 0x00, 0x84 } ++ [1]u8{0x00} ++ [_]u8{0x00} ** 64 ++ [1]u8{0x01} ++ [_]u8{0x00} ** 64;
for (0..64) |i| { for (0..64) |i| {
out_buff[7 + i] = @intFromFloat(buff.Q_Lum[i]); out_buff[7 + i] = @intFromFloat(buff.Q_Lum[i]);
out_buff[7 + i + 65] = @intFromFloat(buff.Q_Chrom[i]); out_buff[7 + i + 65] = @intFromFloat(buff.Q_Chrom[i]);
} }
_ = try f.write(&out_buff); _ = try f.write(&out_buff);
var sof_buff = [_]u8{
0xff, 0xc0, 0x00, 0x11, 0x08, @truncate(w >> 8), @truncate(w & 0x00ff), @truncate(h >> 8), @truncate(h & 0x00ff), 0x03,
0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
};
_ = try f.write(&sof_buff);
} }
fn dump_huffman(f: std.fs.File, huff_meta: HuffmanMeta) !void { fn dump_huffman(f: std.fs.File, huff_meta: HuffmanMeta, tree_i: usize) !void {
_ = huff_meta; const table_len = 3 + 16 + huff_meta.total_n;
_ = f; var out_buff = [5]u8{ 0xff, 0xc4, @truncate(table_len >> 8), @truncate(table_len & 0x00ff), @truncate(((tree_i % 2) << 4) | (tree_i / 2)) };
_ = try f.write(&out_buff);
_ = try f.write(huff_meta.bits[1..17]);
_ = try f.write(huff_meta.huffval[0..huff_meta.total_n]);
} }
pub fn generate_jpg(buff: util.Buffers, alloc: std.mem.Allocator) !void { pub fn generate_jpg(buff: util.Buffers, alloc: std.mem.Allocator) !void {