Skip to content

Commit

Permalink
patterns/jpeg: Small improvements (#184)
Browse files Browse the repository at this point in the history
* patterns/jpeg: exclude EOI marker from SOS image data

* patterns/jpeg: use type::Magic for magic numbers

* patterns/jpeg: add RGB component IDs

* patterns/jpeg: add struct for APP14 marker

* patterns/jpeg: add definition for COM marker

* patterns/jpeg: add some format_read() for better legibility
  • Loading branch information
bgilbert authored Oct 29, 2023
1 parent 8748646 commit e0a602c
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions patterns/jpeg.hexpat
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#pragma author WerWolv
#pragma description JPEG Image Format

#include <std/io.pat>
#include <std/mem.pat>
#include <type/magic.pat>
#pragma endian big

#pragma MIME image/jpeg
Expand Down Expand Up @@ -48,6 +50,12 @@ enum DensityUnit : u8 {
PixelsPerCm = 0x02
};

enum ColorTransform : u8 {
Unknown = 0x00,
YCbCr = 0x01,
YCCK = 0x02
};

struct Pixel {
u8 r, g, b;
} [[sealed, transform("transform_pixel")]];
Expand All @@ -58,26 +66,41 @@ fn transform_pixel(Pixel pixel) {


struct APP0 {
char magic[5];
type::Magic<"JFIF\x00"> magic;
u8 versionMajor, versionMinor;
DensityUnit densityUnit;
u16 densityX, densityY;
u8 thumbnailX, thumbnailY;
Pixel thumbnail[thumbnailX * thumbnailY] [[sealed]];
};

struct APP14 {
type::Magic<"Adobe"> magic;
u16 version;
u16 flags0;
u16 flags1;
ColorTransform transform;
};

enum ComponentId : u8 {
Y = 1,
CB = 2,
CR = 3,
I = 4,
Q = 5
Q = 5,
B = 66,
G = 71,
R = 82
};

struct SOF0Component {
ComponentId componentId;
u8 samplingFactors;
u8 quantizationTableId;
} [[format_read("sof0_component_read")]];

fn sof0_component_read(SOF0Component c) {
return std::format("({}, {}, {})", c.componentId, c.samplingFactors, c.quantizationTableId);
};

struct SOF0 {
Expand All @@ -99,11 +122,11 @@ struct SOS {
u8 endSpectral;
u8 apprBitPos;

u8 image_data[while(!std::mem::eof())] [[sealed]];
u8 image_data[std::mem::size() - $ - 2] [[sealed]];
};

struct Segment {
u8 magic;
type::Magic<"\xff"> magic;
Marker marker;

if (marker == Marker::SOI || marker == Marker::EOI) {
Expand All @@ -112,6 +135,10 @@ struct Segment {
u16 length;
if (marker == Marker::APP0) {
APP0 data;
} else if (marker == Marker::APP14) {
APP14 data;
} else if (marker == Marker::COM) {
char data[length - sizeof(length)];
} else if (marker == Marker::SOF0) {
SOF0 data;
} else if (marker == Marker::SOS) {
Expand All @@ -120,6 +147,10 @@ struct Segment {
u8 data[length - sizeof(length)] [[sealed]];
}
}
} [[format_read("segment_read")]];

fn segment_read(Segment s) {
return std::format("{}", s.marker);
};

Segment segments[while(!std::mem::eof())] @ 0x00 [[hex::visualize("image", this)]];

0 comments on commit e0a602c

Please sign in to comment.