Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/tp/internal/cmdserver/cmdserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func runServer(ctx context.Context, cmd *base.Command, args []string) error {
base.SetExitStatus(base.SApplicationError)
return fmt.Errorf("failed to get printer: %w", err)
}
ippPrn, err := ippsrv.WrapDriver(p, "default", "Thermal Printer")
ippPrn, err := ippsrv.WrapDriver(p, "default", "LX-D02 Thermal Printer")
if err != nil {
base.SetExitStatus(base.SApplicationError)
return fmt.Errorf("failed to wrap printer: %w", err)
Expand Down
6 changes: 6 additions & 0 deletions cmd/tp/siginfo_generic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//go:build !darwin
package main


func trapSigInfo() {
}
160 changes: 160 additions & 0 deletions cupsraster/cupsraster.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
// Package cupsraster decodes the raster streams produced by client-side
// rasterisation in CUPS and macOS/iOS printing: PWG Raster (PWG 5102.4,
// image/pwg-raster) and Apple Raster (URF, image/urf). Both formats carry
// one or more pre-rendered pages compressed with the same simple run-length
// scheme; the decoder converts each page to an image.Image.
//
// References:
// - https://ftp.pwg.org/pub/pwg/candidates/cs-ippraster10-20120420-5102.4.pdf
// - https://openprinting.github.io/driverless/01-standards-and-their-pdls/#apple-raster
package cupsraster

import (
"bufio"
"fmt"
"image"
"image/color"
"io"
)

// Format identifies a supported raster stream format.
type Format int

const (
FormatUnknown Format = iota
FormatPWG // PWG Raster (image/pwg-raster)
FormatURF // Apple Raster (image/urf)
)

func (f Format) String() string {
switch f {
case FormatPWG:
return "PWG"
case FormatURF:
return "URF"
}
return "unknown"
}

// maxDim caps page dimensions to guard against corrupt headers.
const maxDim = 32768

// maxPixels caps total page size (width*height) to about 512 MiB of 8-bit
// gray, which is far beyond anything a label printer will see.
const maxPixels = 1 << 29

// Detect sniffs the magic bytes of data and reports the raster format, or
// FormatUnknown. PWG raster is identified by both the sync word and the
// PwgRaster header magic, which distinguishes it from little-endian CUPS
// raster streams sharing the sync word.
func Detect(data []byte) Format {
if len(data) >= len(pwgSyncWord)+len(pwgMagic) &&
string(data[:len(pwgSyncWord)]) == pwgSyncWord &&
string(data[len(pwgSyncWord):len(pwgSyncWord)+len(pwgMagic)]) == pwgMagic {
return FormatPWG
}
if len(data) >= len(urfMagic) && string(data[:len(urfMagic)]) == urfMagic {
return FormatURF
}
return FormatUnknown
}

// Page is a decoded raster page together with the resolution declared in
// its header. A consumer printing at a different resolution must scale the
// image accordingly to preserve the physical size.
type Page struct {
image.Image
XDPI, YDPI int
}

// Decode sniffs the stream format and decodes all pages.
func Decode(r io.Reader) ([]image.Image, error) {
pages, err := DecodePages(r)
if err != nil {
return nil, err
}
return images(pages), nil
}

// DecodePages sniffs the stream format and decodes all pages with their
// declared resolutions.
func DecodePages(r io.Reader) ([]Page, error) {
br := bufio.NewReader(r)
head, err := br.Peek(len(pwgSyncWord) + len(pwgMagic))
if err != nil && len(head) == 0 {
return nil, fmt.Errorf("reading stream header: %w", err)
}
switch Detect(head) {
case FormatPWG:
return decodePWGPages(br)
case FormatURF:
return decodeURFPages(br)
}
return nil, fmt.Errorf("unrecognised raster stream (header % x)", head)
}

func images(pages []Page) []image.Image {
imgs := make([]image.Image, len(pages))
for i, pg := range pages {
imgs[i] = pg.Image
}
return imgs
}

func checkDimensions(width, height int) error {
if width <= 0 || height <= 0 || width > maxDim || height > maxDim || width*height > maxPixels {
return fmt.Errorf("invalid page dimensions %dx%d", width, height)
}
return nil
}

// decodeGrayPage decodes a 1- or 8-bit single-channel page into image.Gray.
// blackOne selects ink semantics (K color space: max value = black) as
// opposed to luminance semantics (sGray: zero = black).
func decodeGrayPage(br *bufio.Reader, width, height, bpp, bytesPerLine int, blackOne bool) (*image.Gray, error) {
img := image.NewGray(image.Rect(0, 0, width, height))
// The RLE blank filler must be white in the page's own semantics.
fill := byte(0xff)
if blackOne {
fill = 0x00
}
err := decodeLines(br, height, bytesPerLine, 1, fill, func(y int, row []byte) {
dst := img.Pix[y*img.Stride : y*img.Stride+width]
switch bpp {
case 1:
for x := 0; x < width; x++ {
bit := row[x/8]>>(7-x%8)&1 == 1
if bit == blackOne {
dst[x] = 0x00 // black
} else {
dst[x] = 0xff // white
}
}
case 8:
copy(dst, row)
if blackOne {
for x := range dst {
dst[x] = 0xff - dst[x]
}
}
}
})
if err != nil {
return nil, err
}
return img, nil
}

// decodeRGBPage decodes a 24-bit chunky RGB page into image.NRGBA.
func decodeRGBPage(br *bufio.Reader, width, height, bytesPerLine int) (*image.NRGBA, error) {
img := image.NewNRGBA(image.Rect(0, 0, width, height))
err := decodeLines(br, height, bytesPerLine, 3, 0xff, func(y int, row []byte) {
for x := 0; x < width; x++ {
img.SetNRGBA(x, y, color.NRGBA{R: row[x*3], G: row[x*3+1], B: row[x*3+2], A: 0xff})
}
})
if err != nil {
return nil, err
}
return img, nil
}
112 changes: 112 additions & 0 deletions cupsraster/fixture_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package cupsraster

import (
"bytes"
"image"
"os"
"testing"
)

// The testdata fixtures were generated on macOS from the same source image
// (black border + black bars on white, 384x320) with:
//
// cupsfilter -i image/png -m image/pwg-raster -p ippsrv/ppd/LX-D02.ppd -o Resolution=203dpi fixture.png > doc.pwg
// cupsfilter -i image/png -m image/urf -p ippsrv/ppd/LX-D02.ppd -o Resolution=203dpi fixture.png > doc.urf
//
// Decoding both must yield the same page with the same polarity: black
// content black, white background white — PWG black_1 (K space, bit 1 =
// black) and URF mono (sGray, bit 0 = black) use opposite bit semantics for
// identical content.

func loadFixture(t *testing.T, name string, want Format) image.Image {
t.Helper()
data, err := os.ReadFile("testdata/" + name)
if err != nil {
t.Fatal(err)
}
if got := Detect(data); got != want {
t.Fatalf("Detect(%s) = %v, want %v", name, got, want)
}
pages, err := Decode(bytes.NewReader(data))
if err != nil {
t.Fatalf("Decode(%s): %v", name, err)
}
if len(pages) != 1 {
t.Fatalf("%s: got %d pages, want 1", name, len(pages))
}
return pages[0]
}

// blackFraction returns the fraction of pixels darker than mid-gray.
func blackFraction(img image.Image) float64 {
b := img.Bounds()
var black, total int
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
r, g, bb, _ := img.At(x, y).RGBA()
if (r+g+bb)/3 < 0x8000 {
black++
}
total++
}
}
return float64(black) / float64(total)
}

func TestFixtures_PolarityAndConsistency(t *testing.T) {
pwg := loadFixture(t, "doc.pwg", FormatPWG)
urf := loadFixture(t, "doc.urf", FormatURF)

// the macOS cupsfilter fixtures are 100dpi (it ignores -o Resolution);
// the declared resolution must be surfaced so the printer can rescale.
for _, name := range []string{"doc.pwg", "doc.urf"} {
data, err := os.ReadFile("testdata/" + name)
if err != nil {
t.Fatal(err)
}
pages, err := DecodePages(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
if pages[0].XDPI != 100 || pages[0].YDPI != 100 {
t.Errorf("%s: declared resolution %dx%d, want 100x100", name, pages[0].XDPI, pages[0].YDPI)
}
}

if pwg.Bounds() != urf.Bounds() {
t.Fatalf("bounds differ: pwg %v, urf %v", pwg.Bounds(), urf.Bounds())
}
t.Logf("fixture page: %v", pwg.Bounds())

for _, tt := range []struct {
name string
img image.Image
}{{"pwg", pwg}, {"urf", urf}} {
frac := blackFraction(tt.img)
t.Logf("%s black fraction: %.3f", tt.name, frac)
if frac < 0.02 {
t.Errorf("%s: black fraction %.3f — page looks blank; polarity inverted or content lost", tt.name, frac)
}
if frac > 0.5 {
t.Errorf("%s: black fraction %.3f — page mostly black; polarity likely inverted", tt.name, frac)
}
}

// Both formats must agree pixel-perfectly on 1-bit content rendered
// from the same source through the same PPD.
b := pwg.Bounds()
diff := 0
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
pr, _, _, _ := pwg.At(x, y).RGBA()
ur, _, _, _ := urf.At(x, y).RGBA()
if (pr < 0x8000) != (ur < 0x8000) {
diff++
}
}
}
total := b.Dx() * b.Dy()
if frac := float64(diff) / float64(total); frac > 0.01 {
t.Errorf("pwg and urf pages disagree on %.2f%% of pixels — polarity mismatch between decoders", frac*100)
}
}
Loading