Browse Source

Add dng render support

Toby Chui 1 day ago
parent
commit
d49032c49e

+ 206 - 0
src/mod/filesystem/metadata/dngrender/colour.go

@@ -0,0 +1,206 @@
+package dngrender
+
+import "math"
+
+/*
+	Colour and tone
+
+	The camera colour matrix (XYZ to camera) is turned into a camera to linear
+	sRGB matrix whose rows sum to one, so a white balanced grey stays grey (the
+	method of dcraw). Brightness is then raised until the brightest 1% of the
+	picture reaches white, and a gentle contrast curve is applied: a straight
+	linear to sRGB conversion of raw data looks flat and dark.
+*/
+
+// matrix is a 3x3 matrix
+type matrix [3][3]float64
+
+// colourSettings is what turns camera values into sRGB
+type colourSettings struct {
+	multipliers [3]float64 // white balance gain of each camera colour
+	toSRGB      matrix     // white balanced camera values to linear sRGB
+	exposure    float64    // BaselineExposure as a gain
+}
+
+// Linear sRGB to XYZ (D65)
+var sRGBToXYZ = matrix{
+	{0.4124564, 0.3575761, 0.1804375},
+	{0.2126729, 0.7151522, 0.0721750},
+	{0.0193339, 0.1191920, 0.9503041},
+}
+
+var identity = matrix{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
+
+const illuminantD65 = 21
+
+func (a matrix) multiply(b matrix) matrix {
+	var out matrix
+	for i := 0; i < 3; i++ {
+		for j := 0; j < 3; j++ {
+			out[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] + a[i][2]*b[2][j]
+		}
+	}
+	return out
+}
+
+func (a matrix) inverse() (matrix, bool) {
+	var out matrix
+	for i := 0; i < 3; i++ {
+		for j := 0; j < 3; j++ {
+			r1, r2 := (j+1)%3, (j+2)%3
+			c1, c2 := (i+1)%3, (i+2)%3
+			out[i][j] = a[r1][c1]*a[r2][c2] - a[r1][c2]*a[r2][c1]
+		}
+	}
+	det := a[0][0]*out[0][0] + a[0][1]*out[1][0] + a[0][2]*out[2][0]
+	if math.Abs(det) < 1e-9 {
+		return identity, false
+	}
+	for i := range out {
+		for j := range out[i] {
+			out[i][j] /= det
+		}
+	}
+	return out, true
+}
+
+// boundedValues reports whether every value is within -limit..limit
+func boundedValues(values []float64, limit float64) bool {
+	for _, v := range values {
+		if !(math.Abs(v) <= limit) {
+			return false
+		}
+	}
+	return true
+}
+
+func (a matrix) bounded(limit float64) bool {
+	return boundedValues(a[0][:], limit) && boundedValues(a[1][:], limit) && boundedValues(a[2][:], limit)
+}
+
+// tableIndex clamps a value to 0..last, taking anything not positive (also
+// NaN) as 0
+func tableIndex(v float32, last int) int {
+	if !(v > 0) {
+		return 0
+	}
+	if v >= float32(last) {
+		return last
+	}
+	return int(v)
+}
+
+// readColourSettings reads the white balance and colour matrix of IFD0
+func readColourSettings(t *tiffFile, dir directory) colourSettings {
+	settings := colourSettings{multipliers: [3]float64{1, 1, 1}, toSRGB: identity, exposure: 1}
+
+	//The daylight calibration is the one closest to most photos
+	tag := uint16(tagColorMatrix1)
+	if _, ok := dir[tagColorMatrix2]; ok && t.uintValue(dir, tagCalibrationIllum1, 0) != illuminantD65 &&
+		t.uintValue(dir, tagCalibrationIllum2, 0) == illuminantD65 {
+		tag = tagColorMatrix2
+	}
+
+	var neutral []float64
+	if n := t.numbers(dir[tagAsShotNeutral], 3); len(n) == 3 && n[0] > 0 && n[1] > 0 && n[2] > 0 {
+		neutral = n
+	}
+
+	if values := t.numbers(dir[tag], 9); len(values) == 9 && boundedValues(values, 100) {
+		var xyzToCamera matrix
+		for i, v := range values {
+			xyzToCamera[i/3][i%3] = v
+		}
+		if xy := t.numbers(dir[tagAsShotWhiteXY], 2); neutral == nil && len(xy) == 2 && xy[1] > 0 {
+			white := [3]float64{xy[0] / xy[1], 1, (1 - xy[0] - xy[1]) / xy[1]}
+			n := make([]float64, 3)
+			for i := range n {
+				n[i] = xyzToCamera[i][0]*white[0] + xyzToCamera[i][1]*white[1] + xyzToCamera[i][2]*white[2]
+			}
+			if n[0] > 0 && n[1] > 0 && n[2] > 0 {
+				neutral = n
+			}
+		}
+
+		sRGBToCamera := xyzToCamera.multiply(sRGBToXYZ)
+		var daylight [3]float64
+		usable := true
+		for i := range sRGBToCamera {
+			sum := sRGBToCamera[i][0] + sRGBToCamera[i][1] + sRGBToCamera[i][2]
+			if sum < 1e-6 {
+				usable = false
+				break
+			}
+			daylight[i] = sum
+			for j := range sRGBToCamera[i] {
+				sRGBToCamera[i][j] /= sum
+			}
+		}
+		if usable {
+			//A nearly singular matrix inverts into nonsense, keep identity
+			if inverse, ok := sRGBToCamera.inverse(); ok && inverse.bounded(100) {
+				settings.toSRGB = inverse
+				if neutral == nil {
+					//No white balance recorded: assume daylight
+					neutral = daylight[:]
+				}
+			}
+		}
+	}
+
+	if neutral != nil {
+		//The smallest gain is 1 so that a clipped sensor stays white
+		largest := math.Max(neutral[0], math.Max(neutral[1], neutral[2]))
+		for i := range settings.multipliers {
+			settings.multipliers[i] = math.Min(largest/neutral[i], 16)
+		}
+	}
+
+	if ev := t.numbers(dir[tagBaselineExposure], 1); len(ev) == 1 {
+		settings.exposure = math.Pow(2, math.Max(-4, math.Min(4, ev[0])))
+	}
+	return settings
+}
+
+// toneSteps is the resolution of the linear to sRGB lookup table
+const toneSteps = 1 << 14
+
+// toneCurve maps linear values (0 to toneSteps) to 8 bit sRGB
+func toneCurve() *[toneSteps + 1]uint8 {
+	const contrast = 0.35
+	var table [toneSteps + 1]uint8
+	for i := range table {
+		v := float64(i) / toneSteps
+		if v <= 0.0031308 {
+			v *= 12.92
+		} else {
+			v = 1.055*math.Pow(v, 1/2.4) - 0.055
+		}
+		//Blend towards an S curve
+		v += contrast * (v*v*(3-2*v) - v)
+		table[i] = uint8(math.Max(0, math.Min(255, v*255+0.5)))
+	}
+	return &table
+}
+
+// autoExposure returns the gain that brings the brightest 1% of the picture to
+// white, between 1 and 4. histogram counts the brightest channel of sampled
+// pixels, its last bin being white.
+func autoExposure(histogram []int) float32 {
+	total := 0
+	for _, n := range histogram {
+		total += n
+	}
+	if total == 0 {
+		return 1
+	}
+	above := 0
+	for i := len(histogram) - 1; i > 0; i-- {
+		above += histogram[i]
+		if above > total/100 {
+			white := float32(i+1) / float32(len(histogram))
+			return max(1, min(4, 1/white))
+		}
+	}
+	return 4
+}

+ 315 - 0
src/mod/filesystem/metadata/dngrender/develop.go

@@ -0,0 +1,315 @@
+package dngrender
+
+import (
+	"errors"
+	"image"
+	"runtime"
+	"sync"
+)
+
+/*
+	Development pipeline
+
+	1. Unpack the mosaic and scale it to 0..1 between black and white level,
+	   apply the lens shading gains and the white balance
+	2. Demosaic: Malvar-He-Cutler at full resolution, or the average of each
+	   block of 2x2 cells for a smaller picture
+	3. Colour matrix, exposure, tone curve and orientation
+	4. At full resolution, smooth the colour noise (noise.go)
+*/
+
+// Develop renders the raw data of a DNG as it is shown, upright.
+//
+// With minShortSide 0 the picture has the full resolution. Otherwise it is
+// scaled down by an even factor, as far as its shorter side stays at least
+// minShortSide pixels, which is much faster. A picture too small to be halved
+// keeps its full resolution.
+func Develop(data []byte, minShortSide int) (image.Image, error) {
+	r, err := parse(data)
+	if err != nil {
+		return nil, err
+	}
+	plane, err := r.loadPlane()
+	if err != nil {
+		return nil, err
+	}
+
+	//Number of Bayer cells averaged along each side of an output pixel
+	cells := 0
+	if minShortSide > 0 {
+		cells = min(r.crop.width, r.crop.height) / 2 / minShortSide
+	}
+	if cells == 0 {
+		return smoothChroma(r.render(r.demosaicRows(plane), r.crop.width, r.crop.height)), nil
+	}
+	width, height := r.crop.width/(2*cells), r.crop.height/(2*cells)
+	return r.render(r.binnedRows(plane, cells, width), width, height), nil
+}
+
+// parallelRows splits the rows 0..height between the processors
+func parallelRows(height int, work func(from, to int)) {
+	workers := min(runtime.GOMAXPROCS(0), height)
+	var wg sync.WaitGroup
+	for i := 0; i < workers; i++ {
+		wg.Add(1)
+		go func(from, to int) {
+			defer wg.Done()
+			work(from, to)
+		}(i*height/workers, (i+1)*height/workers)
+	}
+	wg.Wait()
+}
+
+// planeScale is the value of a white pixel in the plane. White balance gains
+// push values past white, they are clipped there.
+const planeScale = 1<<16 - 1
+
+// loadPlane unpacks the active area of the mosaic into white balanced values
+// between 0 and planeScale
+func (r *rawImage) loadPlane() ([]uint16, error) {
+	data := r.file.data
+
+	//Check every tile before allocating anything
+	rowBytes := (int64(r.tileWidth)*int64(r.bits) + 7) / 8
+	across := (r.width + r.tileWidth - 1) / r.tileWidth
+	for i := range r.offsets {
+		rows := min(r.tileHeight, r.height-(i/across)*r.tileHeight)
+		need := rowBytes * int64(rows)
+		if r.counts[i] < need || need > int64(len(data)) || r.offsets[i] > int64(len(data))-need {
+			return nil, errors.New("DNG raw data is truncated")
+		}
+	}
+
+	width, height := r.active.width, r.active.height
+	plane := make([]uint16, width*height)
+	parallelRows(height, func(from, to int) {
+		stored := make([]uint16, r.width)
+		row := make([]float32, width)
+		for y := from; y < to; y++ {
+			r.readStoredRow(r.active.top+y, stored)
+
+			for x := range row {
+				value := float64(stored[r.active.left+x])
+				if n := len(r.linearization); n > 0 {
+					value = r.linearization[min(int(value), n-1)]
+				}
+				black := r.black[(y%r.blackRows)*r.blackCols+x%r.blackCols]
+				row[x] = float32(max(0, (value-black)/(r.white-black)))
+			}
+			for i := range r.gainMaps {
+				r.gainMaps[i].applyRow(row, y, width, height)
+			}
+
+			out := plane[y*width : (y+1)*width]
+			for x, v := range row {
+				v *= float32(r.colour.multipliers[r.cfa[(y&1)*2+x&1]])
+				out[x] = uint16(max(0, min(1, v))*planeScale + 0.5)
+			}
+		}
+	})
+	return plane, nil
+}
+
+// readStoredRow unpacks row y of the stored mosaic. loadPlane has checked that
+// every tile holds its rows.
+func (r *rawImage) readStoredRow(y int, out []uint16) {
+	data := r.file.data
+	across := (r.width + r.tileWidth - 1) / r.tileWidth
+	rowBytes := (r.tileWidth*r.bits + 7) / 8
+	for column := 0; column < across; column++ {
+		tile := (y/r.tileHeight)*across + column
+		start := int(r.offsets[tile]) + (y%r.tileHeight)*rowBytes
+		src := data[start : start+rowBytes]
+
+		x := column * r.tileWidth
+		dst := out[x:min(x+r.tileWidth, r.width)]
+		switch r.bits {
+		case 16:
+			for i := range dst {
+				dst[i] = r.file.order.Uint16(src[i*2:])
+			}
+		case 8:
+			for i := range dst {
+				dst[i] = uint16(src[i])
+			}
+		default:
+			//Packed samples, most significant bit first
+			var buffer uint32
+			bits, next := 0, 0
+			for i := range dst {
+				for bits < r.bits {
+					buffer = buffer<<8 | uint32(src[next])
+					next++
+					bits += 8
+				}
+				bits -= r.bits
+				dst[i] = uint16(buffer>>bits) & (1<<r.bits - 1)
+			}
+		}
+	}
+}
+
+// rowSource fills rgb (3 values a pixel, 0 to planeScale) with row y of the
+// picture before orientation
+type rowSource func(y int, rgb []float32)
+
+// binnedRows averages blocks of cells x cells Bayer cells into one pixel
+func (r *rawImage) binnedRows(plane []uint16, cells, width int) rowSource {
+	stride := r.active.width
+	block := 2 * cells
+	return func(y int, rgb []float32) {
+		top := r.crop.top + y*block
+		for x := 0; x < width; x++ {
+			left := r.crop.left + x*block
+			var sum [3]uint64
+			var count [3]uint64
+			for by := top; by < top+block; by++ {
+				row := plane[by*stride+left : by*stride+left+block]
+				for i, v := range row {
+					c := r.cfa[(by&1)*2+(left+i)&1]
+					sum[c] += uint64(v)
+					count[c]++
+				}
+			}
+			for c := range sum {
+				rgb[x*3+c] = float32(sum[c]) / float32(count[c])
+			}
+		}
+	}
+}
+
+// reflect keeps a coordinate inside 0..n-1 by mirroring at the edges, which
+// preserves its colour in the mosaic
+func reflect(i, n int) int {
+	if i < 0 {
+		return -i
+	}
+	if i >= n {
+		return 2*n - 2 - i
+	}
+	return i
+}
+
+// demosaicRows rebuilds the two missing colours of every pixel with the
+// gradient corrected filters of Malvar, He and Cutler
+func (r *rawImage) demosaicRows(plane []uint16) rowSource {
+	width, height := r.active.width, r.active.height
+	return func(y int, rgb []float32) {
+		py := r.crop.top + y
+		var lines [5][]uint16
+		for i := range lines {
+			line := reflect(py+i-2, height)
+			lines[i] = plane[line*width : (line+1)*width]
+		}
+
+		for x := 0; x < r.crop.width; x++ {
+			px := r.crop.left + x
+			xm2, xm1, xp1, xp2 := px-2, px-1, px+1, px+2
+			if xm2 < 0 || xp2 >= width {
+				xm2, xm1 = reflect(xm2, width), reflect(xm1, width)
+				xp1, xp2 = reflect(xp1, width), reflect(xp2, width)
+			}
+
+			centre := float32(lines[2][px])
+			horizontal := float32(lines[2][xm1]) + float32(lines[2][xp1])
+			vertical := float32(lines[1][px]) + float32(lines[3][px])
+			diagonal := float32(lines[1][xm1]) + float32(lines[1][xp1]) +
+				float32(lines[3][xm1]) + float32(lines[3][xp1])
+			farHorizontal := float32(lines[2][xm2]) + float32(lines[2][xp2])
+			farVertical := float32(lines[0][px]) + float32(lines[4][px])
+
+			colour := r.cfa[(py&1)*2+px&1]
+			pixel := rgb[x*3 : x*3+3]
+			if colour == 1 {
+				//Green pixel: one other colour is left and right of it, the
+				//other above and below
+				beside := r.cfa[(py&1)*2+(px+1)&1]
+				alongRow := (5*centre + 4*horizontal - diagonal - farHorizontal + 0.5*farVertical) / 8
+				alongColumn := (5*centre + 4*vertical - diagonal - farVertical + 0.5*farHorizontal) / 8
+				pixel[1] = centre
+				pixel[beside] = alongRow
+				pixel[2-beside] = alongColumn
+			} else {
+				pixel[colour] = centre
+				pixel[1] = (4*centre + 2*(horizontal+vertical) - farHorizontal - farVertical) / 8
+				pixel[2-colour] = (6*centre + 2*diagonal - 1.5*(farHorizontal+farVertical)) / 8
+			}
+			for c, v := range pixel {
+				pixel[c] = max(0, min(planeScale, v))
+			}
+		}
+	}
+}
+
+// orient returns where pixel (x, y) of a width x height picture goes, by the
+// EXIF orientation of the file
+func orient(orientation, x, y, width, height int) (int, int) {
+	switch orientation {
+	case 2:
+		return width - 1 - x, y
+	case 3:
+		return width - 1 - x, height - 1 - y
+	case 4:
+		return x, height - 1 - y
+	case 5:
+		return y, x
+	case 6:
+		return height - 1 - y, x
+	case 7:
+		return height - 1 - y, width - 1 - x
+	case 8:
+		return y, width - 1 - x
+	}
+	return x, y
+}
+
+// render converts the camera values of rows into an upright sRGB picture
+func (r *rawImage) render(rows rowSource, width, height int) *image.RGBA {
+	var m [3][3]float32
+	for i := range m {
+		for j := range m[i] {
+			m[i][j] = float32(r.colour.toSRGB[i][j] / planeScale * r.colour.exposure)
+		}
+	}
+	convert := func(p []float32) (float32, float32, float32) {
+		return m[0][0]*p[0] + m[0][1]*p[1] + m[0][2]*p[2],
+			m[1][0]*p[0] + m[1][1]*p[1] + m[1][2]*p[2],
+			m[2][0]*p[0] + m[2][1]*p[1] + m[2][2]*p[2]
+	}
+
+	//Measure the brightness on a sample of rows and pixels
+	histogram := make([]int, 1024)
+	sample := make([]float32, width*3)
+	for y := 0; y < height; y += max(1, height/256) {
+		rows(y, sample)
+		for x := 0; x < width; x += max(1, width/256) {
+			red, green, blue := convert(sample[x*3:])
+			last := len(histogram) - 1
+			histogram[tableIndex(max(red, green, blue)*float32(last), last)]++
+		}
+	}
+	gain := autoExposure(histogram) * toneSteps
+	table := toneCurve()
+
+	outWidth, outHeight := width, height
+	if r.orientation >= 5 {
+		outWidth, outHeight = height, width
+	}
+	out := image.NewRGBA(image.Rect(0, 0, outWidth, outHeight))
+	parallelRows(height, func(from, to int) {
+		rgb := make([]float32, width*3)
+		for y := from; y < to; y++ {
+			rows(y, rgb)
+			for x := 0; x < width; x++ {
+				red, green, blue := convert(rgb[x*3:])
+				ox, oy := orient(r.orientation, x, y, width, height)
+				pixel := out.Pix[out.PixOffset(ox, oy):][:4]
+				pixel[0] = table[tableIndex(red*gain, toneSteps)]
+				pixel[1] = table[tableIndex(green*gain, toneSteps)]
+				pixel[2] = table[tableIndex(blue*gain, toneSteps)]
+				pixel[3] = 255
+			}
+		}
+	})
+	return out
+}

+ 279 - 0
src/mod/filesystem/metadata/dngrender/dng.go

@@ -0,0 +1,279 @@
+// Package dngrender develops the raw sensor data of a DNG photo into a normal
+// picture, in pure Go.
+//
+// Most DNG files carry a JPEG preview that can be shown as it is. Phone apps
+// built on Android's DngCreator often write none, only the Bayer mosaic of the
+// sensor, so it has to be developed here.
+//
+// Supported: uncompressed Bayer (2x2 CFA) data of 8 to 16 bits, in strips or
+// tiles. Compressed raw data returns ErrUnsupported. The result is meant for
+// viewing: black and white level, lens shading (GainMap), white balance, the
+// camera colour matrix and a tone curve are applied and, at full resolution,
+// colour noise is smoothed. Lens distortion is not corrected.
+//
+// The input is an untrusted file: every size and offset in it is checked
+// before use, and memory is only allocated for data that is really there.
+package dngrender
+
+import (
+	"errors"
+	"fmt"
+)
+
+// ErrUnsupported is returned for DNG files this package cannot develop
+var ErrUnsupported = errors.New("unsupported DNG")
+
+const (
+	photometricCFA = 32803
+
+	// Largest sensor that is developed
+	maxDimension = 1 << 15
+	maxPixels    = 200 << 20
+)
+
+// rectangle is a half open area of the image, in pixels
+type rectangle struct {
+	left, top, width, height int
+}
+
+// rawImage is everything needed to develop the raw data of one file
+type rawImage struct {
+	file *tiffFile
+
+	width, height int // stored size of the mosaic
+	bits          int
+
+	//Where the stored data lies: strips are tiles as wide as the image
+	tileWidth, tileHeight int
+	offsets, counts       []int64
+
+	active rectangle // area holding picture data, in stored coordinates
+	crop   rectangle // area to show, relative to active
+	cfa    [4]int    // colour (0 red, 1 green, 2 blue) of each 2x2 position
+
+	linearization []float64
+	blackRows     int
+	blackCols     int
+	black         []float64
+	white         float64
+
+	gainMaps []gainMap
+
+	orientation int
+	colour      colourSettings
+}
+
+// Size returns the width and height of the picture Develop renders at full
+// resolution, as it is shown (after the orientation of the file).
+func Size(data []byte) (int, int, error) {
+	r, err := parse(data)
+	if err != nil {
+		return 0, 0, err
+	}
+	if r.orientation >= 5 {
+		return r.crop.height, r.crop.width, nil
+	}
+	return r.crop.width, r.crop.height, nil
+}
+
+// parse finds the raw mosaic of a DNG and reads how to develop it
+func parse(data []byte) (*rawImage, error) {
+	t, directories, err := readDirectories(data)
+	if err != nil {
+		return nil, err
+	}
+	first := directories[0]
+	if _, ok := first[tagDNGVersion]; !ok {
+		return nil, errors.New("not a DNG file")
+	}
+
+	//The raw mosaic is the largest CFA picture of the file
+	var dir directory
+	var best int64
+	for _, d := range directories {
+		if t.uintValue(d, tagPhotometric, 0) != photometricCFA {
+			continue
+		}
+		area := t.uintValue(d, tagImageWidth, 0) * t.uintValue(d, tagImageLength, 0)
+		if area > best {
+			dir, best = d, area
+		}
+	}
+	if dir == nil {
+		return nil, fmt.Errorf("%w: no Bayer raw data", ErrUnsupported)
+	}
+
+	r := &rawImage{file: t}
+	if err := r.readLayout(dir); err != nil {
+		return nil, err
+	}
+	r.readGeometry(dir)
+	if r.crop.width < 4 || r.crop.height < 4 {
+		return nil, errors.New("DNG picture area too small")
+	}
+	if err := r.readCFA(dir); err != nil {
+		return nil, err
+	}
+	if err := r.readLevels(dir); err != nil {
+		return nil, err
+	}
+	if list, ok := dir[tagOpcodeList2]; ok {
+		r.gainMaps = parseGainMaps(list.value)
+	}
+
+	r.orientation = int(t.uintValue(first, tagOrientation, 1))
+	if r.orientation < 1 || r.orientation > 8 {
+		r.orientation = 1
+	}
+	r.colour = readColourSettings(t, first)
+	return r, nil
+}
+
+// readLayout reads the size of the mosaic and where its bytes are
+func (r *rawImage) readLayout(dir directory) error {
+	t := r.file
+	width := t.uintValue(dir, tagImageWidth, 0)
+	height := t.uintValue(dir, tagImageLength, 0)
+	if width < 4 || height < 4 || width > maxDimension || height > maxDimension || width*height > maxPixels {
+		return fmt.Errorf("%w: raw size %dx%d", ErrUnsupported, width, height)
+	}
+	if c := t.uintValue(dir, tagCompression, 1); c != 1 {
+		return fmt.Errorf("%w: compression %d", ErrUnsupported, c)
+	}
+	if s := t.uintValue(dir, tagSamplesPerPixel, 1); s != 1 {
+		return fmt.Errorf("%w: %d samples per pixel", ErrUnsupported, s)
+	}
+	bits := t.uintValue(dir, tagBitsPerSample, 0)
+	if bits < 8 || bits > 16 {
+		return fmt.Errorf("%w: %d bits per sample", ErrUnsupported, bits)
+	}
+
+	//An uncompressed mosaic cannot be larger than the file holding it
+	if width*height*bits/8 > int64(len(t.data)) {
+		return errors.New("DNG raw data is truncated")
+	}
+	r.width, r.height, r.bits = int(width), int(height), int(bits)
+
+	offsetTag, countTag := uint16(tagStripOffsets), uint16(tagStripByteCounts)
+	tileWidth, tileHeight := width, t.uintValue(dir, tagRowsPerStrip, height)
+	if _, tiled := dir[tagTileOffsets]; tiled {
+		offsetTag, countTag = tagTileOffsets, tagTileByteCounts
+		tileWidth = t.uintValue(dir, tagTileWidth, 0)
+		tileHeight = t.uintValue(dir, tagTileLength, 0)
+	}
+	if tileHeight > height && offsetTag == tagStripOffsets {
+		tileHeight = height
+	}
+	if tileWidth < 1 || tileHeight < 1 || tileWidth > maxDimension || tileHeight > maxDimension {
+		return errors.New("DNG has an invalid tile size")
+	}
+	r.tileWidth, r.tileHeight = int(tileWidth), int(tileHeight)
+
+	across := (r.width + r.tileWidth - 1) / r.tileWidth
+	down := (r.height + r.tileHeight - 1) / r.tileHeight
+	total := int64(across) * int64(down)
+	if total > int64(dir[offsetTag].count) || total > int64(dir[countTag].count) {
+		return errors.New("DNG raw data is incomplete")
+	}
+	r.offsets = t.uints(dir[offsetTag], int(total))
+	r.counts = t.uints(dir[countTag], int(total))
+	if int64(len(r.offsets)) != total || int64(len(r.counts)) != total {
+		return errors.New("DNG raw data is incomplete")
+	}
+	return nil
+}
+
+// readGeometry reads the active area and the default crop inside it. Values
+// that do not fit the image are ignored.
+func (r *rawImage) readGeometry(dir directory) {
+	t := r.file
+	r.active = rectangle{0, 0, r.width, r.height}
+	if a := t.uints(dir[tagActiveArea], 4); len(a) == 4 {
+		top, left, bottom, right := a[0], a[1], a[2], a[3]
+		if top < bottom && left < right && bottom <= int64(r.height) && right <= int64(r.width) {
+			r.active = rectangle{int(left), int(top), int(right - left), int(bottom - top)}
+		}
+	}
+
+	r.crop = rectangle{0, 0, r.active.width, r.active.height}
+	origin := t.numbers(dir[tagDefaultCropOrigin], 2)
+	size := t.numbers(dir[tagDefaultCropSize], 2)
+	if len(origin) == 2 && len(size) == 2 {
+		inside := func(start, length float64, limit int) bool {
+			return start >= 0 && length >= 1 && start <= float64(limit) && length <= float64(limit)-start
+		}
+		if inside(origin[0], size[0], r.active.width) && inside(origin[1], size[1], r.active.height) {
+			r.crop = rectangle{int(origin[0]), int(origin[1]), int(size[0]), int(size[1])}
+		}
+	}
+}
+
+// readCFA reads which colour each pixel of the 2x2 mosaic cell carries
+func (r *rawImage) readCFA(dir directory) error {
+	t := r.file
+	repeat := t.uints(dir[tagCFARepeatPatternDim], 2)
+	pattern := t.uints(dir[tagCFAPattern], 4)
+	if len(repeat) != 2 || repeat[0] != 2 || repeat[1] != 2 || len(pattern) != 4 {
+		return fmt.Errorf("%w: not a 2x2 colour filter", ErrUnsupported)
+	}
+	if layout := t.uintValue(dir, tagCFALayout, 1); layout != 1 {
+		return fmt.Errorf("%w: colour filter layout %d", ErrUnsupported, layout)
+	}
+
+	//CFAPlaneColor maps the plane numbers used by the colour matrices to
+	//colours; only the usual red, green, blue order is handled
+	if planes := t.uints(dir[tagCFAPlaneColor], 4); len(planes) > 0 {
+		if len(planes) != 3 || planes[0] != 0 || planes[1] != 1 || planes[2] != 2 {
+			return fmt.Errorf("%w: colour filter is not RGB", ErrUnsupported)
+		}
+	}
+
+	var found [3]int
+	for i, c := range pattern {
+		if c > 2 {
+			return fmt.Errorf("%w: colour filter is not RGB", ErrUnsupported)
+		}
+		r.cfa[i] = int(c)
+		found[c]++
+	}
+	//A Bayer cell has red and blue once and green on one of its diagonals
+	if found[0] != 1 || found[1] != 2 || found[2] != 1 || (r.cfa[0] == 1) != (r.cfa[3] == 1) {
+		return fmt.Errorf("%w: colour filter is not Bayer", ErrUnsupported)
+	}
+	return nil
+}
+
+// readLevels reads the values the sensor stores for black and for white
+func (r *rawImage) readLevels(dir directory) error {
+	t := r.file
+	//Levels and table values beyond any sensor would overflow the arithmetic
+	const maxLevel = 1 << 24
+	r.white = float64(int64(1)<<r.bits - 1)
+	if w := t.numbers(dir[tagWhiteLevel], 1); len(w) == 1 && w[0] > 0 && w[0] <= maxLevel {
+		r.white = w[0]
+	}
+
+	r.blackRows, r.blackCols = 1, 1
+	if dim := t.uints(dir[tagBlackLevelRepeatDim], 2); len(dim) == 2 {
+		if dim[0] < 1 || dim[1] < 1 || dim[0] > 16 || dim[1] > 16 {
+			return errors.New("DNG has an invalid black level pattern")
+		}
+		r.blackRows, r.blackCols = int(dim[0]), int(dim[1])
+	}
+	r.black = make([]float64, r.blackRows*r.blackCols)
+	levels := t.numbers(dir[tagBlackLevel], len(r.black))
+	for i := range r.black {
+		if len(levels) > 0 {
+			r.black[i] = levels[i%len(levels)]
+		}
+		if r.black[i] >= r.white || r.black[i] < -maxLevel {
+			return errors.New("DNG black level is not below its white level")
+		}
+	}
+
+	r.linearization = t.numbers(dir[tagLinearizationTable], 1<<16)
+	if !boundedValues(r.linearization, maxLevel) {
+		return errors.New("DNG has an invalid linearization table")
+	}
+	return nil
+}

+ 531 - 0
src/mod/filesystem/metadata/dngrender/dng_test.go

@@ -0,0 +1,531 @@
+package dngrender
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"image"
+	"image/color"
+	"math"
+	"sort"
+	"testing"
+)
+
+// testTag is one directory entry of a DNG built for a test
+type testTag struct {
+	fieldType uint16
+	count     int
+	value     []byte
+}
+
+// testDNG describes a DNG to build. All tags go in IFD0, as Android writes it.
+type testDNG struct {
+	order         binary.ByteOrder
+	width, height int
+	bits          int
+	tile          int     // side of square tiles, 0 for one strip
+	cfa           [4]byte // colour of each position of the 2x2 cell
+	// stored is the value of the sensor at (x, y), which has this colour
+	stored func(x, y, colour int) uint16
+	tags   map[uint16]testTag // added to, or replacing, the standard ones
+}
+
+func (d testDNG) shorts(values ...uint16) testTag {
+	b := make([]byte, 2*len(values))
+	for i, v := range values {
+		d.order.PutUint16(b[i*2:], v)
+	}
+	return testTag{3, len(values), b}
+}
+
+func (d testDNG) longs(values ...uint32) testTag {
+	b := make([]byte, 4*len(values))
+	for i, v := range values {
+		d.order.PutUint32(b[i*4:], v)
+	}
+	return testTag{4, len(values), b}
+}
+
+// signed rationals with a denominator of 100000
+func (d testDNG) rationals(values ...float64) testTag {
+	b := make([]byte, 8*len(values))
+	for i, v := range values {
+		d.order.PutUint32(b[i*8:], uint32(int32(math.Round(v*100000))))
+		d.order.PutUint32(b[i*8+4:], 100000)
+	}
+	return testTag{10, len(values), b}
+}
+
+// block packs the sensor values of one strip or tile
+func (d testDNG) block(left, top, width, height int) []byte {
+	var out bytes.Buffer
+	for y := top; y < top+height; y++ {
+		var buffer uint32
+		bits := 0
+		for x := left; x < left+width; x++ {
+			var v uint16
+			if x < d.width && y < d.height {
+				v = d.stored(x, y, int(d.cfa[(y&1)*2+x&1]))
+			}
+			switch d.bits {
+			case 16:
+				var b [2]byte
+				d.order.PutUint16(b[:], v)
+				out.Write(b[:])
+			case 8:
+				out.WriteByte(byte(v))
+			default:
+				buffer = buffer<<d.bits | uint32(v)
+				bits += d.bits
+				for bits >= 8 {
+					bits -= 8
+					out.WriteByte(byte(buffer >> bits))
+				}
+			}
+		}
+		if bits > 0 {
+			out.WriteByte(byte(buffer << (8 - bits)))
+		}
+	}
+	return out.Bytes()
+}
+
+func (d testDNG) build() []byte {
+	out := []byte("II*\x00\x00\x00\x00\x00")
+	if d.order == binary.BigEndian {
+		out = []byte("MM\x00*\x00\x00\x00\x00")
+	}
+
+	var offsets, counts []uint32
+	add := func(block []byte) {
+		offsets = append(offsets, uint32(len(out)))
+		counts = append(counts, uint32(len(block)))
+		out = append(out, block...)
+	}
+	tags := map[uint16]testTag{
+		tagImageWidth:          d.longs(uint32(d.width)),
+		tagImageLength:         d.longs(uint32(d.height)),
+		tagBitsPerSample:       d.shorts(uint16(d.bits)),
+		tagCompression:         d.shorts(1),
+		tagPhotometric:         d.shorts(photometricCFA),
+		tagCFARepeatPatternDim: d.shorts(2, 2),
+		tagCFAPattern:          {1, 4, d.cfa[:]},
+		tagDNGVersion:          {1, 4, []byte{1, 4, 0, 0}},
+	}
+	if d.tile > 0 {
+		for top := 0; top < d.height; top += d.tile {
+			for left := 0; left < d.width; left += d.tile {
+				add(d.block(left, top, d.tile, d.tile))
+			}
+		}
+		tags[tagTileWidth] = d.longs(uint32(d.tile))
+		tags[tagTileLength] = d.longs(uint32(d.tile))
+		tags[tagTileOffsets] = d.longs(offsets...)
+		tags[tagTileByteCounts] = d.longs(counts...)
+	} else {
+		add(d.block(0, 0, d.width, d.height))
+		tags[tagStripOffsets] = d.longs(offsets...)
+		tags[tagStripByteCounts] = d.longs(counts...)
+	}
+	for id, tag := range d.tags {
+		tags[id] = tag
+	}
+
+	ids := make([]int, 0, len(tags))
+	for id := range tags {
+		ids = append(ids, int(id))
+	}
+	sort.Ints(ids)
+
+	var entries []byte
+	for _, id := range ids {
+		tag := tags[uint16(id)]
+		entry := make([]byte, 12)
+		d.order.PutUint16(entry, uint16(id))
+		d.order.PutUint16(entry[2:], tag.fieldType)
+		d.order.PutUint32(entry[4:], uint32(tag.count))
+		if len(tag.value) <= 4 {
+			copy(entry[8:], tag.value)
+		} else {
+			d.order.PutUint32(entry[8:], uint32(len(out)))
+			out = append(out, tag.value...)
+		}
+		entries = append(entries, entry...)
+	}
+	d.order.PutUint32(out[4:], uint32(len(out)))
+	var count [2]byte
+	d.order.PutUint16(count[:], uint16(len(ids)))
+	out = append(out, count[:]...)
+	out = append(out, entries...)
+	return append(out, 0, 0, 0, 0)
+}
+
+var rggb = [4]byte{0, 1, 1, 2}
+
+// flat is a DNG whose whole sensor sees one colour, given as fractions of the
+// white level for red, green and blue
+func flat(width, height, bits int, colour [3]float64) testDNG {
+	white := float64(int(1)<<bits - 1)
+	return testDNG{
+		order: binary.LittleEndian, width: width, height: height, bits: bits, cfa: rggb,
+		stored: func(x, y, c int) uint16 { return uint16(math.Round(colour[c] * white)) },
+		tags:   map[uint16]testTag{},
+	}
+}
+
+// tone is the 8 bit value a linear value (0 to 1) is shown as
+func tone(v float64) int {
+	return int(toneCurve()[tableIndex(float32(v)*toneSteps, toneSteps)])
+}
+
+func rgbAt(img image.Image, x, y int) [3]int {
+	c := color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA)
+	return [3]int{int(c.R), int(c.G), int(c.B)}
+}
+
+// wantColour checks every pixel of a picture, allowing for rounding
+func wantColour(t *testing.T, img image.Image, want [3]int) {
+	t.Helper()
+	b := img.Bounds()
+	for y := b.Min.Y; y < b.Max.Y; y++ {
+		for x := b.Min.X; x < b.Max.X; x++ {
+			got := rgbAt(img, x, y)
+			for c := range got {
+				if got[c] < want[c]-4 || got[c] > want[c]+4 {
+					t.Fatalf("pixel %d,%d = %v, want about %v", x, y, got, want)
+				}
+			}
+		}
+	}
+}
+
+func develop(t *testing.T, data []byte, minShortSide int) image.Image {
+	t.Helper()
+	img, err := Develop(data, minShortSide)
+	if err != nil {
+		t.Fatalf("Develop: %v", err)
+	}
+	return img
+}
+
+func TestDevelopLayouts(t *testing.T) {
+	colour := [3]float64{1, 0.5, 0.25}
+	want := [3]int{tone(1), tone(0.5), tone(0.25)}
+	patterns := map[string][4]byte{
+		"RGGB": {0, 1, 1, 2}, "BGGR": {2, 1, 1, 0}, "GRBG": {1, 0, 2, 1}, "GBRG": {1, 2, 0, 1},
+	}
+	for name, cfa := range patterns {
+		for _, bits := range []int{8, 10, 12, 14, 16} {
+			for _, tile := range []int{0, 8} {
+				for _, order := range []binary.ByteOrder{binary.LittleEndian, binary.BigEndian} {
+					d := flat(20, 14, bits, colour)
+					d.cfa, d.tile, d.order = cfa, tile, order
+					img := develop(t, d.build(), 0)
+					if img.Bounds().Dx() != 20 || img.Bounds().Dy() != 14 {
+						t.Fatalf("%s %d bit tile %d: size %v", name, bits, tile, img.Bounds())
+					}
+					wantColour(t, img, want)
+					if t.Failed() {
+						t.Fatalf("%s %d bit tile %d %v", name, bits, tile, order)
+					}
+				}
+			}
+		}
+	}
+}
+
+func TestDevelopSizes(t *testing.T) {
+	data := flat(64, 48, 12, [3]float64{1, 0.5, 0.25}).build()
+	tests := []struct {
+		name          string
+		minShortSide  int
+		width, height int
+	}{
+		{"full resolution", 0, 64, 48},
+		{"one cell per pixel", 24, 32, 24},
+		{"largest factor keeping the short side", 12, 16, 12},
+		{"factor rounds down", 11, 16, 12},
+		{"too small to halve", 40, 64, 48},
+	}
+	for _, tc := range tests {
+		img := develop(t, data, tc.minShortSide)
+		if img.Bounds().Dx() != tc.width || img.Bounds().Dy() != tc.height {
+			t.Errorf("%s: size = %v, want %dx%d", tc.name, img.Bounds(), tc.width, tc.height)
+		}
+		wantColour(t, img, [3]int{tone(1), tone(0.5), tone(0.25)})
+	}
+}
+
+func TestDevelopColourAndLevels(t *testing.T) {
+	grey := func(v float64) [3]int { return [3]int{tone(v), tone(v), tone(v)} }
+	d := testDNG{order: binary.LittleEndian}
+
+	//A real camera matrix: whatever it holds, a neutral subject stays neutral
+	sony := d.rationals(1.43907, -0.7894, -0.06345, -0.43902, 1.40078, 0.2289, -0.02661, 0.1622, 0.61441)
+
+	tests := []struct {
+		name   string
+		colour [3]float64
+		tags   map[uint16]testTag
+		want   [3]int
+	}{
+		{"white balance and matrix keep neutral white", [3]float64{0.5, 1, 0.5},
+			map[uint16]testTag{tagAsShotNeutral: d.rationals(0.5, 1, 0.5), tagColorMatrix1: sony}, grey(1)},
+		{"auto exposure brightens a dim picture", [3]float64{0.5, 0.5, 0.5}, nil, grey(1)},
+		{"auto exposure is limited to 4x", [3]float64{0.05, 0.05, 0.05}, nil, grey(0.2)},
+		{"baseline exposure", [3]float64{1, 1, 1},
+			map[uint16]testTag{tagBaselineExposure: d.rationals(-1)}, grey(1)},
+		{"black level is subtracted", [3]float64{0.25, 0.25, 0.25},
+			map[uint16]testTag{tagBlackLevel: d.longs(16384)}, grey(0)},
+		{"white level", [3]float64{0.25, 0.125, 0.125},
+			map[uint16]testTag{tagWhiteLevel: d.longs(16384)}, [3]int{tone(1), tone(0.5), tone(0.5)}},
+		{"linearization table", [3]float64{0, 0, 0},
+			map[uint16]testTag{tagLinearizationTable: d.longs(65535)}, grey(1)},
+		{"unusable matrix is ignored", [3]float64{1, 0.5, 0.25},
+			map[uint16]testTag{tagColorMatrix1: d.rationals(0, 0, 0, 0, 0, 0, 0, 0, 0)},
+			[3]int{tone(1), tone(0.5), tone(0.25)}},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			dng := flat(16, 12, 16, tc.colour)
+			dng.tags = tc.tags
+			wantColour(t, develop(t, dng.build(), 0), tc.want)
+		})
+	}
+}
+
+// gainMapList is an opcode list with one GainMap of a single point
+func gainMapList(width, height int, gain float32) testTag {
+	be := binary.BigEndian
+	body := make([]byte, 80)
+	for i, v := range []uint32{0, 0, uint32(height), uint32(width), 0, 1, 2, 2, 1, 1} {
+		be.PutUint32(body[i*4:], v)
+	}
+	be.PutUint64(body[40:], math.Float64bits(1))
+	be.PutUint64(body[48:], math.Float64bits(1))
+	be.PutUint32(body[72:], 1)
+	be.PutUint32(body[76:], math.Float32bits(gain))
+
+	list := make([]byte, 20)
+	be.PutUint32(list, 1)
+	be.PutUint32(list[4:], opcodeGainMap)
+	be.PutUint32(list[16:], uint32(len(body)))
+	list = append(list, body...)
+	return testTag{7, len(list), list}
+}
+
+func TestDevelopGainMap(t *testing.T) {
+	d := flat(16, 12, 16, [3]float64{1, 1, 1})
+	//The map starts at row 0, column 0 with a pitch of 2: only red pixels
+	d.tags[tagOpcodeList2] = gainMapList(16, 12, 0.5)
+	wantColour(t, develop(t, d.build(), 0), [3]int{tone(0.5), tone(1), tone(1)})
+}
+
+func TestGridPosition(t *testing.T) {
+	tests := []struct {
+		name      string
+		position  float64
+		points    int
+		low, high int
+		fraction  float32
+	}{
+		{"before the grid", -1, 3, 0, 0, 0},
+		{"between points", 0.25, 3, 0, 1, 0.5},
+		{"past the grid", 2, 3, 2, 2, 0},
+		{"single point", 0.5, 1, 0, 0, 0},
+		{"not a number", math.NaN(), 3, 0, 0, 0},
+	}
+	for _, tc := range tests {
+		low, high, fraction := gridPosition(tc.position, 0, 0.5, tc.points)
+		if low != tc.low || high != tc.high || fraction != tc.fraction {
+			t.Errorf("%s: got %d,%d,%v", tc.name, low, high, fraction)
+		}
+	}
+}
+
+func TestOrient(t *testing.T) {
+	//Where the top left and top right pixel of a 3x2 picture end up
+	tests := []struct {
+		orientation       int
+		topLeft, topRight image.Point
+	}{
+		{1, image.Pt(0, 0), image.Pt(2, 0)},
+		{2, image.Pt(2, 0), image.Pt(0, 0)},
+		{3, image.Pt(2, 1), image.Pt(0, 1)},
+		{4, image.Pt(0, 1), image.Pt(2, 1)},
+		{5, image.Pt(0, 0), image.Pt(0, 2)},
+		{6, image.Pt(1, 0), image.Pt(1, 2)},
+		{7, image.Pt(1, 2), image.Pt(1, 0)},
+		{8, image.Pt(0, 2), image.Pt(0, 0)},
+	}
+	for _, tc := range tests {
+		lx, ly := orient(tc.orientation, 0, 0, 3, 2)
+		rx, ry := orient(tc.orientation, 2, 0, 3, 2)
+		if image.Pt(lx, ly) != tc.topLeft || image.Pt(rx, ry) != tc.topRight {
+			t.Errorf("orientation %d: top left %d,%d top right %d,%d", tc.orientation, lx, ly, rx, ry)
+		}
+	}
+}
+
+func TestDevelopOrientationAndSize(t *testing.T) {
+	//Left half white, right half black; turned 90 degrees clockwise the
+	//white half is on top
+	d := flat(32, 16, 12, [3]float64{})
+	d.stored = func(x, y, c int) uint16 {
+		if x < 16 {
+			return 4095
+		}
+		return 0
+	}
+	d.tags[tagOrientation] = d.shorts(6)
+	data := d.build()
+
+	width, height, err := Size(data)
+	if err != nil || width != 16 || height != 32 {
+		t.Fatalf("Size = %d, %d, %v; want 16, 32", width, height, err)
+	}
+	img := develop(t, data, 0)
+	if img.Bounds().Dx() != 16 || img.Bounds().Dy() != 32 {
+		t.Fatalf("size = %v", img.Bounds())
+	}
+	if top, bottom := rgbAt(img, 8, 4), rgbAt(img, 8, 27); top[1] < 250 || bottom[1] > 5 {
+		t.Errorf("top = %v, bottom = %v, want white above black", top, bottom)
+	}
+}
+
+func TestDevelopCrop(t *testing.T) {
+	//A masked (black) border outside the active area must not show
+	d := flat(28, 22, 16, [3]float64{})
+	d.stored = func(x, y, c int) uint16 {
+		if x >= 4 && x < 24 && y >= 2 && y < 20 {
+			return 65535
+		}
+		return 0
+	}
+	d.tags[tagActiveArea] = d.longs(2, 4, 20, 24)
+	d.tags[tagDefaultCropOrigin] = d.longs(2, 3)
+	d.tags[tagDefaultCropSize] = d.longs(16, 12)
+	img := develop(t, d.build(), 0)
+	if img.Bounds().Dx() != 16 || img.Bounds().Dy() != 12 {
+		t.Fatalf("size = %v, want 16x12", img.Bounds())
+	}
+	wantColour(t, img, [3]int{255, 255, 255})
+}
+
+func TestDevelopErrors(t *testing.T) {
+	base := func() testDNG { return flat(16, 12, 16, [3]float64{1, 1, 1}) }
+	with := func(tag uint16, value testTag) []byte {
+		d := base()
+		d.tags[tag] = value
+		return d.build()
+	}
+	d := base()
+	notDNG := base().build()
+	//Rename the DNGVersion tag
+	notDNG = bytes.Replace(notDNG, []byte{0x12, 0xC6, 1, 0}, []byte{0xFF, 0xFE, 1, 0}, 1)
+
+	tests := []struct {
+		name        string
+		data        []byte
+		unsupported bool
+	}{
+		{"empty", nil, false},
+		{"not a TIFF", []byte("this is not a picture at all"), false},
+		{"TIFF without DNG version", notDNG, false},
+		{"compressed", with(tagCompression, d.shorts(7)), true},
+		{"not Bayer", with(tagCFAPattern, testTag{1, 4, []byte{0, 0, 1, 2}}), true},
+		{"no CFA picture", with(tagPhotometric, d.shorts(2)), true},
+		{"floating point depth", with(tagBitsPerSample, d.shorts(32)), true},
+		{"size beyond the data", with(tagImageWidth, d.longs(30000)), false},
+		{"short strip", with(tagStripByteCounts, d.longs(10)), false},
+		{"strip outside the file", with(tagStripOffsets, d.longs(1<<31)), false},
+		{"black above white", with(tagBlackLevel, d.longs(70000)), false},
+	}
+	for _, tc := range tests {
+		_, err := Develop(tc.data, 0)
+		if err == nil {
+			t.Errorf("%s: expected an error", tc.name)
+		} else if errors.Is(err, ErrUnsupported) != tc.unsupported {
+			t.Errorf("%s: unsupported = %v, error %v", tc.name, !tc.unsupported, err)
+		}
+	}
+}
+
+// A directory that names itself as its child and as the next one is read once
+func TestSelfReferencingDirectory(t *testing.T) {
+	d := flat(16, 12, 16, [3]float64{1, 1, 1})
+	d.tags[tagSubIFDs] = d.longs(0)
+	data := d.build()
+	ifd := binary.LittleEndian.Uint32(data[4:])
+	count := int(binary.LittleEndian.Uint16(data[ifd:]))
+	for i := 0; i < count; i++ {
+		entry := data[int(ifd)+2+i*12:]
+		if binary.LittleEndian.Uint16(entry) == tagSubIFDs {
+			binary.LittleEndian.PutUint32(entry[8:], ifd)
+		}
+	}
+	binary.LittleEndian.PutUint32(data[len(data)-4:], ifd)
+
+	_, directories, err := readDirectories(data)
+	if err != nil || len(directories) != 1 {
+		t.Fatalf("got %d directories, %v; want 1", len(directories), err)
+	}
+	develop(t, data, 0)
+}
+
+// Damaged and hostile files must end in a picture or an error, never a panic
+func TestBoundaryValuesDoNotPanic(t *testing.T) {
+	d := flat(24, 20, 12, [3]float64{1, 0.5, 0.25})
+	d.tile = 8
+	for id, tag := range map[uint16]testTag{
+		tagOrientation:         d.shorts(6),
+		tagActiveArea:          d.longs(0, 0, 20, 24),
+		tagDefaultCropOrigin:   d.longs(2, 2),
+		tagDefaultCropSize:     d.longs(20, 16),
+		tagBlackLevelRepeatDim: d.shorts(2, 2),
+		tagBlackLevel:          d.longs(0, 1, 2, 3),
+		tagLinearizationTable:  d.shorts(0, 1000, 2000, 4095),
+		tagAsShotNeutral:       d.rationals(0.5, 1, 0.5),
+		tagColorMatrix1:        d.rationals(1, 0, 0, 0, 1, 0, 0, 0, 1),
+		tagBaselineExposure:    d.rationals(1),
+		tagOpcodeList2:         gainMapList(24, 20, 1.5),
+	} {
+		d.tags[id] = tag
+	}
+	data := d.build()
+	develop(t, data, 0)
+
+	mutated := make([]byte, len(data))
+	for _, value := range []uint32{0, 1, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF, 0x01000000, 0x00010001, 0x7F800000} {
+		for offset := 0; offset+4 <= len(data); offset += 2 {
+			copy(mutated, data)
+			binary.LittleEndian.PutUint32(mutated[offset:], value)
+			Develop(mutated, 0)
+			Develop(mutated, 4)
+		}
+	}
+	for length := 0; length < len(data); length += 7 {
+		Develop(data[:length], 0)
+	}
+}
+
+func TestSmoothChroma(t *testing.T) {
+	//Odd size, grey with a single coloured speckle
+	src := image.NewRGBA(image.Rect(0, 0, 21, 15))
+	for i := range src.Pix {
+		src.Pix[i] = 128
+	}
+	src.SetRGBA(10, 6, color.RGBA{255, 0, 0, 255})
+	out := smoothChroma(src)
+	if out.Bounds() != src.Bounds() {
+		t.Fatalf("bounds = %v", out.Bounds())
+	}
+	if got := rgbAt(out, 2, 2); got != [3]int{128, 128, 128} {
+		t.Errorf("grey changed to %v", got)
+	}
+	//The speckle keeps its brightness but loses most of its colour
+	speckle := rgbAt(out, 10, 6)
+	if speckle[0]-speckle[1] > 30 {
+		t.Errorf("speckle is still coloured: %v", speckle)
+	}
+}

+ 80 - 0
src/mod/filesystem/metadata/dngrender/noise.go

@@ -0,0 +1,80 @@
+package dngrender
+
+import (
+	"image"
+	"image/color"
+)
+
+/*
+	Colour noise
+
+	A single raw frame of a small sensor is covered in coloured speckles at
+	full resolution, which the camera app removes from its own JPEG. The eye
+	takes its detail from brightness, so smoothing only the two colour
+	channels removes the speckles without softening the picture. Smaller
+	renderings average many sensor pixels and need none of this.
+*/
+
+// Reach of the colour smoothing, in pixels of the half size colour channels
+const chromaRadius = 3
+
+// smoothChroma converts a picture to YCbCr 4:2:0 and smooths its colour
+// channels
+func smoothChroma(src *image.RGBA) *image.YCbCr {
+	width, height := src.Rect.Dx(), src.Rect.Dy()
+	out := image.NewYCbCr(src.Rect, image.YCbCrSubsampleRatio420)
+	chromaWidth, chromaHeight := (width+1)/2, (height+1)/2
+
+	parallelRows(chromaHeight, func(from, to int) {
+		for cy := from; cy < to; cy++ {
+			for cx := 0; cx < chromaWidth; cx++ {
+				var cbSum, crSum, n int
+				for y := cy * 2; y < min(cy*2+2, height); y++ {
+					for x := cx * 2; x < min(cx*2+2, width); x++ {
+						p := src.Pix[y*src.Stride+x*4:]
+						luma, cb, cr := color.RGBToYCbCr(p[0], p[1], p[2])
+						out.Y[y*out.YStride+x] = luma
+						cbSum += int(cb)
+						crSum += int(cr)
+						n++
+					}
+				}
+				out.Cb[cy*out.CStride+cx] = uint8((cbSum + n/2) / n)
+				out.Cr[cy*out.CStride+cx] = uint8((crSum + n/2) / n)
+			}
+		}
+	})
+
+	scratch := make([]uint8, len(out.Cb))
+	for _, plane := range [][]uint8{out.Cb, out.Cr} {
+		//Two box blurs in each direction come close to a Gaussian blur
+		for pass := 0; pass < 2; pass++ {
+			boxBlur(scratch, plane, chromaHeight, chromaWidth, out.CStride, 1)
+			boxBlur(plane, scratch, chromaWidth, chromaHeight, 1, out.CStride)
+		}
+	}
+	return out
+}
+
+// boxBlur averages each value with its chromaRadius neighbours on both sides
+// along lines of the plane: lines of length values, step apart, the lines
+// themselves next apart. Values past an end repeat the end.
+func boxBlur(dst, src []uint8, lines, length, next, step int) {
+	const window = 2*chromaRadius + 1
+	parallelRows(lines, func(from, to int) {
+		for line := from; line < to; line++ {
+			start := line * next
+			at := func(i int) int {
+				return int(src[start+max(0, min(length-1, i))*step])
+			}
+			sum := 0
+			for i := -chromaRadius; i <= chromaRadius; i++ {
+				sum += at(i)
+			}
+			for i := 0; i < length; i++ {
+				dst[start+i*step] = uint8((sum + window/2) / window)
+				sum += at(i+chromaRadius+1) - at(i-chromaRadius)
+			}
+		}
+	})
+}

+ 139 - 0
src/mod/filesystem/metadata/dngrender/opcode.go

@@ -0,0 +1,139 @@
+package dngrender
+
+import (
+	"encoding/binary"
+	"math"
+)
+
+/*
+	GainMap opcodes
+
+	Phone cameras record the shading of their lens (darker, tinted corners)
+	as one gain map for each colour of the mosaic, stored in OpcodeList2. The
+	other opcodes (bad pixel and lens distortion fixes) are not needed to view
+	a photo and are skipped. Opcode lists are always big endian.
+*/
+
+const (
+	opcodeGainMap = 9
+	maxGainMaps   = 8
+)
+
+// gainMap multiplies the pixels of its area by a coarse grid of gains,
+// interpolated between the grid points
+type gainMap struct {
+	top, left, bottom, right int
+	rowPitch, colPitch       int
+	pointsV, pointsH         int
+	spacingV, spacingH       float64
+	originV, originH         float64
+	mapPlanes                int
+	gains                    []float32
+}
+
+// parseGainMaps returns the GainMap opcodes of an opcode list
+func parseGainMaps(list []byte) []gainMap {
+	if len(list) < 4 {
+		return nil
+	}
+	be := binary.BigEndian
+	count := be.Uint32(list)
+	list = list[4:]
+
+	var maps []gainMap
+	for i := uint32(0); i < count && len(list) >= 16 && len(maps) < maxGainMaps; i++ {
+		id := be.Uint32(list)
+		size := int64(be.Uint32(list[12:]))
+		list = list[16:]
+		if size > int64(len(list)) {
+			break
+		}
+		body := list[:size]
+		list = list[size:]
+		if id != opcodeGainMap {
+			continue
+		}
+		if m, ok := parseGainMap(body); ok {
+			maps = append(maps, m)
+		}
+	}
+	return maps
+}
+
+// parseGainMap reads the parameters of one GainMap opcode
+func parseGainMap(body []byte) (gainMap, bool) {
+	const header = 76
+	var m gainMap
+	if len(body) < header {
+		return m, false
+	}
+	be := binary.BigEndian
+	field := func(i int) int { return int(min(be.Uint32(body[i*4:]), maxDimension)) }
+	double := func(offset int) float64 { return math.Float64frombits(be.Uint64(body[offset:])) }
+
+	m.top, m.left, m.bottom, m.right = field(0), field(1), field(2), field(3)
+	//field 4 and 5 are the first plane and plane count, a mosaic has one
+	if field(4) != 0 {
+		return m, false
+	}
+	m.rowPitch, m.colPitch = field(6), field(7)
+	m.pointsV, m.pointsH = field(8), field(9)
+	m.spacingV, m.spacingH = double(40), double(48)
+	m.originV, m.originH = double(56), double(64)
+	m.mapPlanes = field(72 / 4)
+	if m.rowPitch < 1 || m.colPitch < 1 || m.pointsV < 1 || m.pointsH < 1 || m.mapPlanes < 1 || m.mapPlanes > 4 {
+		return m, false
+	}
+	for _, v := range []float64{m.spacingV, m.spacingH, m.originV, m.originH} {
+		if math.IsNaN(v) || math.IsInf(v, 0) {
+			return m, false
+		}
+	}
+
+	total := int64(m.pointsV) * int64(m.pointsH) * int64(m.mapPlanes)
+	if total > int64(len(body)-header)/4 {
+		return m, false
+	}
+	m.gains = make([]float32, total)
+	for i := range m.gains {
+		g := math.Float32frombits(be.Uint32(body[header+i*4:]))
+		if !(g > 0 && g < 64) {
+			g = 1
+		}
+		m.gains[i] = g
+	}
+	return m, true
+}
+
+// gridPosition turns a position in the image (0 to 1) into the two grid points
+// around it and how far it is from the first
+func gridPosition(position, origin, spacing float64, points int) (int, int, float32) {
+	index := 0.0
+	if spacing > 0 {
+		index = (position - origin) / spacing
+	}
+	if !(index > 0) {
+		return 0, 0, 0
+	}
+	if index >= float64(points-1) {
+		return points - 1, points - 1, 0
+	}
+	low := int(index)
+	return low, low + 1, float32(index - float64(low))
+}
+
+// applyRow multiplies one row of the active area by the gains of this map.
+// width and height are the size of the active area.
+func (m *gainMap) applyRow(row []float32, y, width, height int) {
+	if y < m.top || y >= m.bottom || (y-m.top)%m.rowPitch != 0 {
+		return
+	}
+	v0, v1, fv := gridPosition((float64(y)+0.5)/float64(height), m.originV, m.spacingV, m.pointsV)
+	stride := m.pointsH * m.mapPlanes
+	for x := m.left; x < min(m.right, width); x += m.colPitch {
+		h0, h1, fh := gridPosition((float64(x)+0.5)/float64(width), m.originH, m.spacingH, m.pointsH)
+		top := m.gains[v0*stride+h0*m.mapPlanes]*(1-fh) + m.gains[v0*stride+h1*m.mapPlanes]*fh
+		bottom := m.gains[v1*stride+h0*m.mapPlanes]*(1-fh) + m.gains[v1*stride+h1*m.mapPlanes]*fh
+		row[x] *= top*(1-fv) + bottom*fv
+	}
+}

+ 239 - 0
src/mod/filesystem/metadata/dngrender/tiff.go

@@ -0,0 +1,239 @@
+package dngrender
+
+import (
+	"encoding/binary"
+	"errors"
+	"math"
+)
+
+/*
+	The part of TIFF a DNG is built on
+
+	Every offset and count comes from the file, so each one is checked against
+	the bytes that are really there, and the directories are walked with a
+	visited set: a directory that points back at itself must not loop.
+*/
+
+// Tags read from the directories
+const (
+	tagNewSubfileType      = 254
+	tagImageWidth          = 256
+	tagImageLength         = 257
+	tagBitsPerSample       = 258
+	tagCompression         = 259
+	tagPhotometric         = 262
+	tagStripOffsets        = 273
+	tagOrientation         = 274
+	tagSamplesPerPixel     = 277
+	tagRowsPerStrip        = 278
+	tagStripByteCounts     = 279
+	tagTileWidth           = 322
+	tagTileLength          = 323
+	tagTileOffsets         = 324
+	tagTileByteCounts      = 325
+	tagSubIFDs             = 330
+	tagCFARepeatPatternDim = 33421
+	tagCFAPattern          = 33422
+	tagDNGVersion          = 50706
+	tagCFAPlaneColor       = 50710
+	tagCFALayout           = 50711
+	tagLinearizationTable  = 50712
+	tagBlackLevelRepeatDim = 50713
+	tagBlackLevel          = 50714
+	tagWhiteLevel          = 50717
+	tagDefaultCropOrigin   = 50719
+	tagDefaultCropSize     = 50720
+	tagColorMatrix1        = 50721
+	tagColorMatrix2        = 50722
+	tagAsShotNeutral       = 50728
+	tagAsShotWhiteXY       = 50729
+	tagBaselineExposure    = 50730
+	tagCalibrationIllum1   = 50778
+	tagCalibrationIllum2   = 50779
+	tagActiveArea          = 50829
+	tagOpcodeList2         = 51009
+)
+
+// Limits on what a file may ask the parser to do
+const (
+	maxDirectories = 32
+	maxEntries     = 1024
+)
+
+// entry is one directory entry whose value lies inside the file
+type entry struct {
+	fieldType uint16
+	count     int
+	value     []byte
+}
+
+// directory is one image file directory, by tag
+type directory map[uint16]entry
+
+type tiffFile struct {
+	data  []byte
+	order binary.ByteOrder
+}
+
+// Bytes of one value of each TIFF field type, by type number
+var typeSizes = [...]int{0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4}
+
+// readDirectories returns every directory of a TIFF file: the main chain and
+// the SubIFDs. The first one is IFD0.
+func readDirectories(data []byte) (*tiffFile, []directory, error) {
+	if len(data) < 8 {
+		return nil, nil, errors.New("file too small to be a DNG")
+	}
+	t := &tiffFile{data: data}
+	switch string(data[:2]) {
+	case "II":
+		t.order = binary.LittleEndian
+	case "MM":
+		t.order = binary.BigEndian
+	default:
+		return nil, nil, errors.New("not a TIFF based file")
+	}
+	if t.order.Uint16(data[2:4]) != 42 {
+		return nil, nil, errors.New("not a TIFF based file")
+	}
+
+	var directories []directory
+	visited := map[uint32]bool{}
+	pending := []uint32{t.order.Uint32(data[4:8])}
+	for len(pending) > 0 && len(directories) < maxDirectories {
+		offset := pending[0]
+		pending = pending[1:]
+		if offset == 0 || visited[offset] {
+			continue
+		}
+		visited[offset] = true
+
+		dir, next, ok := t.readDirectory(offset)
+		if !ok {
+			continue
+		}
+		directories = append(directories, dir)
+		for _, sub := range t.uints(dir[tagSubIFDs], maxDirectories) {
+			pending = append(pending, uint32(sub))
+		}
+		pending = append(pending, next)
+	}
+	if len(directories) == 0 {
+		return nil, nil, errors.New("no image directory found")
+	}
+	return t, directories, nil
+}
+
+// readDirectory reads the directory at offset and the offset of the next one
+func (t *tiffFile) readDirectory(offset uint32) (directory, uint32, bool) {
+	size := int64(len(t.data))
+	pos := int64(offset)
+	if pos > size-2 {
+		return nil, 0, false
+	}
+	count := int(t.order.Uint16(t.data[pos:]))
+	if count == 0 || count > maxEntries {
+		return nil, 0, false
+	}
+	pos += 2
+
+	dir := directory{}
+	for i := 0; i < count; i++ {
+		if pos > size-12 {
+			return dir, 0, true
+		}
+		raw := t.data[pos : pos+12]
+		pos += 12
+
+		tag := t.order.Uint16(raw[0:])
+		fieldType := t.order.Uint16(raw[2:])
+		n := int64(t.order.Uint32(raw[4:]))
+		if int(fieldType) >= len(typeSizes) || fieldType == 0 {
+			continue
+		}
+		length := n * int64(typeSizes[fieldType])
+		var value []byte
+		if length <= 4 {
+			value = raw[8 : 8+length]
+		} else {
+			start := int64(t.order.Uint32(raw[8:]))
+			if length > size || start > size-length {
+				continue
+			}
+			value = t.data[start : start+length]
+		}
+		dir[tag] = entry{fieldType: fieldType, count: int(n), value: value}
+	}
+
+	var next uint32
+	if pos <= size-4 {
+		next = t.order.Uint32(t.data[pos:])
+	}
+	return dir, next, true
+}
+
+// numbers decodes up to limit values of an entry as floating point
+func (t *tiffFile) numbers(e entry, limit int) []float64 {
+	n := min(e.count, limit)
+	if n <= 0 {
+		return nil
+	}
+	out := make([]float64, n)
+	for i := range out {
+		switch e.fieldType {
+		case 1, 7: // BYTE, UNDEFINED
+			out[i] = float64(e.value[i])
+		case 6: // SBYTE
+			out[i] = float64(int8(e.value[i]))
+		case 3: // SHORT
+			out[i] = float64(t.order.Uint16(e.value[i*2:]))
+		case 8: // SSHORT
+			out[i] = float64(int16(t.order.Uint16(e.value[i*2:])))
+		case 4, 13: // LONG, IFD
+			out[i] = float64(t.order.Uint32(e.value[i*4:]))
+		case 9: // SLONG
+			out[i] = float64(int32(t.order.Uint32(e.value[i*4:])))
+		case 5: // RATIONAL
+			if d := t.order.Uint32(e.value[i*8+4:]); d != 0 {
+				out[i] = float64(t.order.Uint32(e.value[i*8:])) / float64(d)
+			}
+		case 10: // SRATIONAL
+			if d := int32(t.order.Uint32(e.value[i*8+4:])); d != 0 {
+				out[i] = float64(int32(t.order.Uint32(e.value[i*8:]))) / float64(d)
+			}
+		case 11: // FLOAT
+			out[i] = float64(math.Float32frombits(t.order.Uint32(e.value[i*4:])))
+		case 12: // DOUBLE
+			out[i] = math.Float64frombits(t.order.Uint64(e.value[i*8:]))
+		default:
+			return nil
+		}
+		if math.IsNaN(out[i]) || math.IsInf(out[i], 0) {
+			out[i] = 0
+		}
+	}
+	return out
+}
+
+// uints decodes up to limit values of an entry as non negative integers
+func (t *tiffFile) uints(e entry, limit int) []int64 {
+	values := t.numbers(e, limit)
+	if values == nil {
+		return nil
+	}
+	out := make([]int64, len(values))
+	for i, v := range values {
+		if v > 0 && v <= math.MaxUint32 {
+			out[i] = int64(v)
+		}
+	}
+	return out
+}
+
+// uintValue is the first value of a tag, or fallback when the tag is missing
+func (t *tiffFile) uintValue(dir directory, tag uint16, fallback int64) int64 {
+	if v := t.uints(dir[tag], 1); len(v) == 1 {
+		return v[0]
+	}
+	return fallback
+}

+ 112 - 58
src/mod/filesystem/metadata/raw.go

@@ -12,6 +12,7 @@ import (
 	"github.com/nfnt/resize"
 	"github.com/oliamb/cutter"
 	"imuslab.com/arozos/mod/filesystem"
+	"imuslab.com/arozos/mod/filesystem/metadata/dngrender"
 )
 
 // Generate thumbnail for RAW image files by extracting embedded JPEG
@@ -33,37 +34,14 @@ func generateThumbnailForRAW(fsh *filesystem.FileSystemHandler, cacheFolder stri
 
 	// Try to decode the RAW image
 	var img image.Image
-	var jpegData []byte
-
-	ext := filepath.Ext(file)
-	if strings.ToLower(ext) == ".dng" {
-		// For DNG files, try both marker scanning and TIFF IFD parsing
-		// Then use the largest JPEG found
-		jpegFromMarkers, err1 := extractLargestJPEG(rawData)
-		jpegFromTIFF, err2 := extractJPEGFromTIFF(rawData)
-
-		// Use whichever is largest
-		if err1 == nil && err2 == nil {
-			if len(jpegFromMarkers) > len(jpegFromTIFF) {
-				jpegData = jpegFromMarkers
-			} else {
-				jpegData = jpegFromTIFF
-			}
-		} else if err1 == nil {
-			jpegData = jpegFromMarkers
-		} else if err2 == nil {
-			jpegData = jpegFromTIFF
-		} else {
-			return "", errors.New("failed to extract any JPEG from DNG file: " + err1.Error() + "; " + err2.Error())
-		}
-
-		img, _, err = image.Decode(bytes.NewReader(jpegData))
+	if strings.ToLower(filepath.Ext(file)) == ".dng" {
+		img, err = dngThumbnailSource(rawData)
 		if err != nil {
-			return "", errors.New("failed to decode DNG JPEG data: " + err.Error())
+			return "", err
 		}
 	} else {
 		// For other RAW formats (ARW, CR2, NEF, RAF, ORF), only use marker scanning
-		jpegData, err = extractLargestJPEG(rawData)
+		jpegData, err := extractLargestJPEG(rawData)
 		if err != nil {
 			return "", errors.New("failed to extract thumbnail from RAW file: " + err.Error())
 		}
@@ -125,6 +103,80 @@ func generateThumbnailForRAW(fsh *filesystem.FileSystemHandler, cacheFolder stri
 	return "", nil
 }
 
+/*
+	DNG files
+
+	Many carry a JPEG preview like other RAW formats, which is the camera's own
+	rendering and is used when it is large enough. Others (phones, through
+	Android's DngCreator) hold only the sensor data, or a tiny thumbnail
+	beside it: those are developed by package dngrender.
+*/
+
+const (
+	// Shortest long side of a preview that is shown as the photo
+	dngMinPreviewSize = 1024
+	// Short side of the picture a thumbnail is cut from
+	dngThumbnailSize = 480
+)
+
+// dngPreview returns the embedded JPEG of a DNG with the most pixels and its
+// size, or nil when it holds none that can be decoded. Raw data stored as
+// lossless JPEG looks like one but cannot be decoded, so it is not chosen.
+func dngPreview(data []byte) (preview []byte, width int, height int) {
+	for _, extract := range []func([]byte) ([]byte, error){extractLargestJPEG, extractJPEGFromTIFF} {
+		candidate, err := extract(data)
+		if err != nil {
+			continue
+		}
+		cfg, err := jpeg.DecodeConfig(bytes.NewReader(candidate))
+		if err == nil && int64(cfg.Width)*int64(cfg.Height) > int64(width)*int64(height) {
+			preview, width, height = candidate, cfg.Width, cfg.Height
+		}
+	}
+	return preview, width, height
+}
+
+// renderDNG returns a DNG photo as a JPEG
+func renderDNG(data []byte) ([]byte, error) {
+	preview, width, height := dngPreview(data)
+	if max(width, height) >= dngMinPreviewSize {
+		return preview, nil
+	}
+
+	img, err := dngrender.Develop(data, 0)
+	if err != nil {
+		if preview != nil {
+			//A small preview is better than nothing
+			return preview, nil
+		}
+		return nil, errors.New("failed to render DNG file: " + err.Error())
+	}
+	var buf bytes.Buffer
+	if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 92}); err != nil {
+		return nil, errors.New("failed to encode DNG file: " + err.Error())
+	}
+	return buf.Bytes(), nil
+}
+
+// dngThumbnailSource returns the picture the thumbnail of a DNG is made from
+func dngThumbnailSource(data []byte) (image.Image, error) {
+	preview, width, height := dngPreview(data)
+	if min(width, height) < dngThumbnailSize {
+		img, err := dngrender.Develop(data, dngThumbnailSize)
+		if err == nil {
+			return img, nil
+		}
+		if preview == nil {
+			return nil, errors.New("failed to render DNG file: " + err.Error())
+		}
+	}
+	img, err := jpeg.Decode(bytes.NewReader(preview))
+	if err != nil {
+		return nil, errors.New("failed to decode DNG preview: " + err.Error())
+	}
+	return img, nil
+}
+
 // Extract largest embedded JPEG from RAW file
 // Most RAW files (ARW, CR2, DNG, NEF, etc.) are TIFF-based and contain embedded JPEG previews
 // This follows the approach used by dcraw.c for thumbnail extraction
@@ -319,13 +371,15 @@ func extractUncompressedThumbnail(data []byte, order binary.ByteOrder, ifdOffset
 
 	stripData := data[stripOffset : stripOffset+stripByteCount]
 
-	// Decode RGB strip to image.Image
-	img := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
-	expectedSize := int(width * height * 3)
-	if len(stripData) < expectedSize {
+	// The claimed size must fit in the strip before anything is allocated
+	// (written as a division so that it cannot overflow)
+	if uint64(width) > uint64(len(stripData))/3/uint64(height) {
 		return nil, errors.New("strip data smaller than expected")
 	}
 
+	// Decode RGB strip to image.Image
+	img := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
+
 	// Copy RGB data to RGBA image
 	for y := 0; y < int(height); y++ {
 		for x := 0; x < int(width); x++ {
@@ -348,15 +402,35 @@ func extractUncompressedThumbnail(data []byte, order binary.ByteOrder, ifdOffset
 	return buf.Bytes(), nil
 }
 
+// Limits on the directories of an untrusted TIFF file
+const (
+	maxTIFFDirectories = 64
+	maxTIFFEntries     = 1024
+)
+
 // Parse TIFF IFD chain recursively to find all JPEG data
 // DNG files have multiple IFDs linked together and SubIFDs
 func parseTIFFIFDChain(data []byte, order binary.ByteOrder, ifdOffset uint64, candidates *[][]byte) {
+	walkTIFFDirectories(data, order, ifdOffset, candidates, map[uint64]bool{})
+}
+
+// walkTIFFDirectories reads one directory and those it points to. Each is read
+// once: a file whose directories point back at each other would otherwise
+// recurse until the stack overflows, which ends the whole server.
+func walkTIFFDirectories(data []byte, order binary.ByteOrder, ifdOffset uint64, candidates *[][]byte, visited map[uint64]bool) {
 	if ifdOffset == 0 || ifdOffset >= uint64(len(data))-2 {
 		return
 	}
+	if visited[ifdOffset] || len(visited) >= maxTIFFDirectories {
+		return
+	}
+	visited[ifdOffset] = true
 
 	// Read number of directory entries
 	numEntries := order.Uint16(data[ifdOffset : ifdOffset+2])
+	if numEntries > maxTIFFEntries {
+		return
+	}
 	entryOffset := ifdOffset + 2
 
 	var stripOffsets []uint64
@@ -440,7 +514,9 @@ func parseTIFFIFDChain(data []byte, order binary.ByteOrder, ifdOffset uint64, ca
 			for i := 0; i < len(stripOffsets) && i < len(stripByteCounts); i++ {
 				offset := stripOffsets[i]
 				length := stripByteCounts[i]
-				if offset+length <= uint64(len(data)) {
+				// Strips repeating the same bytes must not add up to more
+				// than the file holds
+				if offset+length <= uint64(len(data)) && uint64(jpegData.Len())+length <= uint64(len(data)) {
 					jpegData.Write(data[offset : offset+length])
 				}
 			}
@@ -456,7 +532,7 @@ func parseTIFFIFDChain(data []byte, order binary.ByteOrder, ifdOffset uint64, ca
 
 	// Process SubIFDs (child IFDs)
 	for _, subOffset := range subIFDOffsets {
-		parseTIFFIFDChain(data, order, subOffset, candidates)
+		walkTIFFDirectories(data, order, subOffset, candidates, visited)
 	}
 
 	// Get next IFD in chain (offset is after all entries)
@@ -464,7 +540,7 @@ func parseTIFFIFDChain(data []byte, order binary.ByteOrder, ifdOffset uint64, ca
 	if nextIFDOffset+4 <= uint64(len(data)) {
 		nextIFD := order.Uint32(data[nextIFDOffset : nextIFDOffset+4])
 		if nextIFD > 0 {
-			parseTIFFIFDChain(data, order, uint64(nextIFD), candidates)
+			walkTIFFDirectories(data, order, uint64(nextIFD), candidates, visited)
 		}
 	}
 }
@@ -555,30 +631,8 @@ func RenderRAWImage(fsh *filesystem.FileSystemHandler, file string) ([]byte, err
 		return nil, errors.New("failed to read RAW file: " + err.Error())
 	}
 
-	ext := filepath.Ext(file)
-	if strings.ToLower(ext) == ".dng" {
-		// For DNG files, try both marker scanning and TIFF IFD parsing
-		// Then use the largest JPEG found
-		jpegFromMarkers, err1 := extractLargestJPEG(rawData)
-		jpegFromTIFF, err2 := extractJPEGFromTIFF(rawData)
-
-		// Use whichever is largest
-		var jpegData []byte
-		if err1 == nil && err2 == nil {
-			if len(jpegFromMarkers) > len(jpegFromTIFF) {
-				jpegData = jpegFromMarkers
-			} else {
-				jpegData = jpegFromTIFF
-			}
-		} else if err1 == nil {
-			jpegData = jpegFromMarkers
-		} else if err2 == nil {
-			jpegData = jpegFromTIFF
-		} else {
-			return nil, errors.New("failed to extract any JPEG from DNG file: " + err1.Error() + "; " + err2.Error())
-		}
-
-		return jpegData, nil
+	if strings.ToLower(filepath.Ext(file)) == ".dng" {
+		return renderDNG(rawData)
 	}
 
 	// For other RAW formats (ARW, CR2, NEF, RAF, ORF), use marker scanning

+ 236 - 0
src/mod/filesystem/metadata/raw_dng_test.go

@@ -0,0 +1,236 @@
+package metadata
+
+import (
+	"bytes"
+	"encoding/binary"
+	"image"
+	"image/jpeg"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// testIFD builds a little endian TIFF whose only directory has these entries
+// of {tag, type, count, value}, followed by extra
+func testIFD(entries [][4]uint32, extra []byte) []byte {
+	le := binary.LittleEndian
+	out := []byte("II*\x00\x08\x00\x00\x00")
+	out = le.AppendUint16(out, uint16(len(entries)))
+	for _, e := range entries {
+		out = le.AppendUint16(out, uint16(e[0]))
+		out = le.AppendUint16(out, uint16(e[1]))
+		out = le.AppendUint32(out, e[2])
+		out = le.AppendUint32(out, e[3])
+	}
+	out = le.AppendUint32(out, 0)
+	return append(out, extra...)
+}
+
+// testDNGFile builds a DNG holding width x height of grey sensor data and,
+// when previewWidth is not 0, a JPEG preview of that width (4:3)
+func testDNGFile(t *testing.T, width, height int, compression uint32, previewWidth int) []byte {
+	t.Helper()
+	const entries = 10
+	dataOffset := uint32(8 + 2 + entries*12 + 4)
+
+	raw := make([]byte, width*height*2)
+	for i := 0; i < len(raw); i += 2 {
+		binary.LittleEndian.PutUint16(raw[i:], 2000)
+	}
+	out := testIFD([][4]uint32{
+		{256, 4, 1, uint32(width)},
+		{257, 4, 1, uint32(height)},
+		{258, 3, 1, 12},
+		{259, 3, 1, compression},
+		{262, 3, 1, 32803},
+		{273, 4, 1, dataOffset},
+		{279, 4, 1, uint32(width * height * 2)},
+		{33421, 3, 2, 0x00020002},
+		{33422, 1, 4, 0x02010100}, // RGGB
+		{50706, 1, 4, 0x00000401},
+	}, nil)
+
+	//The strip is 16 bit so that no marker bytes appear in it by chance
+	le := binary.LittleEndian
+	le.PutUint32(out[8+2+2*12+8:], 16)
+	out = append(out, raw...)
+
+	if previewWidth > 0 {
+		var buf bytes.Buffer
+		if err := jpeg.Encode(&buf, image.NewGray(image.Rect(0, 0, previewWidth, previewWidth*3/4)), nil); err != nil {
+			t.Fatalf("encode preview: %v", err)
+		}
+		out = append(out, buf.Bytes()...)
+	}
+	return out
+}
+
+func jpegSize(t *testing.T, data []byte) image.Point {
+	t.Helper()
+	cfg, err := jpeg.DecodeConfig(bytes.NewReader(data))
+	if err != nil {
+		t.Fatalf("not a JPEG: %v", err)
+	}
+	return image.Pt(cfg.Width, cfg.Height)
+}
+
+func TestRenderDNG(t *testing.T) {
+	tests := []struct {
+		name          string
+		width, height int
+		compression   uint32
+		preview       int
+		want          image.Point // zero: an error is expected
+	}{
+		{"raw data only is developed", 64, 48, 1, 0, image.Pt(64, 48)},
+		{"large preview is used", 64, 48, 1, 1200, image.Pt(1200, 900)},
+		{"thumbnail sized preview is not", 640, 480, 1, 160, image.Pt(640, 480)},
+		{"small preview when raw cannot be developed", 64, 48, 7, 160, image.Pt(160, 120)},
+		{"nothing to show", 64, 48, 7, 0, image.Point{}},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			got, err := renderDNG(testDNGFile(t, tc.width, tc.height, tc.compression, tc.preview))
+			if tc.want == (image.Point{}) {
+				if err == nil {
+					t.Fatal("expected an error")
+				}
+				return
+			}
+			if err != nil {
+				t.Fatalf("renderDNG: %v", err)
+			}
+			if size := jpegSize(t, got); size != tc.want {
+				t.Errorf("size = %v, want %v", size, tc.want)
+			}
+		})
+	}
+}
+
+func TestDNGThumbnailSource(t *testing.T) {
+	tests := []struct {
+		name          string
+		width, height int
+		compression   uint32
+		preview       int
+		want          image.Point
+	}{
+		{"developed at a reduced size", 1920, 1440, 1, 0, image.Pt(960, 720)},
+		{"preview large enough", 64, 48, 1, 800, image.Pt(800, 600)},
+		{"preview too small", 640, 480, 1, 160, image.Pt(640, 480)},
+		{"small preview when raw cannot be developed", 64, 48, 7, 160, image.Pt(160, 120)},
+		{"nothing to show", 64, 48, 7, 0, image.Point{}},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			img, err := dngThumbnailSource(testDNGFile(t, tc.width, tc.height, tc.compression, tc.preview))
+			if tc.want == (image.Point{}) {
+				if err == nil {
+					t.Fatal("expected an error")
+				}
+				return
+			}
+			if err != nil {
+				t.Fatalf("dngThumbnailSource: %v", err)
+			}
+			if size := img.Bounds().Size(); size != tc.want {
+				t.Errorf("size = %v, want %v", size, tc.want)
+			}
+		})
+	}
+}
+
+func TestRawOnlyDNGThumbnailAndRender(t *testing.T) {
+	fsh, dir := newTestFSH(t)
+	src := filepath.ToSlash(filepath.Join(dir, "20230618_144115.DNG"))
+	if err := os.WriteFile(src, testDNGFile(t, 640, 480, 1, 0), 0644); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+	cache := filepath.ToSlash(dir) + "/"
+
+	if _, err := generateThumbnailForRAW(fsh, cache, src, true); err != nil {
+		t.Fatalf("thumbnail: %v", err)
+	}
+	thumbnail, err := os.ReadFile(cache + "20230618_144115.DNG.jpg")
+	if err != nil {
+		t.Fatalf("no thumbnail written: %v", err)
+	}
+	if size := jpegSize(t, thumbnail); size != image.Pt(480, 480) {
+		t.Errorf("thumbnail size = %v, want 480x480", size)
+	}
+
+	full, err := RenderRAWImage(fsh, src)
+	if err != nil {
+		t.Fatalf("render: %v", err)
+	}
+	if size := jpegSize(t, full); size != image.Pt(640, 480) {
+		t.Errorf("rendered size = %v, want 640x480", size)
+	}
+}
+
+// Directories pointing back at themselves used to recurse until the stack
+// overflowed, which no recover can catch
+func TestParseTIFFIFDChain_SelfReference(t *testing.T) {
+	data := testIFD([][4]uint32{{0x014A, 4, 1, 8}}, nil)
+	binary.LittleEndian.PutUint32(data[len(data)-4:], 8) // next directory: itself
+
+	var candidates [][]byte
+	parseTIFFIFDChain(data, binary.LittleEndian, 8, &candidates)
+	if len(candidates) != 0 {
+		t.Errorf("got %d candidates, want none", len(candidates))
+	}
+}
+
+// Strips naming the same bytes over and over must not multiply the file
+func TestParseTIFFIFDChain_RepeatedStrips(t *testing.T) {
+	const (
+		strips  = 3
+		offsets = 8 + 2 + 3*12 + 4 // right after the directory
+		counts  = offsets + strips*4
+		blob    = counts + strips*4
+		length  = 1000
+	)
+	var extra []byte
+	for i := 0; i < strips; i++ {
+		extra = binary.LittleEndian.AppendUint32(extra, blob)
+	}
+	for i := 0; i < strips; i++ {
+		extra = binary.LittleEndian.AppendUint32(extra, length)
+	}
+	extra = append(extra, 0xFF, 0xD8)
+	extra = append(extra, make([]byte, length-2)...)
+	data := testIFD([][4]uint32{
+		{0x0103, 3, 1, 7},
+		{0x0111, 4, strips, offsets},
+		{0x0117, 4, strips, counts},
+	}, extra)
+
+	var candidates [][]byte
+	parseTIFFIFDChain(data, binary.LittleEndian, 8, &candidates)
+	if len(candidates) != 1 || len(candidates[0]) != length {
+		t.Fatalf("got %d candidates, want one of %d bytes", len(candidates), length)
+	}
+}
+
+func TestExtractUncompressedThumbnail_HugeSize(t *testing.T) {
+	tests := []struct {
+		name          string
+		width, height uint32
+	}{
+		{"overflowing", 0xFFFFFFFF, 0xFFFFFFFF},
+		{"larger than the data", 100000, 100000},
+	}
+	for _, tc := range tests {
+		data := testIFD([][4]uint32{
+			{0x0100, 4, 1, tc.width},
+			{0x0101, 4, 1, tc.height},
+			{0x0103, 3, 1, 1},
+			{0x0106, 3, 1, 2},
+			{0x0111, 4, 1, 8},
+			{0x0117, 4, 1, 16},
+		}, nil)
+		if _, err := extractUncompressedThumbnail(data, binary.LittleEndian, 8); err == nil {
+			t.Errorf("%s: expected an error", tc.name)
+		}
+	}
+}

+ 45 - 25
src/mod/media/mediaserver/mediaserver.go

@@ -225,18 +225,9 @@ func (s *Instance) ServerMedia(w http.ResponseWriter, r *http.Request) {
 	}
 
 	// Check if this is a RAW image file and render it as JPEG (preview only, not download)
-	if !downloadMode && metadata.IsRawImageFile(realFilepath) {
-		jpegData, err := metadata.RenderRAWImage(targetFsh, realFilepath)
-		if err != nil {
-			// If RAW rendering fails, fall back to serving the raw file
-			s.options.Logger.PrintAndLog("Media Server", "Failed to render RAW image: "+err.Error(), nil)
-		} else {
-			// Successfully rendered RAW image, serve as JPEG
-			w.Header().Set("Content-Type", "image/jpeg")
-			w.Header().Set("Content-Length", strconv.Itoa(len(jpegData)))
-			w.Write(jpegData)
-			return
-		}
+	// If rendering fails, fall back to serving the raw file
+	if !downloadMode && metadata.IsRawImageFile(realFilepath) && s.serveRAWAsJPEG(w, r, targetFsh, realFilepath) {
+		return
 	}
 
 	// HEIC photos (iPhone) only show in Safari, so they are decoded and sent
@@ -806,20 +797,49 @@ func readStoryboardMeta(fshAbs filesystem.FileSystemAbstraction, realFilepath st
 	return &layout
 }
 
-// serveHEICAsJPEG sends a HEIC photo decoded to JPEG. Decoding a 12 MP photo
-// takes a while, so the ETag of the source file is checked first: a browser
-// that already holds this version gets a 304 without a decode.
+// answerNotModified sets the revalidation headers of a picture rendered from a
+// source file. Rendering takes a while, so it is checked first: a browser that
+// already holds this version of the source gets a 304 (done is then true).
+func answerNotModified(w http.ResponseWriter, r *http.Request, fsh *filesystem.FileSystemHandler, realFilepath string) (modTime time.Time, done bool) {
+	if fsh.RequireBuffer {
+		return modTime, false
+	}
+	info, err := fsh.FileSystemAbstraction.Stat(realFilepath)
+	if err != nil {
+		return modTime, false
+	}
+	utils.SetRevalidationHeaders(w, info)
+	if etag := w.Header().Get("ETag"); etag != "" && r.Header.Get("If-None-Match") == etag {
+		w.WriteHeader(http.StatusNotModified)
+		return info.ModTime(), true
+	}
+	return info.ModTime(), false
+}
+
+// serveRAWAsJPEG sends a RAW photo rendered as JPEG. It returns false, with
+// nothing written, when the file cannot be rendered.
+func (s *Instance) serveRAWAsJPEG(w http.ResponseWriter, r *http.Request, fsh *filesystem.FileSystemHandler, realFilepath string) bool {
+	modTime, done := answerNotModified(w, r, fsh, realFilepath)
+	if done {
+		return true
+	}
+
+	jpegData, err := metadata.RenderRAWImage(fsh, realFilepath)
+	if err != nil {
+		s.options.Logger.PrintAndLog("Media Server", "Failed to render RAW image", err)
+		w.Header().Del("ETag")
+		return false
+	}
+	w.Header().Set("Content-Type", "image/jpeg")
+	http.ServeContent(w, r, filepath.Base(realFilepath)+".jpg", modTime, bytes.NewReader(jpegData))
+	return true
+}
+
+// serveHEICAsJPEG sends a HEIC photo decoded to JPEG
 func (s *Instance) serveHEICAsJPEG(w http.ResponseWriter, r *http.Request, fsh *filesystem.FileSystemHandler, realFilepath string) {
-	var modTime time.Time
-	if !fsh.RequireBuffer {
-		if info, err := fsh.FileSystemAbstraction.Stat(realFilepath); err == nil {
-			utils.SetRevalidationHeaders(w, info)
-			modTime = info.ModTime()
-			if etag := w.Header().Get("ETag"); etag != "" && r.Header.Get("If-None-Match") == etag {
-				w.WriteHeader(http.StatusNotModified)
-				return
-			}
-		}
+	modTime, done := answerNotModified(w, r, fsh, realFilepath)
+	if done {
+		return
 	}
 
 	jpegData, err := metadata.RenderHEICImage(fsh, realFilepath)

+ 101 - 0
src/mod/media/mediaserver/raw_test.go

@@ -0,0 +1,101 @@
+package mediaserver
+
+import (
+	"encoding/binary"
+	"image/jpeg"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// writeRawDNG writes a DNG holding only grey sensor data, no preview
+func writeRawDNG(t *testing.T, path string, width, height int) {
+	t.Helper()
+	const entries = 10
+	le := binary.LittleEndian
+	dataOffset := uint32(8 + 2 + entries*12 + 4)
+
+	out := []byte("II*\x00\x08\x00\x00\x00")
+	out = le.AppendUint16(out, entries)
+	for _, e := range [entries][4]uint32{
+		{256, 4, 1, uint32(width)},
+		{257, 4, 1, uint32(height)},
+		{258, 3, 1, 16},
+		{259, 3, 1, 1},
+		{262, 3, 1, 32803},
+		{273, 4, 1, dataOffset},
+		{279, 4, 1, uint32(width * height * 2)},
+		{33421, 3, 2, 0x00020002},
+		{33422, 1, 4, 0x02010100},
+		{50706, 1, 4, 0x00000401},
+	} {
+		out = le.AppendUint16(out, uint16(e[0]))
+		out = le.AppendUint16(out, uint16(e[1]))
+		out = le.AppendUint32(out, e[2])
+		out = le.AppendUint32(out, e[3])
+	}
+	out = le.AppendUint32(out, 0)
+	for i := 0; i < width*height; i++ {
+		out = le.AppendUint16(out, 2000)
+	}
+	if err := os.WriteFile(path, out, 0644); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+}
+
+func TestServeRAWAsJPEG(t *testing.T) {
+	srv, fsh, dir := newHEICTestServer(t)
+	src := filepath.Join(dir, "IMG_0001.DNG")
+	writeRawDNG(t, src, 64, 48)
+	broken := filepath.Join(dir, "broken.dng")
+	os.WriteFile(broken, []byte("not a picture"), 0644)
+
+	rec := httptest.NewRecorder()
+	if !srv.serveRAWAsJPEG(rec, httptest.NewRequest("GET", "/media?file=x", nil), fsh, src) {
+		t.Fatal("DNG was not served")
+	}
+	if ct := rec.Header().Get("Content-Type"); ct != "image/jpeg" {
+		t.Errorf("Content-Type = %q, want image/jpeg", ct)
+	}
+	img, err := jpeg.Decode(rec.Body)
+	if err != nil {
+		t.Fatalf("body is not a JPEG: %v", err)
+	}
+	if img.Bounds().Dx() != 64 || img.Bounds().Dy() != 48 {
+		t.Errorf("size = %v, want 64x48", img.Bounds())
+	}
+	etag := rec.Header().Get("ETag")
+	if etag == "" {
+		t.Fatal("expected an ETag")
+	}
+
+	tests := []struct {
+		name    string
+		file    string
+		etag    string
+		handled bool
+		want    int
+	}{
+		{"same version is not rendered again", src, etag, true, http.StatusNotModified},
+		{"stale tag gets the picture", src, `"0-0"`, true, http.StatusOK},
+		{"unrenderable file is left to the caller", broken, "", false, http.StatusOK},
+	}
+	for _, tc := range tests {
+		req := httptest.NewRequest("GET", "/media?file=x", nil)
+		if tc.etag != "" {
+			req.Header.Set("If-None-Match", tc.etag)
+		}
+		rec := httptest.NewRecorder()
+		if handled := srv.serveRAWAsJPEG(rec, req, fsh, tc.file); handled != tc.handled {
+			t.Errorf("%s: handled = %v, want %v", tc.name, handled, tc.handled)
+		}
+		if rec.Code != tc.want {
+			t.Errorf("%s: status = %d, want %d", tc.name, rec.Code, tc.want)
+		}
+		if !tc.handled && (rec.Body.Len() != 0 || rec.Header().Get("ETag") != "") {
+			t.Errorf("%s: something was written", tc.name)
+		}
+	}
+}