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
29 changes: 29 additions & 0 deletions CREDITS.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
cmd/mfp-test/cupsraster
Source: github.com/rusq/thermoprint/cupsraster
Author: github.com/rusq
License: MIT

MIT License

Copyright (c) 2025 github.com/rusq

Protocol reverse engineering based on https://github.com/big-vl/catcombo,
which is (c) 2025 big-vl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
164 changes: 164 additions & 0 deletions cmd/mfp-test/cupsraster/cupsraster.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// 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
//
// This package is derived from github.com/rusq/thermoprint/cupsraster,
// which is copyright (c) 2025 github.com/rusq, MIT License.
// See CREDITS.txt at the root of this repository.
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 := 0; x < len(dst); x++ {
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
}
146 changes: 146 additions & 0 deletions cmd/mfp-test/cupsraster/pwg.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
package cupsraster

import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"image"
"io"
)

// PWG Raster stream layout (PWG 5102.4): a 4-byte synchronisation word
// "RaS2", then for each page a 1796-byte big-endian header followed by
// RLE-compressed page data.

const (
pwgSyncWord = "RaS2"
pwgMagic = "PwgRaster\x00"
pwgHeaderSize = 1796
)

// Header field byte offsets (PWG 5102.4 §4.3, empirically verified against
// macOS cupsfilter output).
const (
pwgOffHWResolutionX = 276
pwgOffHWResolutionY = 280
pwgOffWidth = 372
pwgOffHeight = 376
pwgOffBitsPerColor = 384
pwgOffBitsPerPixel = 388
pwgOffBytesPerLine = 392
pwgOffColorOrder = 396
pwgOffColorSpace = 400
)

// PWG cupsColorSpace values (subset the decoder understands).
const (
pwgCSBlack = 3 // K, ink semantics: 1 = black
pwgCSSGray = 18 // sGray, luminance semantics: 0 = black
pwgCSSRGB = 19 // sRGB
pwgCSAdobeRGB = 20 // AdobeRGB, treated as sRGB
)

type pwgHeader struct {
Width, Height int
BitsPerColor, BitsPerPixel int
BytesPerLine int
ColorOrder int
ColorSpace int
XRes, YRes int
}

func parsePWGHeader(buf []byte) (pwgHeader, error) {
u32 := func(off int) int {
return int(binary.BigEndian.Uint32(buf[off : off+4]))
}
h := pwgHeader{
Width: u32(pwgOffWidth),
Height: u32(pwgOffHeight),
BitsPerColor: u32(pwgOffBitsPerColor),
BitsPerPixel: u32(pwgOffBitsPerPixel),
BytesPerLine: u32(pwgOffBytesPerLine),
ColorOrder: u32(pwgOffColorOrder),
ColorSpace: u32(pwgOffColorSpace),
XRes: u32(pwgOffHWResolutionX),
YRes: u32(pwgOffHWResolutionY),
}
if err := checkDimensions(h.Width, h.Height); err != nil {
return h, err
}
if h.ColorOrder != 0 {
return h, fmt.Errorf("unsupported color order %d (only chunky is valid)", h.ColorOrder)
}
switch h.ColorSpace {
case pwgCSBlack, pwgCSSGray:
if h.BitsPerPixel != 1 && h.BitsPerPixel != 8 {
return h, fmt.Errorf("unsupported bits per pixel %d for color space %d", h.BitsPerPixel, h.ColorSpace)
}
case pwgCSSRGB, pwgCSAdobeRGB:
if h.BitsPerPixel != 24 {
return h, fmt.Errorf("unsupported bits per pixel %d for color space %d", h.BitsPerPixel, h.ColorSpace)
}
default:
return h, fmt.Errorf("unsupported color space %d", h.ColorSpace)
}
if want := (h.Width*h.BitsPerPixel + 7) / 8; h.BytesPerLine != want {
return h, fmt.Errorf("bytes per line %d inconsistent with width %d at %d bpp (want %d)", h.BytesPerLine, h.Width, h.BitsPerPixel, want)
}
return h, nil
}

// DecodePWG decodes a PWG Raster stream into one image per page.
func DecodePWG(r io.Reader) ([]image.Image, error) {
pages, err := decodePWGPages(bufio.NewReader(r))
if err != nil {
return nil, err
}
return images(pages), nil
}

func decodePWGPages(br *bufio.Reader) ([]Page, error) {
sync := make([]byte, len(pwgSyncWord))
if _, err := io.ReadFull(br, sync); err != nil {
return nil, fmt.Errorf("reading sync word: %w", err)
}
if string(sync) != pwgSyncWord {
return nil, fmt.Errorf("not a PWG raster stream: sync word %q", sync)
}
var pages []Page
hdr := make([]byte, pwgHeaderSize)
for page := 1; ; page++ {
if _, err := io.ReadFull(br, hdr); err != nil {
if err == io.EOF && page > 1 {
break // clean end of stream
}
return nil, fmt.Errorf("page %d: reading header: %w", page, err)
}
if string(hdr[:len(pwgMagic)]) != pwgMagic {
return nil, fmt.Errorf("page %d: header does not start with %q", page, pwgMagic[:len(pwgMagic)-1])
}
h, err := parsePWGHeader(hdr)
if err != nil {
return nil, fmt.Errorf("page %d: %w", page, err)
}
img, err := decodePWGPage(br, h)
if err != nil {
return nil, fmt.Errorf("page %d: %w", page, err)
}
pages = append(pages, Page{Image: img, XDPI: h.XRes, YDPI: h.YRes})
}
if len(pages) == 0 {
return nil, errors.New("no pages in PWG raster stream")
}
return pages, nil
}

func decodePWGPage(br *bufio.Reader, h pwgHeader) (image.Image, error) {
blackOne := h.ColorSpace == pwgCSBlack
switch h.BitsPerPixel {
case 1, 8:
return decodeGrayPage(br, h.Width, h.Height, h.BitsPerPixel, h.BytesPerLine, blackOne)
case 24:
return decodeRGBPage(br, h.Width, h.Height, h.BytesPerLine)
}
panic("unreachable: bpp validated in parsePWGHeader")
}
Loading