All files / lib raw.ts

56.75% Statements 42/74
71.79% Branches 28/39
83.33% Functions 10/12
58.57% Lines 41/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257                        14x                                                                                           14x                                           3x   76x                                                                                                                 6x 6x 1x     5x 5x 1x     4x 4x               2x       4x 4x     4x 2x   1x                           1x     1x             1x     1x                               15x   2x   1x   1x   1x   1x   1x   1x     1x   1x   1x     1x 1x 3x           1x 1x 3x         1x   1x      
// @wc-ignore-file
 
import type { EXIFField } from './database.js';
import type { RuntimeValue } from './schemas/metadata.js';
 
import LibRaw from 'libraw-wasm';
import { GPSHelper } from 'piexifjs';
 
import { coerceExifValue } from './exif.js';
import { openDatabase, tables } from './idb.svelte.js';
import { storeMetadataValue } from './metadata/storage.js';
 
export const RAW_IMAGE_FILE_EXTENSIONS = [
	'.3fr',
	'.ari',
	'.arw',
	'.bay',
	'.braw',
	'.crw',
	'.cr2',
	'.cr3',
	'.cap',
	'.data',
	'.dcs',
	'.dcr',
	'.dng',
	'.drf',
	'.eip',
	'.erf',
	'.fff',
	'.gpr',
	'.iiq',
	'.k25',
	'.kdc',
	'.mdc',
	'.mef',
	'.mos',
	'.mrw',
	'.nef',
	'.nrw',
	'.obm',
	'.orf',
	'.pef',
	'.ptx',
	'.pxn',
	'.r3d',
	'.raf',
	'.raw',
	'.rwl',
	'.rw2',
	'.rwz',
	'.sr2',
	'.srf',
	'.srw',
	'.tif',
	'.x3f',
];
 
export const RAW_IMAGE_MEDIA_TYPES = [
	'image/CR2',
	'image/x-canon-cr2',
	'image/x-dcraw',
	'image/x-canon-crw',
	'image/x-kodak-dcr',
	'image/x-adobe-dng',
	'image/x-epson-erf',
	'image/x-kodak-k25',
	'image/x-kodak-kdc',
	'image/x-minolta-mrw',
	'image/x-nikon-nef',
	'image/x-olympus-orf',
	'image/x-pentax-pef',
	'image/x-fuji-raf',
	'image/x-panasonic-raw',
	'image/x-sony-sr2',
	'image/x-sony-srf',
	'image/x-sigma-x3f',
];
 
export function isRawImage(file: Pick<File, 'type' | 'name'>) {
	return (
		RAW_IMAGE_MEDIA_TYPES.includes(file.type) ||
		RAW_IMAGE_FILE_EXTENSIONS.some((ext) => file.name.toLocaleLowerCase().endsWith(ext))
	);
}
 
async function decodeRawPhoto(bytes: ArrayBuffer): Promise<{
	imageData: ImageData;
	metadata: import('libraw-wasm').Metadata | undefined;
}> {
	const raw = new LibRaw();
	await raw.open(new Uint8Array(bytes));
	const metadata = await raw.metadata(true);
 
	const decoded = await raw.imageData();
	if (!decoded) {
		throw new Error('Failed to decode raw photo');
	}
 
	const { width, height, data: pixels } = decoded;
	const imageData = new ImageData(width, height);
 
	// Fill imageData. Note that pixels stores in the following order: R/G/B first -> height -> width
	for (let i = 0; i < pixels.length / 3; i++) {
		imageData.data[i * 4 + 0] = pixels[i * 3 + 0];
		imageData.data[i * 4 + 1] = pixels[i * 3 + 1];
		imageData.data[i * 4 + 2] = pixels[i * 3 + 2];
		imageData.data[i * 4 + 3] = 255;
	}
 
	return { imageData, metadata };
}
 
/**
 * Transcode a raw photo into JPEG format.
 */
export async function transcodeRawPhotoToJPEG(bytes: ArrayBuffer): Promise<{
	bytes: ArrayBuffer;
	metadata: import('libraw-wasm').Metadata | undefined;
}> {
	const { imageData, metadata } = await decodeRawPhoto(bytes);
 
	console.debug('Decoded raw photo, got metadata:', metadata);
 
	const canvas = new OffscreenCanvas(imageData.width, imageData.height);
	const ctx = canvas.getContext('2d');
	ctx?.putImageData(imageData, 0, 0);
 
	const blob = await canvas.convertToBlob({ type: 'image/jpeg' });
	const buf = await blob.arrayBuffer();
 
	return { bytes: buf, metadata };
}
 
export async function processRawMetadata(
	sessionId: string,
	imageFileId: string,
	metadata: import('libraw-wasm').Metadata
) {
	const session = await tables.Session.get(sessionId);
	if (!session) {
		throw new Error(`Session with id ${sessionId} not found`);
	}
 
	const protocol = await tables.Protocol.get(session.protocol);
	if (!protocol) {
		throw new Error(`Protocol with id ${session.protocol} not found`);
	}
 
	const metadataDefs = await tables.Metadata.list().then((defs) =>
		defs.filter(
			(
				def
			): def is typeof def & {
				infer:
					| { exif: EXIFField }
					| { latitude: { exif: EXIFField }; longitude: { exif: EXIFField } };
			} =>
				protocol.metadata.includes(def.id) && def.infer !== undefined && 'exif' in def.infer
		)
	);
 
	const images = await tables.Image.list('sessionId', sessionId).then((imgs) =>
		imgs.filter((img) => img.fileId === imageFileId)
	);
 
	for (const { id: subjectId } of images) {
		for (const { id: metadataId, infer, type } of metadataDefs) {
			let value: RuntimeValue;
			Iif ('latitude' in infer && 'longitude' in infer) {
				const latitude = findRawMetadataFieldByExifTag(metadata, infer.latitude.exif);
				const longitude = findRawMetadataFieldByExifTag(metadata, infer.longitude.exif);
 
				// Skip if either latitude or longitude is missing
				if (latitude === undefined || longitude === undefined) {
					continue;
				}
 
				value = {
					latitude: coerceExifValue(latitude, 'float'),
					longitude: coerceExifValue(longitude, 'float'),
				};
			} else {
				const rawValue = findRawMetadataFieldByExifTag(metadata, infer.exif);
 
				// Skip if the raw metadata field is not present
				Iif (rawValue === undefined) {
					console.warn(
						`EXIF tag ${infer.exif} not found in metadata for session ${sessionId}, subject ${subjectId}, skipping metadata ${metadataId}`
					);
					continue;
				}
 
				value = coerceExifValue(rawValue, type);
			}
 
			await storeMetadataValue({
				db: await openDatabase(),
				sessionId,
				subjectId,
				metadataId,
				type,
				value,
			});
		}
	}
}
 
export function findRawMetadataFieldByExifTag(
	metadata: import('libraw-wasm').Metadata,
	tag: EXIFField
): number | string | Date | undefined {
	switch (tag) {
		case 'Make':
			return metadata.camera_make;
		case 'Model':
			return metadata.camera_model;
		case 'ISOSpeed':
			return metadata.iso_speed;
		case 'ShutterSpeedValue':
			return metadata.shutter;
		case 'ApertureValue':
			return metadata.aperture;
		case 'FocalLength':
			return metadata.focal_len;
		case 'DateTimeOriginal':
			return metadata.timestamp;
		// XXX: Not sure about that one
		case 'ImageDescription':
			return metadata.desc;
		case 'Artist':
			return metadata.artist;
		case 'GPSAltitude':
			return metadata.gps_data?.altitude;
		// XXX: Find out if there's a way to get the LatitudeRef
		case 'GPSLatitude': {
			Iif (!metadata.gps_data) return undefined;
			return GPSHelper.dmsRationalToDeg(
				metadata.gps_data.latitude.map((v) => [v, 1] as const),
				'N'
			);
		}
		// XXX: Find out if there's a way to get the LongitudeRef
		case 'GPSLongitude': {
			Iif (!metadata.gps_data) return undefined;
			return GPSHelper.dmsRationalToDeg(
				metadata.gps_data.longitude.map((v) => [v, 1] as const),
				'E'
			);
		}
		case 'ExposureIndex':
			return metadata.metadata_common?.exifExposureIndex;
		case 'ColorSpace':
			return metadata.metadata_common?.ColorSpace;
	}
}