All files / lib exif.ts

78.91% Statements 131/166
69.56% Branches 96/138
93.33% Functions 14/15
85.29% Lines 116/136

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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410                                                                          2x 2x       2x 2x     2x 6x     2x   2x 2x         2x   2x 6x     4x   4x 2x 2x   2x 2x   2x               2x       2x   2x     2x           2x 1x                     2x 2x   2x   2x                   4x   3x                                       2x   2x   2x 2x 3x                         2x   2x                 2x   2x 92x 92x   1x       1x                   26x 20x   20x   4x           5x   5x 1x                     4x           4x   3x     1x     2x 1x       6x                 6x   6x 2x     4x       2x 2x 2x 2x     4x             4x     2x 2x   2x   1x                       19x   15x 10x 9x 8x 7x 1x 4x     6x               2x               2x   6x 6x 4x 6x   4x             2x 2x 2x           2x 2x 2x         2x       2x       2x   2x 2x     2x   2x 10x     10x           10x   10x 10x 10x 8x 8x     2x   2x 2x                                   2x 1x 1x   1x    
import type * as DB from './database.js';
import type { ExifFieldKey } from './exiffields.js';
import type { NamespacedMetadataID } from './schemas/common.js';
import type { RuntimeValue } from './schemas/metadata.js';
 
import { type } from 'arktype';
import * as dates from 'date-fns';
import * as exifParser from 'exif-parser';
import piexif from 'piexifjs';
 
import { Schemas } from './database.js';
import { SANE_ISO_DATE_FORMATS, tryParseDate } from './date.js';
import { EXIF_FIELDS, exifParserKeyToRealKey } from './exiffields.js';
import {
	geolocationAccuracyFromMake,
	geolocationAccuracyToConfidence,
	gpsDilutionOfPrecisionToConfidence,
} from './geolocation.js';
import { errorMessage } from './i18n.js';
import * as db from './idb.svelte.js';
import { resolveMetadataImport, storeMetadataValue } from './metadata/index.js';
import { toasts } from './toasts.svelte.js';
import { byteString, byteStringToArray, throwError, transformObject } from './utils.js';
 
export async function processExifData({
	sessionId,
	imageFileId,
	imageBytes,
	file,
	extra,
}: {
	sessionId: string;
	imageFileId: string;
	imageBytes: ArrayBuffer | Buffer;
	file: { type: string; name: string };
	extra?: { [K in ExifFieldKey]?: unknown };
}) {
	const session = await db.tables.Session.get(sessionId);
	Iif (!session) {
		throw new Error(`Session ${sessionId} introuvable`);
	}
 
	const protocol = await db.tables.Protocol.get(session.protocol);
	Iif (!protocol) {
		throw new Error(`Protocole ${session.protocol} introuvable`);
	}
	const metadataOfProtocol = await db.tables.Metadata.getMany(
		protocol.metadata.map((key) => resolveMetadataImport(protocol, key))
	);
 
	const metadataFromExif = {} as Record<NamespacedMetadataID, DB.MetadataValue>;
 
	try {
		const fields = {
			...extra,
			...(await parseExif(imageBytes, file.type)),
		};
 
		console.debug('Processing EXIF fields', fields);
 
		for (const def of metadataOfProtocol ?? []) {
			if (!def.infer) continue;
 
			let coerced: RuntimeValue | undefined;
			let confidence = 1;
 
			if (def.type === 'location') {
				Iif (!def.infer.longitude?.exif) continue;
				Iif (!def.infer.latitude?.exif) continue;
 
				const lngref = `${def.infer.longitude.exif}Ref` as const;
				const latref = `${def.infer.latitude.exif}Ref` as const;
 
				coerced = coerceExifValue('location', {
					longitude: fields[def.infer.longitude.exif],
					longitudeRef: lngref in fields ? fields[lngref as ExifFieldKey] : undefined,
					latitude: fields[def.infer.latitude.exif],
					latitudeRef: latref in fields ? fields[latref as ExifFieldKey] : undefined,
				});
 
				// TODO: could also work with other GPS-related keys, such as GPSDest*
				Eif (
					def.infer.longitude.exif === 'GPSLongitude' &&
					def.infer.latitude.exif === 'GPSLatitude'
				) {
					const dop = coerceExifValue('float', fields.GPSDOP);
					const herr =
						coerceExifValue('float', fields.GPSHPositioningError) ??
						geolocationAccuracyFromMake(coerceExifValue('string', fields.Make));
 
					confidence = Math.min(
						herr !== undefined ? geolocationAccuracyToConfidence(herr) : 1,
						dop !== undefined ? gpsDilutionOfPrecisionToConfidence(dop) : 1
					);
				}
 
				if (!coerced) {
					console.warn(
						`Couldn't coerce EXIF fields to ${def.type}:`,
						def.infer.longitude.exif,
						'=',
						fields[def.infer.longitude.exif],
						def.infer.latitude.exif,
						'=',
						fields[def.infer.latitude.exif]
					);
				}
			} else {
				Iif (!('exif' in def.infer)) continue;
				Iif (!def.infer.exif) continue;
 
				coerced = coerceExifValue(def.type, fields[def.infer.exif], def.infer.exif);
 
				Iif (!coerced) {
					console.warn(
						`Couldn't coerce EXIF field(s) to ${def.type}:`,
						def.infer.exif,
						'=',
						fields[def.infer.exif]
					);
				}
			}
 
			if (!coerced) continue;
 
			metadataFromExif[def.id] = {
				confidence,
				alternatives: [],
				value: coerced,
				confirmed: false,
				manuallyModified: false,
				isDefault: false,
				confidences: {},
			};
		}
	} catch (e) {
		console.warn(e);
		if (file.type === 'image/jpeg') {
			toasts.warn(
				`Impossible d'extraire les métadonnées EXIF de ${file.name}: ${e?.toString() ?? 'Erreur inattendue'}`
			);
		}
		return {};
	}
 
	const images = await db
		.listByIndex('Image', 'sessionId', sessionId)
		.then((imgs) => imgs.filter((img) => img.fileId === imageFileId));
 
	for (const { id: subjectId } of images) {
		for (const [key, { value, confidence }] of Object.entries(metadataFromExif)) {
			await storeMetadataValue({
				db: db.databaseHandle(),
				subjectId,
				sessionId: session.id,
				metadataId: key,
				value,
				confidence,
			});
		}
	}
}
 
async function parseExif(buffer: ArrayBuffer | Buffer, contentType: string) {
	Iif (contentType !== 'image/jpeg') return;
 
	const exif = exifParser
		.create(
			// 2^16 + 100 of margin
			// see https://www.npmjs.com/package/exif-parser#creating-a-parser
			buffer.slice(0, 2 ** 16 + 100)
		)
		.enableImageSize(false)
		.parse();
 
	console.debug('Finished parsing EXIF data from bytes', exif);
 
	return transformObject(exif.tags, (key, value) => {
		try {
			return [exifParserKeyToRealKey(key), value];
		} catch (e) {
			console.warn(
				`Couldn't translate exif-parser field ${key} to a standard EXIF field:`,
				e
			);
			return undefined;
		}
	});
}
 
export function coerceExifValue<T extends DB.MetadataType>(
	coerceTo: T,
	value: unknown,
	field?: ExifFieldKey
): import('./schemas/metadata.js').RuntimeValue<T> | undefined {
	if (value === undefined) return undefined;
	Iif (value === null) return undefined;
 
	switch (coerceTo) {
		case 'string':
			return value?.toString() ?? '';
 
		case 'boolean':
			return Boolean(value);
 
		case 'date':
			Iif (value instanceof Date) return value;
 
			if (typeof value === 'string') {
				return (
					tryParseDate(
						value,
						...SANE_ISO_DATE_FORMATS,
						// EXIF also has some weird date format standards
						'yyyy:MM:dd HH:mm:SS',
						'yyyy:MM:dd'
					) ?? throwError('Date format is invalid')
				);
			}
 
			Iif (typeof value !== 'number') {
				throw new Error(
					`Unexpected type ${typeof value} for a date, cannot coerce exif value`
				);
			}
 
			if (Number.isNaN(value)) throw new Error('Date value is invalid');
 
			return new Date(value * 1e3);
 
		case 'boundingbox':
			throw new Error('Bounding box not supported in EXIF');
 
		case 'enum':
			if (typeof value !== 'string') throw new Error('Enum value must be a string');
			return value;
 
		case 'integer':
		case 'float': {
			Iif (type(['number', 'number']).array().allows(value)) {
				const [[num, denom]] = value;
				const coerced = num / denom;
 
				if (field === 'Temperature') {
					return avoidSentinelTemperature(coerced);
				}
			}
 
			const coerced = Number(value);
 
			if (field === 'Temperature') {
				return avoidSentinelTemperature(coerced);
			}
 
			return coerced;
		}
 
		case 'location': {
			Iif (!value) return;
			Iif (typeof value !== 'object') return;
			Iif (!('longitude' in value)) return;
			Iif (!('latitude' in value)) return;
 
			function coerceCoordinate(coord: unknown, ref: unknown, refFallback: string) {
				Iif (type(['number', 'number']).array().allows(coord)) {
					return piexif.GPSHelper.dmsRationalToDeg(
						coord,
						typeof ref === 'string' ? ref : refFallback
					);
				}
 
				return coerceExifValue('float', coord, field);
			}
 
			const lng = coerceCoordinate(value.longitude, value.longitudeRef, 'E');
			const lat = coerceCoordinate(value.latitude, value.latitudeRef, 'N');
 
			if (!lng || !lat) return;
 
			return { longitude: lng, latitude: lat };
		}
 
		default:
			throw new Error(`Unknown type ${coerceTo}`);
	}
}
 
/**
 * Serialize a value to a string for EXIF writing
 */
export function serializeExifValue(value: unknown): string | unknown[] {
	if (value instanceof Date) return dates.format(value, 'yyyy:MM:dd HH:mm:ss');
	// Let multivalued exif entries through
	if (Array.isArray(value)) return value;
	if (typeof value === 'number') return [value];
	if (value === undefined) return 'undefined';
	if (value === null) return 'null';
	if (typeof value === 'object' && value !== null) {
		return Object.entries(value)
			.map(([key, val]) => `${key}=${val}`)
			.join(';');
	}
	return value?.toString() ?? '';
}
 
export function addExifMetadata(
	bytes: ArrayBuffer | Buffer,
	metadataDefs: DB.Metadata[],
	metadataValues: DB.MetadataValues
): Uint8Array {
	const ExifMetadata = Schemas.Metadata.and({
		infer: [
			{ exif: 'string' },
			'|',
			{ latitude: { exif: 'string' }, longitude: { exif: 'string' } },
		],
	});
 
	const changes: Partial<Record<ExifFieldKey, unknown>> = {};
 
	for (const def of metadataDefs.map((m) => ExifMetadata(m))) {
		if (def instanceof type.errors) continue;
		const value = metadataValues[def.id]?.value;
		Iif (value === undefined) continue;
 
		if (
			type({ latitude: { exif: 'string' }, longitude: { exif: 'string' } }).allows(
				def.infer
			) &&
			type({ latitude: 'number', longitude: 'number' }).allows(value)
		) {
			// XXX harcoded BS :/
			if (def.infer.latitude.exif === 'GPSLatitude') {
				changes['GPSLatitudeRef'] = value.latitude >= 0 ? 'N' : 'S';
				changes['GPSLatitude'] = piexif.GPSHelper.degToDmsRational(value.latitude);
			} else E{
				changes[def.infer.latitude.exif] = value.latitude;
			}
 
			// XXX harcoded BS :/
			if (def.infer.longitude.exif === 'GPSLongitude') {
				changes['GPSLongitudeRef'] = value.longitude >= 0 ? 'E' : 'W';
				changes['GPSLongitude'] = piexif.GPSHelper.degToDmsRational(value.longitude);
			} else E{
				changes[def.infer.longitude.exif] = value.longitude;
			}
		} else {
			changes[def.infer.exif] = value;
		}
	}
 
	return setExifFields(bytes, changes);
}
 
export function setExifFields(bytes: ArrayBuffer, changes: Partial<Record<ExifFieldKey, unknown>>) {
	const bytestring = byteString(new Uint8Array(bytes));
 
	try {
		const exifDict = piexif.load(bytestring);
 
		// Prevent any write if no exif data changed
		let dirty = false;
 
		for (const [key, value] of Object.entries(changes)) {
			const field = EXIF_FIELDS[key];
 
			const [category] =
				Object.entries(exifDict).find(([, tags]) => tags && field in tags) ??
				Object.entries(piexif.TAGS).find(
					([cat, tags]) => cat !== 'Image' && field in tags
				) ??
				[];
 
			Iif (!category) continue;
 
			const serialized = serializeExifValue(value);
			Iif (serialized === undefined) continue;
			if (serialized === exifDict[category][field]) continue;
			exifDict[category][field] = serialized;
			dirty = true;
		}
 
		Iif (!dirty) return new Uint8Array(bytes);
 
		const outputstr = piexif.insert(piexif.dump(exifDict), bytestring);
		return byteStringToArray(outputstr);
	} catch (error) {
		toasts.warn(errorMessage(error, 'Impossible de modifier les données EXIF'));
		return new Uint8Array(buffer);
	}
}
 
/**
 * aperture value = 2 log_2(f number)
 * @see https://www.uniquephoto.com/community/qa/what-is-aperture-value-in-exif-and-how-does-it-relate-to-the-f-number
 */
export function apertureValueToFNumber(aperture: number): number {
	return 2 ** (aperture / 2);
}
 
// son son son sahur 🫩
// See https://gist.github.com/gwennlbh/b907a5fc4e139f12ddb2c677984a4a83#file-img_6072-cr2-json-L190-L195
function avoidSentinelTemperature(value: number | undefined): number | undefined {
	if (value === -1000) {
		console.debug(`Avoiding sentinel value -1000°C for temperature`);
		return undefined;
	}
	return value;
}