the editable site (validation-lab)

This commit is contained in:
kpgarrod committed 2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 files changed
+2227005

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
import {read} from './reader.mjs'
import {undefinedIfEmpty} from './util/helpers.mjs'
import {Options} from './options.mjs'
import {fileParsers, segmentParsers} from './plugins.mjs'
import {throwError} from './util/helpers.mjs'
export class Exifr {
parsers = {}
output = {}
errors = []
pushToErrors = err => this.errors.push(err)
constructor(options) {
this.options = Options.useCached(options)
}
async read(arg) {
this.file = await read(arg, this.options)
}
setup() {
if (this.fileParser) return
// JPEG's exif is based on TIFF structure from .tif files.
// .tif files start with either 49 49 (LE) or 4D 4D (BE) which is also header for the TIFF structure.
// JPEG starts with with FF D8, followed by APP0 and APP1 section (FF E1 + length + 'Exif\0\0' + data) which contains the TIFF structure (49 49 / 4D 4D + data)
let {file} = this
let marker = file.getUint16(0)
for (let [type, FileParser] of fileParsers) {
if (FileParser.canHandle(file, marker)) {
this.fileParser = new FileParser(this.options, this.file, this.parsers)
return file[type] = true
}
}
// setup is called after read, so we need to close potentially open fs
if (this.file.close) this.file.close()
throwError(`Unknown file format`)
}
async parse() {
let {output, errors} = this
this.setup()
// We're try catching here and not inside the executeParsers() because we shouldn't parse
// segments if file parser throws.
if (this.options.silentErrors) {
await this.executeParsers().catch(this.pushToErrors)
errors.push(...this.fileParser.errors)
} else {
await this.executeParsers()
}
if (this.file.close) this.file.close()
if (this.options.silentErrors && errors.length > 0) output.errors = errors
return undefinedIfEmpty(output)
}
// TODO: Silent error handling needs major rework in order to enable reading
// at least some segments while others are corrupted.
// It'd be nice to move more functionality into segment parsers and hollow out
// the file parsers. This way each semgnet would be in own (kinda) thread.
// EXAMPLE1: All the chunk header calculation happens inside file parser.
// If something goes wrong (like bug in IPTC's static canHandle() and headerLength)
// it crashes right in fileParser.parse().
// tldr: file crashes prematurely on IPTC, no other segments are read.
// EXAMPLE2: PNG file parser does a lot of parsing inside its .parse()
// If it crashed, we'd also prematurely close before extracting any data.
async executeParsers() {
let {output} = this
await this.fileParser.parse()
let promises = Object.values(this.parsers).map(async parser => {
let parserOutput = await parser.parse()
// each parser may want to merge its output into global differently.
parser.assignToOutput(output, parserOutput)
})
if (this.options.silentErrors) {
promises = promises.map(promise => promise.catch(this.pushToErrors))
}
await Promise.all(promises)
}
async extractThumbnail() {
this.setup()
let {options, file} = this
let TiffParser = segmentParsers.get('tiff', options)
var seg
if (file.tiff)
seg = {start: 0, type: 'tiff'}
else if (file.jpeg)
seg = await this.fileParser.getOrFindSegment('tiff')
if (seg === undefined) return
let chunk = await this.fileParser.ensureSegmentChunk(seg)
let parser = this.parsers.tiff = new TiffParser(chunk, options, file)
let thumb = await parser.extractThumbnail()
if (file.close) file.close()
return thumb
}
}
+44
View File
@@ -0,0 +1,44 @@
// only full bundle includes Node.js polyfill for fetch()
import '../polyfill/fetch-node.mjs'
export * from './lite.mjs'
import * as lite from './lite.mjs'
export default lite
// Highlevel API: parseSidecar()
export * from '../highlevel/sidecar.mjs'
// File Readers
import '../file-readers/FsReader.mjs'
import '../file-readers/Base64Reader.mjs'
// File Parsers
import '../file-parsers/tiff.mjs'
import '../file-parsers/heif.mjs'
import '../file-parsers/png.mjs'
// TIFF - Additional tags
import '../dicts/tiff-interop-keys.mjs'
import '../dicts/tiff-other-keys.mjs'
import '../dicts/tiff-gps-values.mjs'
// JFIF (JPEG header)
import '../segment-parsers/jfif.mjs'
import '../dicts/jfif-keys.mjs'
// IHDR (PNG header)
import '../segment-parsers/ihdr.mjs'
import '../dicts/ihdr-keys.mjs'
import '../dicts/ihdr-values.mjs'
// ICC
import '../segment-parsers/icc.mjs'
import '../dicts/icc-keys.mjs'
import '../dicts/icc-values.mjs'
// IPTC
import '../segment-parsers/iptc.mjs'
import '../dicts/iptc-keys.mjs'
import '../dicts/iptc-values.mjs'
+30
View File
@@ -0,0 +1,30 @@
export * from './mini.mjs'
import * as mini from './mini.mjs'
export default mini
// File Readers
import '../file-readers/UrlFetcher.mjs'
import '../file-readers/BlobReader.mjs'
// File Parser
import '../file-parsers/jpeg.mjs'
import '../file-parsers/heif.mjs'
// TIFF Parser
import '../segment-parsers/tiff-exif.mjs'
// TIFF Keys
import '../dicts/tiff-ifd0-keys.mjs'
import '../dicts/tiff-exif-keys.mjs'
import '../dicts/tiff-gps-keys.mjs'
// TIFF Values
import '../dicts/tiff-ifd0-values.mjs'
import '../dicts/tiff-exif-values.mjs'
// TIFF Revivers
import '../dicts/tiff-revivers.mjs'
// XMP
import '../segment-parsers/xmp.mjs'
+18
View File
@@ -0,0 +1,18 @@
export * from './nano.mjs'
import * as nano from './nano.mjs'
export default nano
// Highlevel API: gps(), thumbnail(), thumbnailUrl(), orientation(), rotation()
export * from '../highlevel/gps.mjs'
export * from '../highlevel/thumb.mjs'
export * from '../highlevel/orientation.mjs'
// File Readers
import '../file-readers/BlobReader.mjs'
// File Parser
import '../file-parsers/jpeg.mjs'
// TIFF Parser
import '../segment-parsers/tiff-exif.mjs'
+10
View File
@@ -0,0 +1,10 @@
export * from '../core.mjs'
import * as core from '../core.mjs'
export default core
// File Parser
import '../file-parsers/jpeg.mjs'
// TIFF Parser
import '../segment-parsers/tiff-exif.mjs'
+17
View File
@@ -0,0 +1,17 @@
// Exports from the depths of the library
export {Exifr} from './Exifr.mjs'
// for advanced users
export * from './options.mjs'
export {fileParsers, segmentParsers, fileReaders} from './plugins.mjs'
export {tagKeys, tagValues, tagRevivers, createDictionary, extendDictionary} from './tags.mjs'
// undocumented, needed for demo page and tests
export {fetchUrlAsArrayBuffer, readBlobAsArrayBuffer} from './reader.mjs'
import {Exifr} from './Exifr.mjs'
export async function parse(input, options) {
let exr = new Exifr(options)
await exr.read(input)
return exr.parse()
}
+86
View File
@@ -0,0 +1,86 @@
import {tagKeys, createDictionary} from '../tags.mjs'
// https://exiftool.org/TagNames/ICC_Profile.html
createDictionary(tagKeys, 'icc', [
// Header Tags
[4, 'ProfileCMMType'],
[8, 'ProfileVersion'],
[12, 'ProfileClass'],
[16, 'ColorSpaceData'],
[20, 'ProfileConnectionSpace'],
[24, 'ProfileDateTime'],
[36, 'ProfileFileSignature'],
[40, 'PrimaryPlatform'],
[44, 'CMMFlags'],
[48, 'DeviceManufacturer'],
[52, 'DeviceModel'],
[56, 'DeviceAttributes'],
[64, 'RenderingIntent'],
[68, 'ConnectionSpaceIlluminant'],
[80, 'ProfileCreator'],
[84, 'ProfileID'],
// Other Tags
['Header', 'ProfileHeader'],
['MS00', 'WCSProfiles'],
['bTRC', 'BlueTRC'],
['bXYZ', 'BlueMatrixColumn'],
['bfd', 'UCRBG'],
['bkpt', 'MediaBlackPoint'],
['calt', 'CalibrationDateTime'],
['chad', 'ChromaticAdaptation'],
['chrm', 'Chromaticity'],
['ciis', 'ColorimetricIntentImageState'],
['clot', 'ColorantTableOut'],
['clro', 'ColorantOrder'],
['clrt', 'ColorantTable'],
['cprt', 'ProfileCopyright'],
['crdi', 'CRDInfo'],
['desc', 'ProfileDescription'],
['devs', 'DeviceSettings'],
['dmdd', 'DeviceModelDesc'],
['dmnd', 'DeviceMfgDesc'],
['dscm', 'ProfileDescriptionML'],
['fpce', 'FocalPlaneColorimetryEstimates'],
['gTRC', 'GreenTRC'],
['gXYZ', 'GreenMatrixColumn'],
['gamt', 'Gamut'],
['kTRC', 'GrayTRC'],
['lumi', 'Luminance'],
['meas', 'Measurement'],
['meta', 'Metadata'],
['mmod', 'MakeAndModel'],
['ncl2', 'NamedColor2'],
['ncol', 'NamedColor'],
['ndin', 'NativeDisplayInfo'],
['pre0', 'Preview0'],
['pre1', 'Preview1'],
['pre2', 'Preview2'],
['ps2i', 'PS2RenderingIntent'],
['ps2s', 'PostScript2CSA'],
['psd0', 'PostScript2CRD0'],
['psd1', 'PostScript2CRD1'],
['psd2', 'PostScript2CRD2'],
['psd3', 'PostScript2CRD3'],
['pseq', 'ProfileSequenceDesc'],
['psid', 'ProfileSequenceIdentifier'],
['psvm', 'PS2CRDVMSize'],
['rTRC', 'RedTRC'],
['rXYZ', 'RedMatrixColumn'],
['resp', 'OutputResponse'],
['rhoc', 'ReflectionHardcopyOrigColorimetry'],
['rig0', 'PerceptualRenderingIntentGamut'],
['rig2', 'SaturationRenderingIntentGamut'],
['rpoc', 'ReflectionPrintOutputColorimetry'],
['sape', 'SceneAppearanceEstimates'],
['scoe', 'SceneColorimetryEstimates'],
['scrd', 'ScreeningDesc'],
['scrn', 'Screening'],
['targ', 'CharTarget'],
['tech', 'Technology'],
['vcgt', 'VideoCardGamma'],
['view', 'ViewingConditions'],
['vued', 'ViewingCondDesc'],
['wtpt', 'MediaWhitePoint'],
])
+341
View File
@@ -0,0 +1,341 @@
import {tagValues, createDictionary} from '../tags.mjs'
// inspired by & slightly modified from
// https://exiftool.org/TagNames/ICC_Profile.html
const companies = {
'4d2p': 'Erdt Systems',
AAMA: 'Aamazing Technologies',
ACER: 'Acer',
ACLT: 'Acolyte Color Research',
ACTI: 'Actix Sytems',
ADAR: 'Adara Technology',
ADBE: 'Adobe',
ADI: 'ADI Systems',
AGFA: 'Agfa Graphics',
ALMD: 'Alps Electric',
ALPS: 'Alps Electric',
ALWN: 'Alwan Color Expertise',
AMTI: 'Amiable Technologies',
AOC: 'AOC International',
APAG: 'Apago',
APPL: 'Apple Computer',
AST: 'AST',
'AT&T': 'AT&T',
BAEL: 'BARBIERI electronic',
BRCO: 'Barco NV',
BRKP: 'Breakpoint',
BROT: 'Brother',
BULL: 'Bull',
BUS: 'Bus Computer Systems',
'C-IT': 'C-Itoh',
CAMR: 'Intel',
CANO: 'Canon',
CARR: 'Carroll Touch',
CASI: 'Casio',
CBUS: 'Colorbus PL',
CEL: 'Crossfield',
CELx: 'Crossfield',
CGS: 'CGS Publishing Technologies International',
CHM: 'Rochester Robotics',
CIGL: 'Colour Imaging Group, London',
CITI: 'Citizen',
CL00: 'Candela',
CLIQ: 'Color IQ',
CMCO: 'Chromaco',
CMiX: 'CHROMiX',
COLO: 'Colorgraphic Communications',
COMP: 'Compaq',
COMp: 'Compeq/Focus Technology',
CONR: 'Conrac Display Products',
CORD: 'Cordata Technologies',
CPQ: 'Compaq',
CPRO: 'ColorPro',
CRN: 'Cornerstone',
CTX: 'CTX International',
CVIS: 'ColorVision',
CWC: 'Fujitsu Laboratories',
DARI: 'Darius Technology',
DATA: 'Dataproducts',
DCP: 'Dry Creek Photo',
DCRC: 'Digital Contents Resource Center, Chung-Ang University',
DELL: 'Dell Computer',
DIC: 'Dainippon Ink and Chemicals',
DICO: 'Diconix',
DIGI: 'Digital',
'DL&C': 'Digital Light & Color',
DPLG: 'Doppelganger',
DS: 'Dainippon Screen',
DSOL: 'DOOSOL',
DUPN: 'DuPont',
EPSO: 'Epson',
ESKO: 'Esko-Graphics',
ETRI: 'Electronics and Telecommunications Research Institute',
EVER: 'Everex Systems',
EXAC: 'ExactCODE',
Eizo: 'Eizo',
FALC: 'Falco Data Products',
FF: 'Fuji Photo Film',
FFEI: 'FujiFilm Electronic Imaging',
FNRD: 'Fnord Software',
FORA: 'Fora',
FORE: 'Forefront Technology',
FP: 'Fujitsu',
FPA: 'WayTech Development',
FUJI: 'Fujitsu',
FX: 'Fuji Xerox',
GCC: 'GCC Technologies',
GGSL: 'Global Graphics Software',
GMB: 'Gretagmacbeth',
GMG: 'GMG',
GOLD: 'GoldStar Technology',
GOOG: 'Google',
GPRT: 'Giantprint',
GTMB: 'Gretagmacbeth',
GVC: 'WayTech Development',
GW2K: 'Sony',
HCI: 'HCI',
HDM: 'Heidelberger Druckmaschinen',
HERM: 'Hermes',
HITA: 'Hitachi America',
HP: 'Hewlett-Packard',
HTC: 'Hitachi',
HiTi: 'HiTi Digital',
IBM: 'IBM',
IDNT: 'Scitex',
IEC: 'Hewlett-Packard',
IIYA: 'Iiyama North America',
IKEG: 'Ikegami Electronics',
IMAG: 'Image Systems',
IMI: 'Ingram Micro',
INTC: 'Intel',
INTL: 'N/A (INTL)',
INTR: 'Intra Electronics',
IOCO: 'Iocomm International Technology',
IPS: 'InfoPrint Solutions Company',
IRIS: 'Scitex',
ISL: 'Ichikawa Soft Laboratory',
ITNL: 'N/A (ITNL)',
IVM: 'IVM',
IWAT: 'Iwatsu Electric',
Idnt: 'Scitex',
Inca: 'Inca Digital Printers',
Iris: 'Scitex',
JPEG: 'Joint Photographic Experts Group',
JSFT: 'Jetsoft Development',
JVC: 'JVC Information Products',
KART: 'Scitex',
KFC: 'KFC Computek Components',
KLH: 'KLH Computers',
KMHD: 'Konica Minolta',
KNCA: 'Konica',
KODA: 'Kodak',
KYOC: 'Kyocera',
Kart: 'Scitex',
LCAG: 'Leica',
LCCD: 'Leeds Colour',
LDAK: 'Left Dakota',
LEAD: 'Leading Technology',
LEXM: 'Lexmark International',
LINK: 'Link Computer',
LINO: 'Linotronic',
LITE: 'Lite-On',
Leaf: 'Leaf',
Lino: 'Linotronic',
MAGC: 'Mag Computronic',
MAGI: 'MAG Innovision',
MANN: 'Mannesmann',
MICN: 'Micron Technology',
MICR: 'Microtek',
MICV: 'Microvitec',
MINO: 'Minolta',
MITS: 'Mitsubishi Electronics America',
MITs: 'Mitsuba',
MNLT: 'Minolta',
MODG: 'Modgraph',
MONI: 'Monitronix',
MONS: 'Monaco Systems',
MORS: 'Morse Technology',
MOTI: 'Motive Systems',
MSFT: 'Microsoft',
MUTO: 'MUTOH INDUSTRIES',
Mits: 'Mitsubishi Electric',
NANA: 'NANAO',
NEC: 'NEC',
NEXP: 'NexPress Solutions',
NISS: 'Nissei Sangyo America',
NKON: 'Nikon',
NONE: 'none',
OCE: 'Oce Technologies',
OCEC: 'OceColor',
OKI: 'Oki',
OKID: 'Okidata',
OKIP: 'Okidata',
OLIV: 'Olivetti',
OLYM: 'Olympus',
ONYX: 'Onyx Graphics',
OPTI: 'Optiquest',
PACK: 'Packard Bell',
PANA: 'Matsushita Electric Industrial',
PANT: 'Pantone',
PBN: 'Packard Bell',
PFU: 'PFU',
PHIL: 'Philips Consumer Electronics',
PNTX: 'HOYA',
POne: 'Phase One A/S',
PREM: 'Premier Computer Innovations',
PRIN: 'Princeton Graphic Systems',
PRIP: 'Princeton Publishing Labs',
QLUX: 'Hong Kong',
QMS: 'QMS',
QPCD: 'QPcard AB',
QUAD: 'QuadLaser',
QUME: 'Qume',
RADI: 'Radius',
RDDx: 'Integrated Color Solutions',
RDG: 'Roland DG',
REDM: 'REDMS Group',
RELI: 'Relisys',
RGMS: 'Rolf Gierling Multitools',
RICO: 'Ricoh',
RNLD: 'Edmund Ronald',
ROYA: 'Royal',
RPC: 'Ricoh Printing Systems',
RTL: 'Royal Information Electronics',
SAMP: 'Sampo',
SAMS: 'Samsung',
SANT: 'Jaime Santana Pomares',
SCIT: 'Scitex',
SCRN: 'Dainippon Screen',
SDP: 'Scitex',
SEC: 'Samsung',
SEIK: 'Seiko Instruments',
SEIk: 'Seikosha',
SGUY: 'ScanGuy.com',
SHAR: 'Sharp Laboratories',
SICC: 'International Color Consortium',
SONY: 'Sony',
SPCL: 'SpectraCal',
STAR: 'Star',
STC: 'Sampo Technology',
Scit: 'Scitex',
Sdp: 'Scitex',
Sony: 'Sony',
TALO: 'Talon Technology',
TAND: 'Tandy',
TATU: 'Tatung',
TAXA: 'TAXAN America',
TDS: 'Tokyo Denshi Sekei',
TECO: 'TECO Information Systems',
TEGR: 'Tegra',
TEKT: 'Tektronix',
TI: 'Texas Instruments',
TMKR: 'TypeMaker',
TOSB: 'Toshiba',
TOSH: 'Toshiba',
TOTK: 'TOTOKU ELECTRIC',
TRIU: 'Triumph',
TSBT: 'Toshiba',
TTX: 'TTX Computer Products',
TVM: 'TVM Professional Monitor',
TW: 'TW Casper',
ULSX: 'Ulead Systems',
UNIS: 'Unisys',
UTZF: 'Utz Fehlau & Sohn',
VARI: 'Varityper',
VIEW: 'Viewsonic',
VISL: 'Visual communication',
VIVO: 'Vivo Mobile Communication',
WANG: 'Wang',
WLBR: 'Wilbur Imaging',
WTG2: 'Ware To Go',
WYSE: 'WYSE Technology',
XERX: 'Xerox',
XRIT: 'X-Rite',
ZRAN: 'Zoran',
Zebr: 'Zebra Technologies',
appl: 'Apple Computer',
bICC: 'basICColor',
berg: 'bergdesign',
ceyd: 'Integrated Color Solutions',
clsp: 'MacDermid ColorSpan',
ds: 'Dainippon Screen',
dupn: 'DuPont',
ffei: 'FujiFilm Electronic Imaging',
flux: 'FluxData',
iris: 'Scitex',
kart: 'Scitex',
lcms: 'Little CMS',
lino: 'Linotronic',
none: 'none',
ob4d: 'Erdt Systems',
obic: 'Medigraph',
quby: 'Qubyx Sarl',
scit: 'Scitex',
scrn: 'Dainippon Screen',
sdp: 'Scitex',
siwi: 'SIWI GRAFIKA',
yxym: 'YxyMaster',
}
// 12 ProfileClass
const devices = {
scnr: 'Scanner',
mntr: 'Monitor',
prtr: 'Printer',
link: 'Device Link',
abst: 'Abstract',
spac: 'Color Space Conversion Profile',
nmcl: 'Named Color',
cenc: 'ColorEncodingSpace profile',
mid: 'MultiplexIdentification profile',
mlnk: 'MultiplexLink profile',
mvis: 'MultiplexVisualization profile',
nkpf: 'Nikon Input Device Profile (NON-STANDARD!)',
}
const tech = {
amd: 'Active Matrix Display',
crt: 'Cathode Ray Tube Display',
kpcd: 'Photo CD',
pmd: 'Passive Matrix Display',
dcam: 'Digital Camera',
dcpj: 'Digital Cinema Projector',
dmpc: 'Digital Motion Picture Camera',
dsub: 'Dye Sublimation Printer',
epho: 'Electrophotographic Printer',
esta: 'Electrostatic Printer',
flex: 'Flexography',
fprn: 'Film Writer',
fscn: 'Film Scanner',
grav: 'Gravure',
ijet: 'Ink Jet Printer',
imgs: 'Photo Image Setter',
mpfr: 'Motion Picture Film Recorder',
mpfs: 'Motion Picture Film Scanner',
offs: 'Offset Lithography',
pjtv: 'Projection Television',
rpho: 'Photographic Paper Printer',
rscn: 'Reflective Scanner',
silk: 'Silkscreen',
twax: 'Thermal Wax Printer',
vidc: 'Video Camera',
vidm: 'Video Monitor',
}
createDictionary(tagValues, 'icc', [
[4, companies],
[12, devices],
[40, Object.assign({}, companies, devices)],
[48, companies],
[80, companies],
[64, {
0: 'Perceptual',
1: 'Relative Colorimetric',
2: 'Saturation',
3: 'Absolute Colorimetric',
}],
['tech', tech],
])
+16
View File
@@ -0,0 +1,16 @@
import {tagKeys, createDictionary} from '../tags.mjs'
// PNG Header Tags
// the number is not a tag code but an offset in buffer (standard png header)
// so there's no missing 1,2,3,5,6,7, etc... tag
createDictionary(tagKeys, 'ihdr', [
[0, 'ImageWidth'],
[4, 'ImageHeight'],
[8, 'BitDepth'],
[9, 'ColorType'],
[10, 'Compression'],
[11, 'Filter'],
[12, 'Interlace'],
])
+32
View File
@@ -0,0 +1,32 @@
import {tagValues, createDictionary} from '../tags.mjs'
// PNG Header Tags
createDictionary(tagValues, 'ihdr', [
[9, {
0: 'Grayscale',
2: 'RGB',
3: 'Palette',
4: 'Grayscale with Alpha',
6: 'RGB with Alpha',
DEFAULT: 'Unknown',
}],
[10, {
0: 'Deflate/Inflate',
DEFAULT: 'Unknown',
}],
[11, {
0: 'Adaptive',
DEFAULT: 'Unknown',
}],
[12, {
0: 'Noninterlaced',
1: 'Adam7 Interlace',
DEFAULT: 'Unknown',
}],
])
+78
View File
@@ -0,0 +1,78 @@
import {tagKeys, createDictionary} from '../tags.mjs'
// Slightly modified version of
// https://exiftool.org/TagNames/IPTC.html
createDictionary(tagKeys, 'iptc', [
[0, 'ApplicationRecordVersion'],
[3, 'ObjectTypeReference'],
[4, 'ObjectAttributeReference'],
[5, 'ObjectName'],
[7, 'EditStatus'],
[8, 'EditorialUpdate'],
[10, 'Urgency'],
[12, 'SubjectReference'],
[15, 'Category'],
[20, 'SupplementalCategories'],
[22, 'FixtureIdentifier'],
[25, 'Keywords'],
[26, 'ContentLocationCode'],
[27, 'ContentLocationName'],
[30, 'ReleaseDate'],
[35, 'ReleaseTime'],
[37, 'ExpirationDate'],
[38, 'ExpirationTime'],
[40, 'SpecialInstructions'],
[42, 'ActionAdvised'],
[45, 'ReferenceService'],
[47, 'ReferenceDate'],
[50, 'ReferenceNumber'],
[55, 'DateCreated'],
[60, 'TimeCreated'],
[62, 'DigitalCreationDate'],
[63, 'DigitalCreationTime'],
[65, 'OriginatingProgram'],
[70, 'ProgramVersion'],
[75, 'ObjectCycle'],
[80, 'Byline'],
[85, 'BylineTitle'],
[90, 'City'],
[92, 'Sublocation'],
[95, 'State'], // Province-State
[100, 'CountryCode'], // Country-PrimaryLocationCode
[101, 'Country'], // Country-PrimaryLocationName
[103, 'OriginalTransmissionReference'],
[105, 'Headline'],
[110, 'Credit'],
[115, 'Source'],
[116, 'CopyrightNotice'],
[118, 'Contact'],
[120, 'Caption'], // Caption-Abstract
[121, 'LocalCaption'],
[122, 'Writer'], // Writer-Editor
[125, 'RasterizedCaption'],
[130, 'ImageType'],
[131, 'ImageOrientation'],
[135, 'LanguageIdentifier'],
[150, 'AudioType'],
[151, 'AudioSamplingRate'],
[152, 'AudioSamplingResolution'],
[153, 'AudioDuration'],
[154, 'AudioOutcue'],
[184, 'JobID'],
[185, 'MasterDocumentID'],
[186, 'ShortDocumentID'],
[187, 'UniqueDocumentID'],
[188, 'OwnerID'],
[200, 'ObjectPreviewFileFormat'],
[201, 'ObjectPreviewFileVersion'],
[202, 'ObjectPreviewData'],
[221, 'Prefs'],
[225, 'ClassifyState'],
[228, 'SimilarityIndex'],
[230, 'DocumentNotes'],
[231, 'DocumentHistory'],
[232, 'ExifCameraInfo'],
[255, 'CatalogSets'],
])
+92
View File
@@ -0,0 +1,92 @@
import {tagValues, createDictionary} from '../tags.mjs'
// Taken from
// https://exiftool.org/TagNames/IPTC.html
createDictionary(tagValues, 'iptc', [
[10, {
0: '0 (reserved)',
1: '1 (most urgent)',
2: '2',
3: '3',
4: '4',
5: '5 (normal urgency)',
6: '6',
7: '7',
8: '8 (least urgent)',
9: '9 (user-defined priority)',
}],
// TODO 42
[75, {
'a': 'Morning',
'b': 'Both Morning and Evening',
'p': 'Evening',
}],
[131, {
'L': 'Landscape',
'P': 'Portrait',
'S': 'Square',
}],
// not useful in images
/*
[150, {
'0T': 'Text Only',
'1A': 'Mono Actuality',
'1C': 'Mono Question and Answer Session',
'1M': 'Mono Music',
'1Q': 'Mono Response to a Question',
'1R': 'Mono Raw Sound',
'1S': 'Mono Scener',
'1V': 'Mono Voicer',
'1W': 'Mono Wrap',
'2A': 'Stereo Actuality',
'2C': 'Stereo Question and Answer Session',
'2M': 'Stereo Music',
'2Q': 'Stereo Response to a Question',
'2R': 'Stereo Raw Sound',
'2S': 'Stereo Scener',
'2V': 'Stereo Voicer',
'2W': 'Stereo Wrap',
}],
[200, {
0: 'No ObjectData',
1: 'IPTC-NAA Digital Newsphoto Parameter Record',
2: 'IPTC7901 Recommended Message Format',
3: 'Tagged Image File Format (Adobe/Aldus Image data)',
4: 'Illustrator (Adobe Graphics data)',
5: 'AppleSingle (Apple Computer Inc)',
6: 'NAA 89-3 (ANPA 1312)',
7: 'MacBinary II',
8: 'IPTC Unstructured Character Oriented File Format (UCOFF)',
9: 'United Press International ANPA 1312 variant',
10: 'United Press International Down-Load Message',
11: 'JPEG File Interchange (JFIF)',
12: 'Photo-CD Image-Pac (Eastman Kodak)',
13: 'Bit Mapped Graphics File [.BMP] (Microsoft)',
14: 'Digital Audio File [.WAV] (Microsoft & Creative Labs)',
15: 'Audio plus Moving Video [.AVI] (Microsoft)',
16: 'PC DOS/Windows Executable Files [.COM][.EXE]',
17: 'Compressed Binary File [.ZIP] (PKWare Inc)',
18: 'Audio Interchange File Format AIFF (Apple Computer Inc)',
19: 'RIFF Wave (Microsoft Corporation)',
20: 'Freehand (Macromedia/Aldus)',
21: 'Hypertext Markup Language [.HTML] (The Internet Society)',
22: 'MPEG 2 Audio Layer 2 (Musicom), ISO/IEC',
23: 'MPEG 2 Audio Layer 3, ISO/IEC',
24: 'Portable Document File [.PDF] Adobe',
25: 'News Industry Text Format (NITF)',
26: 'Tape Archive [.TAR]',
27: 'Tidningarnas Telegrambyra NITF version (TTNITF DTD)',
28: 'Ritzaus Bureau NITF version (RBNITF DTD)',
29: 'Corel Draw [.CDR]',
}],
*/
])
+15
View File
@@ -0,0 +1,15 @@
import {tagKeys, createDictionary} from '../tags.mjs'
// JPEG Header Tags
// the number is not a tag code but an offset in buffer (standard jpg header)
// so there's no missing 1,2,3,5,6,7, etc... tag
createDictionary(tagKeys, 'jfif', [
[0, 'JFIFVersion'],
[2, 'ResolutionUnit'],
[3, 'XResolution'],
[5, 'YResolution'],
[7, 'ThumbnailWidth'],
[8, 'ThumbnailHeight']
])
+113
View File
@@ -0,0 +1,113 @@
import {tagKeys, createDictionary} from '../tags.mjs'
// inspired by
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
// TODO: check and add missing ones from:
// https://metacpan.org/pod/distribution/Image-ExifTool/lib/Image/ExifTool/TagNames.pod#EXIF-Tags
// https://metacpan.org/pod/Image::MetaData::JPEG::TagLists#Exif-tags-for-the-0th-IFD-Exif-private-subdirectory
createDictionary(tagKeys, 'exif', [
[0x829a, 'ExposureTime'],
[0x829d, 'FNumber'],
[0x8822, 'ExposureProgram'],
[0x8824, 'SpectralSensitivity'],
[0x8827, 'ISO'],
[0x882a, 'TimeZoneOffset'],
[0x882b, 'SelfTimerMode'],
[0x8830, 'SensitivityType'],
[0x8831, 'StandardOutputSensitivity'],
[0x8832, 'RecommendedExposureIndex'],
[0x8833, 'ISOSpeed'],
[0x8834, 'ISOSpeedLatitudeyyy'],
[0x8835, 'ISOSpeedLatitudezzz'],
[0x9000, 'ExifVersion'],
[0x9003, 'DateTimeOriginal'],
[0x9004, 'CreateDate'],
[0x9009, 'GooglePlusUploadCode'],
[0x9010, 'OffsetTime'],
[0x9011, 'OffsetTimeOriginal'],
[0x9012, 'OffsetTimeDigitized'],
[0x9101, 'ComponentsConfiguration'],
[0x9102, 'CompressedBitsPerPixel'],
[0x9201, 'ShutterSpeedValue'],
[0x9202, 'ApertureValue'],
[0x9203, 'BrightnessValue'],
[0x9204, 'ExposureCompensation'],
[0x9205, 'MaxApertureValue'],
[0x9206, 'SubjectDistance'],
[0x9207, 'MeteringMode'],
[0x9208, 'LightSource'],
[0x9209, 'Flash'],
[0x920a, 'FocalLength'],
[0x9211, 'ImageNumber'],
[0x9212, 'SecurityClassification'],
[0x9213, 'ImageHistory'],
[0x9214, 'SubjectArea'],
[0x927c, 'MakerNote'],
[0x9286, 'UserComment'],
[0x9290, 'SubSecTime'],
[0x9291, 'SubSecTimeOriginal'],
[0x9292, 'SubSecTimeDigitized'],
[0x9400, 'AmbientTemperature'],
[0x9401, 'Humidity'],
[0x9402, 'Pressure'],
[0x9403, 'WaterDepth'],
[0x9404, 'Acceleration'],
[0x9405, 'CameraElevationAngle'],
[0xa000, 'FlashpixVersion'],
[0xa001, 'ColorSpace'],
[0xa002, 'ExifImageWidth'],
[0xa003, 'ExifImageHeight'],
[0xa004, 'RelatedSoundFile'],
[0xa20b, 'FlashEnergy'],
[0xa20e, 'FocalPlaneXResolution'],
[0xa20f, 'FocalPlaneYResolution'],
[0xa210, 'FocalPlaneResolutionUnit'],
[0xa214, 'SubjectLocation'],
[0xa215, 'ExposureIndex'],
[0xa217, 'SensingMethod'],
[0xa300, 'FileSource'],
[0xa301, 'SceneType'],
[0xa302, 'CFAPattern'],
[0xa401, 'CustomRendered'],
[0xa402, 'ExposureMode'],
[0xa403, 'WhiteBalance'],
[0xa404, 'DigitalZoomRatio'],
[0xa405, 'FocalLengthIn35mmFormat'],
[0xa406, 'SceneCaptureType'],
[0xa407, 'GainControl'],
[0xa408, 'Contrast'],
[0xa409, 'Saturation'],
[0xa40a, 'Sharpness'],
[0xa40c, 'SubjectDistanceRange'],
[0xa420, 'ImageUniqueID'],
[0xa430, 'OwnerName'],
[0xa431, 'SerialNumber'],
[0xa432, 'LensInfo'],
[0xa433, 'LensMake'],
[0xa434, 'LensModel'],
[0xa435, 'LensSerialNumber'],
[0xa460, 'CompositeImage'],
[0xa461, 'CompositeImageCount'],
[0xa462, 'CompositeImageExposureTimes'],
[0xa500, 'Gamma'],
[0xea1c, 'Padding'],
[0xea1d, 'OffsetSchema'],
[0xfde8, 'OwnerName'],
[0xfde9, 'SerialNumber'],
[0xfdea, 'Lens'],
[0xfe4c, 'RawFile'],
[0xfe4d, 'Converter'],
[0xfe4e, 'WhiteBalance'],
[0xfe51, 'Exposure'],
[0xfe52, 'Shadows'],
[0xfe53, 'Brightness'],
[0xfe54, 'Contrast'],
[0xfe55, 'Saturation'],
[0xfe56, 'Sharpness'],
[0xfe57, 'Smoothness'],
[0xfe58, 'MoireFilter'],
// not actually assigned to IFD0 but offten found here
[0xa005, 'InteropIFD'],
])
+195
View File
@@ -0,0 +1,195 @@
import {tagValues, createDictionary} from '../tags.mjs'
let exif = createDictionary(tagValues, 'exif', [
// ExposureProgram
[0x8822, {
0: 'Not defined',
1: 'Manual',
2: 'Normal program',
3: 'Aperture priority',
4: 'Shutter priority',
5: 'Creative program',
6: 'Action program',
7: 'Portrait mode',
8: 'Landscape mode'
}],
// ComponentsConfiguration
[0x9101, {
0: '-',
1: 'Y',
2: 'Cb',
3: 'Cr',
4: 'R',
5: 'G',
6: 'B'
}],
// MeteringMode
[0x9207, {
0: 'Unknown',
1: 'Average',
2: 'CenterWeightedAverage',
3: 'Spot',
4: 'MultiSpot',
5: 'Pattern',
6: 'Partial',
255: 'Other'
}],
// LightSource
[0x9208, {
0: 'Unknown',
1: 'Daylight',
2: 'Fluorescent',
3: 'Tungsten (incandescent light)',
4: 'Flash',
9: 'Fine weather',
10: 'Cloudy weather',
11: 'Shade',
12: 'Daylight fluorescent (D 5700 - 7100K)',
13: 'Day white fluorescent (N 4600 - 5400K)',
14: 'Cool white fluorescent (W 3900 - 4500K)',
15: 'White fluorescent (WW 3200 - 3700K)',
17: 'Standard light A',
18: 'Standard light B',
19: 'Standard light C',
20: 'D55',
21: 'D65',
22: 'D75',
23: 'D50',
24: 'ISO studio tungsten',
255: 'Other'
}],
// Flash
[0x9209, {
0x00: 'Flash did not fire',
0x01: 'Flash fired',
0x05: 'Strobe return light not detected',
0x07: 'Strobe return light detected',
0x09: 'Flash fired, compulsory flash mode',
0x0D: 'Flash fired, compulsory flash mode, return light not detected',
0x0F: 'Flash fired, compulsory flash mode, return light detected',
0x10: 'Flash did not fire, compulsory flash mode',
0x18: 'Flash did not fire, auto mode',
0x19: 'Flash fired, auto mode',
0x1D: 'Flash fired, auto mode, return light not detected',
0x1F: 'Flash fired, auto mode, return light detected',
0x20: 'No flash function',
0x41: 'Flash fired, red-eye reduction mode',
0x45: 'Flash fired, red-eye reduction mode, return light not detected',
0x47: 'Flash fired, red-eye reduction mode, return light detected',
0x49: 'Flash fired, compulsory flash mode, red-eye reduction mode',
0x4D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
0x4F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
0x59: 'Flash fired, auto mode, red-eye reduction mode',
0x5D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
0x5F: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
}],
// SensingMethod
[0xa217, {
1: 'Not defined',
2: 'One-chip color area sensor',
3: 'Two-chip color area sensor',
4: 'Three-chip color area sensor',
5: 'Color sequential area sensor',
7: 'Trilinear sensor',
8: 'Color sequential linear sensor'
}],
// FileSource
[0xa300, {
1: 'Film Scanner',
2: 'Reflection Print Scanner',
3: 'Digital Camera',
}],
// SceneType
[0xa301, {
1: 'Directly photographed'
}],
// CustomRendered
[0xa401, {
0: 'Normal',
1: 'Custom',
2: 'HDR (no original saved)',
3: 'HDR (original saved)',
4: 'Original (for HDR)',
6: 'Panorama',
7: 'Portrait HDR',
8: 'Portrait',
}],
// ExposureMode
[0xa402, {
0: 'Auto',
1: 'Manual',
2: 'Auto bracket',
}],
// WhiteBalance
[0xa403, {
0: 'Auto',
1: 'Manual'
}],
// SceneCaptureType
[0xa406, {
0: 'Standard',
1: 'Landscape',
2: 'Portrait',
3: 'Night',
4: 'Other',
}],
// GainControl
[0xa407, {
0: 'None',
1: 'Low gain up',
2: 'High gain up',
3: 'Low gain down',
4: 'High gain down'
}],
// SubjectDistanceRange
[0xa40c, {
0: 'Unknown',
1: 'Macro',
2: 'Close',
3: 'Distant'
}],
// CompositeImage
[0xa460, {
0: 'Unknown',
1: 'Not a Composite Image',
2: 'General Composite Image',
3: 'Composite Image Captured While Shooting',
}],
])
// FocalPlaneResolutionUnit
const shared1 = {
1: 'No absolute unit of measurement',
2: 'Inch',
3: 'Centimeter',
}
exif.set(0x9210, shared1)
exif.set(0xa210, shared1)
// Contrast, Saturation, Sharpness
const shared2 = {
0: 'Normal',
1: 'Low',
2: 'High'
}
exif.set(0xa408, shared2)
exif.set(0xa409, shared2)
exif.set(0xa40a, shared2)
+37
View File
@@ -0,0 +1,37 @@
import {tagKeys, createDictionary} from '../tags.mjs'
createDictionary(tagKeys, 'gps', [
[0x0000, 'GPSVersionID'],
[0x0001, 'GPSLatitudeRef'],
[0x0002, 'GPSLatitude'],
[0x0003, 'GPSLongitudeRef'],
[0x0004, 'GPSLongitude'],
[0x0005, 'GPSAltitudeRef'],
[0x0006, 'GPSAltitude'],
[0x0007, 'GPSTimeStamp'],
[0x0008, 'GPSSatellites'],
[0x0009, 'GPSStatus'],
[0x000A, 'GPSMeasureMode'],
[0x000B, 'GPSDOP'],
[0x000C, 'GPSSpeedRef'],
[0x000D, 'GPSSpeed'],
[0x000E, 'GPSTrackRef'],
[0x000F, 'GPSTrack'],
[0x0010, 'GPSImgDirectionRef'],
[0x0011, 'GPSImgDirection'],
[0x0012, 'GPSMapDatum'],
[0x0013, 'GPSDestLatitudeRef'],
[0x0014, 'GPSDestLatitude'],
[0x0015, 'GPSDestLongitudeRef'],
[0x0016, 'GPSDestLongitude'],
[0x0017, 'GPSDestBearingRef'],
[0x0018, 'GPSDestBearing'],
[0x0019, 'GPSDestDistanceRef'],
[0x001A, 'GPSDestDistance'],
[0x001B, 'GPSProcessingMethod'],
[0x001C, 'GPSAreaInformation'],
[0x001D, 'GPSDateStamp'],
[0x001E, 'GPSDifferential'],
[0x001F, 'GPSHPositioningError'],
])
+21
View File
@@ -0,0 +1,21 @@
import {tagValues, createDictionary} from '../tags.mjs'
// TODO https://exiftool.org/TagNames/GPS.html
createDictionary(tagValues, 'gps', [
// GPSDestBearingRef
[0x0017, {
M: 'Magnetic North',
T: 'True North',
}],
// GPSDestDistanceRef
[0x0019, {
K: 'Kilometers',
M: 'Miles',
N: 'Nautical Miles',
}],
])
+58
View File
@@ -0,0 +1,58 @@
import {tagKeys, createDictionary} from '../tags.mjs'
// inspired by
// https://exiftool.org/TagNames/EXIF.html
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
// https://metacpan.org/pod/distribution/Image-ExifTool/lib/Image/ExifTool/TagNames.pod#EXIF-Tags
// https://metacpan.org/pod/Image::MetaData::JPEG::TagLists - canonical + custom tags
createDictionary(tagKeys, ['ifd0', 'ifd1'], [
// most of these plus more https://metacpan.org/pod/Image::MetaData::JPEG::TagLists#Canonical-Exif-2.2-and-TIFF-6.0-tags-for-IFD0-and-IFD1
[0x0100, 'ImageWidth'],
[0x0101, 'ImageHeight'],
[0x0102, 'BitsPerSample'],
[0x0103, 'Compression'],
[0x0106, 'PhotometricInterpretation'],
[0x010e, 'ImageDescription'],
[0x010f, 'Make'],
[0x0110, 'Model'],
[0x0111, 'StripOffsets'], // PreviewImageStart
[0x0112, 'Orientation'],
[0x0115, 'SamplesPerPixel'],
[0x0116, 'RowsPerStrip'],
[0x0117, 'StripByteCounts'], // PreviewImageLength
[0x011a, 'XResolution'],
[0x011b, 'YResolution'],
[0x011c, 'PlanarConfiguration'],
[0x0128, 'ResolutionUnit'],
[0x012d, 'TransferFunction'],
[0x0131, 'Software'],
[0x0132, 'ModifyDate'],
[0x013b, 'Artist'],
[0x013c, 'HostComputer'],
[0x013d, 'Predictor'],
[0x013e, 'WhitePoint'],
[0x013f, 'PrimaryChromaticities'],
[0x0201, 'ThumbnailOffset'],
[0x0202, 'ThumbnailLength'],
[0x0211, 'YCbCrCoefficients'],
[0x0212, 'YCbCrSubSampling'],
[0x0213, 'YCbCrPositioning'],
[0x0214, 'ReferenceBlackWhite'],
[0x02bc, 'ApplicationNotes'], // [Adobe XMP technote 9-14-02]
[0x8298, 'Copyright'],
// not core, but useful
[0x83bb, 'IPTC'],
[0x8769, 'ExifIFD'],
[0x8773, 'ICC'],
[0x8825, 'GpsIFD'],
[0x014a, 'SubIFD'], // [Adobe TIFF technote 1]
[0xa005, 'InteropIFD'], // not actually assigned to IFD0 but offten found here
// descriptions, not core
[0x9c9b, 'XPTitle'],
[0x9c9c, 'XPComment'],
[0x9c9d, 'XPAuthor'],
[0x9c9e, 'XPKeywords'],
[0x9c9f, 'XPSubject'],
])
+25
View File
@@ -0,0 +1,25 @@
import {tagValues, createDictionary} from '../tags.mjs'
createDictionary(tagValues, ['ifd0', 'ifd1'], [
// Orientation
[0x0112, {
1: 'Horizontal (normal)',
2: 'Mirror horizontal',
3: 'Rotate 180',
4: 'Mirror vertical',
5: 'Mirror horizontal and rotate 270 CW',
6: 'Rotate 90 CW',
7: 'Mirror horizontal and rotate 90 CW',
8: 'Rotate 270 CW',
}],
// ResolutionUnit
[0x0128, {
1: 'None',
2: 'inches',
3: 'cm',
}],
])
+10
View File
@@ -0,0 +1,10 @@
import {tagKeys, createDictionary} from '../tags.mjs'
createDictionary(tagKeys, 'interop', [
[0x0001, 'InteropIndex'],
[0x0002, 'InteropVersion'],
[0x1000, 'RelatedImageFileFormat'],
[0x1001, 'RelatedImageWidth'],
[0x1002, 'RelatedImageHeight'],
])
+359
View File
@@ -0,0 +1,359 @@
import {tagKeys, extendDictionary} from '../tags.mjs'
// all other uncathegorized or SubIFD tags from:
// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
// https://metacpan.org/pod/distribution/Image-ExifTool/lib/Image/ExifTool/TagNames.pod#EXIF-Tags
// Additional and barely used, but known tags in IFD0
extendDictionary(tagKeys, 'ifd0', [
// Additional IFD0 TIFF 6.0 tags not in Exif 2.2
// This is not complete list. This list was taken from https://exiftool.org/TagNames/EXIF.html
// https://metacpan.org/pod/Image::MetaData::JPEG::TagLists#Additional-TIFF-6.0-tags-not-in-Exif-2.2-for-IFD0
[0x000b, 'ProcessingSoftware'],
[0x00fe, 'SubfileType'],
[0x00ff, 'OldSubfileType'],
[0x0107, 'Thresholding'],
[0x0108, 'CellWidth'],
[0x0109, 'CellLength'],
[0x010a, 'FillOrder'],
[0x010d, 'DocumentName'],
[0x0118, 'MinSampleValue'],
[0x0119, 'MaxSampleValue'],
[0x011d, 'PageName'],
[0x011e, 'XPosition'],
[0x011f, 'YPosition'],
[0x0122, 'GrayResponseUnit'],
[0x0129, 'PageNumber'],
[0x0141, 'HalftoneHints'],
[0x0142, 'TileWidth'],
[0x0143, 'TileLength'],
[0x014c, 'InkSet'],
[0x0151, 'TargetPrinter'],
// yet another list
[0x4746, 'Rating'],
[0x4749, 'RatingPercent'],
[0x830e, 'PixelScale'],
[0x85d8, 'ModelTransform'],
[0x8649, 'PhotoshopSettings'],
[0xc612, 'DNGVersion'],
[0xc613, 'DNGBackwardVersion'],
[0xc614, 'UniqueCameraModel'],
[0xc615, 'LocalizedCameraModel'],
[0xc630, 'DNGLensInfo'],
[0xc633, 'ShadowScale'],
[0xc634, 'DNGPrivateData'],
// and more tags
[0x8480, 'IntergraphMatrix'],
[0x8482, 'ModelTiePoint'],
[0x8546, 'SEMInfo'],
[0x87af, 'GeoTiffDirectory'],
[0x87b0, 'GeoTiffDoubleParams'],
[0x87b1, 'GeoTiffAsciiParams'],
[0xc4a5, 'PrintIM'],
[0xc621, 'ColorMatrix1'],
[0xc622, 'ColorMatrix2'],
[0xc623, 'CameraCalibration1'],
[0xc624, 'CameraCalibration2'],
[0xc625, 'ReductionMatrix1'],
[0xc626, 'ReductionMatrix2'],
[0xc627, 'AnalogBalance'],
[0xc628, 'AsShotNeutral'],
[0xc629, 'AsShotWhiteXY'],
[0xc62a, 'BaselineExposure'],
[0xc62b, 'BaselineNoise'],
[0xc62c, 'BaselineSharpness'],
[0xc62e, 'LinearResponseLimit'],
[0xc62f, 'CameraSerialNumber'],
[0xc635, 'MakerNoteSafety'],
[0xc65a, 'CalibrationIlluminant1'],
[0xc65b, 'CalibrationIlluminant2'],
[0xc65d, 'RawDataUniqueID'],
[0xc68b, 'OriginalRawFileName'],
[0xc68c, 'OriginalRawFileData'],
[0xc68f, 'AsShotICCProfile'],
[0xc690, 'AsShotPreProfileMatrix'],
[0xc691, 'CurrentICCProfile'],
[0xc692, 'CurrentPreProfileMatrix'],
[0xc6bf, 'ColorimetricReference'],
[0xc6c5, 'SRawType'],
[0xc6d2, 'PanasonicTitle'],
[0xc6d3, 'PanasonicTitle2'],
[0xc6f3, 'CameraCalibrationSig'],
[0xc6f4, 'ProfileCalibrationSig'],
[0xc6f5, 'ProfileIFD'],
[0xc6f6, 'AsShotProfileName'],
[0xc6f8, 'ProfileName'],
[0xc6f9, 'ProfileHueSatMapDims'],
[0xc6fa, 'ProfileHueSatMapData1'],
[0xc6fb, 'ProfileHueSatMapData2'],
[0xc6fc, 'ProfileToneCurve'],
[0xc6fd, 'ProfileEmbedPolicy'],
[0xc6fe, 'ProfileCopyright'],
[0xc714, 'ForwardMatrix1'],
[0xc715, 'ForwardMatrix2'],
[0xc716, 'PreviewApplicationName'],
[0xc717, 'PreviewApplicationVersion'],
[0xc718, 'PreviewSettingsName'],
[0xc719, 'PreviewSettingsDigest'],
[0xc71a, 'PreviewColorSpace'],
[0xc71b, 'PreviewDateTime'],
[0xc71c, 'RawImageDigest'],
[0xc71d, 'OriginalRawFileDigest'],
[0xc725, 'ProfileLookTableDims'],
[0xc726, 'ProfileLookTableData'],
[0xc763, 'TimeCodes'],
[0xc764, 'FrameRate'],
[0xc772, 'TStop'],
[0xc789, 'ReelName'],
[0xc791, 'OriginalDefaultFinalSize'],
[0xc792, 'OriginalBestQualitySize'],
[0xc793, 'OriginalDefaultCropSize'],
[0xc7a1, 'CameraLabel'],
[0xc7a3, 'ProfileHueSatMapEncoding'],
[0xc7a4, 'ProfileLookTableEncoding'],
[0xc7a5, 'BaselineExposureOffset'],
[0xc7a6, 'DefaultBlackRender'],
[0xc7a7, 'NewRawImageDigest'],
[0xc7a8, 'RawToPreviewGain'],
])
// TODO: check all of these and add missing ones.
// https://metacpan.org/pod/Image::MetaData::JPEG::TagLists#Exif-tags-assigned-to-companies-for-IFD0-and-IFD1
// https://metacpan.org/pod/Image::MetaData::JPEG::TagLists#Exif-tags-for-the-0th-IFD-Exif-private-subdirectory
let otherTiffTags = [
[0x0111, 'StripOffsets'],
[0x0117, 'StripByteCounts'],
[0x0120, 'FreeOffsets'],
[0x0121, 'FreeByteCounts'],
[0x0123, 'GrayResponseCurve'],
[0x0124, 'T4Options'],
[0x0125, 'T6Options'],
[0x012c, 'ColorResponseUnit'],
[0x0140, 'ColorMap'],
[0x0144, 'TileOffsets'],
[0x0145, 'TileByteCounts'],
[0x0146, 'BadFaxLines'],
[0x0147, 'CleanFaxData'],
[0x0148, 'ConsecutiveBadFaxLines'],
[0x014a, 'SubIFD'],
[0x014d, 'InkNames'],
[0x014e, 'NumberofInks'],
[0x0150, 'DotRange'],
[0x0152, 'ExtraSamples'],
[0x0153, 'SampleFormat'],
[0x0154, 'SMinSampleValue'],
[0x0155, 'SMaxSampleValue'],
[0x0156, 'TransferRange'],
[0x0157, 'ClipPath'],
[0x0158, 'XClipPathUnits'],
[0x0159, 'YClipPathUnits'],
[0x015a, 'Indexed'],
[0x015b, 'JPEGTables'],
[0x015f, 'OPIProxy'],
[0x0190, 'GlobalParametersIFD'],
[0x0191, 'ProfileType'],
[0x0192, 'FaxProfile'],
[0x0193, 'CodingMethods'],
[0x0194, 'VersionYear'],
[0x0195, 'ModeNumber'],
[0x01b1, 'Decode'],
[0x01b2, 'DefaultImageColor'],
[0x01b3, 'T82Options'],
[0x01b5, 'JPEGTables'],
[0x0200, 'JPEGProc'],
[0x0203, 'JPEGRestartInterval'],
[0x0205, 'JPEGLosslessPredictors'],
[0x0206, 'JPEGPointTransforms'],
[0x0207, 'JPEGQTables'],
[0x0208, 'JPEGDCTables'],
[0x0209, 'JPEGACTables'],
[0x022f, 'StripRowCounts'],
[0x03e7, 'USPTOMiscellaneous'],
[0x4747, 'XP_DIP_XML'],
[0x4748, 'StitchInfo'],
[0x7000, 'SonyRawFileType'],
[0x7010, 'SonyToneCurve'],
[0x7031, 'VignettingCorrection'],
[0x7032, 'VignettingCorrParams'],
[0x7034, 'ChromaticAberrationCorrection'],
[0x7035, 'ChromaticAberrationCorrParams'],
[0x7036, 'DistortionCorrection'],
[0x7037, 'DistortionCorrParams'],
[0x74c7, 'SonyCropTopLeft'],
[0x74c8, 'SonyCropSize'],
[0x800d, 'ImageID'],
[0x80a3, 'WangTag1'],
[0x80a4, 'WangAnnotation'],
[0x80a5, 'WangTag3'],
[0x80a6, 'WangTag4'],
[0x80b9, 'ImageReferencePoints'],
[0x80ba, 'RegionXformTackPoint'],
[0x80bb, 'WarpQuadrilateral'],
[0x80bc, 'AffineTransformMat'],
[0x80e3, 'Matteing'],
[0x80e4, 'DataType'],
[0x80e5, 'ImageDepth'],
[0x80e6, 'TileDepth'],
[0x8214, 'ImageFullWidth'],
[0x8215, 'ImageFullHeight'],
[0x8216, 'TextureFormat'],
[0x8217, 'WrapModes'],
[0x8218, 'FovCot'],
[0x8219, 'MatrixWorldToScreen'],
[0x821a, 'MatrixWorldToCamera'],
[0x827d, 'Model2'],
[0x828d, 'CFARepeatPatternDim'],
[0x828e, 'CFAPattern2'],
[0x828f, 'BatteryLevel'],
[0x8290, 'KodakIFD'],
[0x82a5, 'MDFileTag'],
[0x82a6, 'MDScalePixel'],
[0x82a7, 'MDColorTable'],
[0x82a8, 'MDLabName'],
[0x82a9, 'MDSampleInfo'],
[0x82aa, 'MDPrepDate'],
[0x82ab, 'MDPrepTime'],
[0x82ac, 'MDFileUnits'],
[0x8335, 'AdventScale'],
[0x8336, 'AdventRevision'],
[0x835c, 'UIC1Tag'],
[0x835d, 'UIC2Tag'],
[0x835e, 'UIC3Tag'],
[0x835f, 'UIC4Tag'],
[0x847e, 'IntergraphPacketData'],
[0x847f, 'IntergraphFlagRegisters'],
[0x8481, 'INGRReserved'],
[0x84e0, 'Site'],
[0x84e1, 'ColorSequence'],
[0x84e2, 'IT8Header'],
[0x84e3, 'RasterPadding'],
[0x84e4, 'BitsPerRunLength'],
[0x84e5, 'BitsPerExtendedRunLength'],
[0x84e6, 'ColorTable'],
[0x84e7, 'ImageColorIndicator'],
[0x84e8, 'BackgroundColorIndicator'],
[0x84e9, 'ImageColorValue'],
[0x84ea, 'BackgroundColorValue'],
[0x84eb, 'PixelIntensityRange'],
[0x84ec, 'TransparencyIndicator'],
[0x84ed, 'ColorCharacterization'],
[0x84ee, 'HCUsage'],
[0x84ef, 'TrapIndicator'],
[0x84f0, 'CMYKEquivalent'],
[0x8568, 'AFCP_IPTC'],
[0x85b8, 'PixelMagicJBIGOptions'],
[0x85d7, 'JPLCartoIFD'],
[0x8602, 'WB_GRGBLevels'],
[0x8606, 'LeafData'],
[0x877f, 'TIFF_FXExtensions'],
[0x8780, 'MultiProfiles'],
[0x8781, 'SharedData'],
[0x8782, 'T88Options'],
[0x87ac, 'ImageLayer'],
[0x87be, 'JBIGOptions'],
[0x8828, 'Opto-ElectricConvFactor'],
[0x8829, 'Interlace'],
[0x885c, 'FaxRecvParams'],
[0x885d, 'FaxSubAddress'],
[0x885e, 'FaxRecvTime'],
[0x8871, 'FedexEDR'],
[0x888a, 'LeafSubIFD'],
[0x920b, 'FlashEnergy'],
[0x920c, 'SpatialFrequencyResponse'],
[0x920d, 'Noise'],
[0x920e, 'FocalPlaneXResolution'],
[0x920f, 'FocalPlaneYResolution'],
[0x9210, 'FocalPlaneResolutionUnit'],
[0x9215, 'ExposureIndex'],
[0x9216, 'TIFF-EPStandardID'],
[0x9217, 'SensingMethod'],
[0x923a, 'CIP3DataFile'],
[0x923b, 'CIP3Sheet'],
[0x923c, 'CIP3Side'],
[0x923f, 'StoNits'],
[0x932f, 'MSDocumentText'],
[0x9330, 'MSPropertySetStorage'],
[0x9331, 'MSDocumentTextPosition'],
[0x935c, 'ImageSourceData'],
[0xa005, 'InteropIFD'],
[0xa010, 'SamsungRawPointersOffset'],
[0xa011, 'SamsungRawPointersLength'],
[0xa101, 'SamsungRawByteOrder'],
[0xa102, 'SamsungRawUnknown'],
[0xa20c, 'SpatialFrequencyResponse'],
[0xa20d, 'Noise'],
[0xa211, 'ImageNumber'],
[0xa212, 'SecurityClassification'],
[0xa213, 'ImageHistory'],
[0xa216, 'TIFF-EPStandardID'],
[0xa40b, 'DeviceSettingDescription'],
[0xa480, 'GDALMetadata'],
[0xa481, 'GDALNoData'],
[0xafc0, 'ExpandSoftware'],
[0xafc1, 'ExpandLens'],
[0xafc2, 'ExpandFilm'],
[0xafc3, 'ExpandFilterLens'],
[0xafc4, 'ExpandScanner'],
[0xafc5, 'ExpandFlashLamp'],
[0xb4c3, 'HasselbladRawImage'],
[0xbc01, 'PixelFormat'],
[0xbc02, 'Transformation'],
[0xbc03, 'Uncompressed'],
[0xbc04, 'ImageType'],
[0xbc80, 'ImageWidth'],
[0xbc81, 'ImageHeight'],
[0xbc82, 'WidthResolution'],
[0xbc83, 'HeightResolution'],
[0xbcc0, 'ImageOffset'],
[0xbcc1, 'ImageByteCount'],
[0xbcc2, 'AlphaOffset'],
[0xbcc3, 'AlphaByteCount'],
[0xbcc4, 'ImageDataDiscard'],
[0xbcc5, 'AlphaDataDiscard'],
[0xc427, 'OceScanjobDesc'],
[0xc428, 'OceApplicationSelector'],
[0xc429, 'OceIDNumber'],
[0xc42a, 'OceImageLogic'],
[0xc44f, 'Annotations'],
[0xc51b, 'HasselbladExif'],
[0xc573, 'OriginalFileName'],
[0xc580, 'USPTOOriginalContentType'],
[0xc5e0, 'CR2CFAPattern'],
[0xc616, 'CFAPlaneColor'],
[0xc617, 'CFALayout'],
[0xc618, 'LinearizationTable'],
[0xc619, 'BlackLevelRepeatDim'],
[0xc61a, 'BlackLevel'],
[0xc61b, 'BlackLevelDeltaH'],
[0xc61c, 'BlackLevelDeltaV'],
[0xc61d, 'WhiteLevel'],
[0xc61e, 'DefaultScale'],
[0xc61f, 'DefaultCropOrigin'],
[0xc620, 'DefaultCropSize'],
[0xc62d, 'BayerGreenSplit'],
[0xc631, 'ChromaBlurRadius'],
[0xc632, 'AntiAliasStrength'],
[0xc640, 'RawImageSegmentation'],
[0xc65c, 'BestQualityScale'],
[0xc660, 'AliasLayerMetadata'],
[0xc68d, 'ActiveArea'],
[0xc68e, 'MaskedAreas'],
[0xc6f7, 'NoiseReductionApplied'],
[0xc71e, 'SubTileBlockSize'],
[0xc71f, 'RowInterleaveFactor'],
[0xc740, 'OpcodeList1'],
[0xc741, 'OpcodeList2'],
[0xc74e, 'OpcodeList3'],
[0xc761, 'NoiseProfile'],
[0xc7aa, 'CacheVersion'],
[0xc7b5, 'DefaultUserCrop'],
[0xc7d5, 'NikonNEFInfo'],
[0xfe00, 'KdcIFD'],
]
extendDictionary(tagKeys, 'ifd0', otherTiffTags)
extendDictionary(tagKeys, 'exif', otherTiffTags)
+80
View File
@@ -0,0 +1,80 @@
import {tagRevivers, createDictionary} from '../tags.mjs'
import {toAsciiString} from '../util/BufferView.mjs'
import {normalizeString} from '../util/helpers.mjs'
createDictionary(tagRevivers, ['ifd0', 'ifd1'], [
[0xC68B, toAsciiString],
[0x0132, reviveDate],
// extensions
[0x9c9b, reviveUcs2String],
[0x9c9c, reviveUcs2String],
[0x9c9d, reviveUcs2String],
[0x9c9e, reviveUcs2String],
[0x9c9f, reviveUcs2String],
])
createDictionary(tagRevivers, 'exif', [
[0xA000, reviveVersion],
[0x9000, reviveVersion],
[0x9003, reviveDate],
[0x9004, reviveDate],
// https://github.com/MikeKovarik/exifr/issues/36
[0xa002, unwrapExifSizeArray],
[0xa003, unwrapExifSizeArray],
])
createDictionary(tagRevivers, 'gps', [
[0x0000, val => Array.from(val).join('.')], // GPSVersionID
[0x0007, val => Array.from(val).join(':')], // GPSTimeStamp
])
function unwrapExifSizeArray(arr) {
if (typeof arr === 'object' && arr.length !== undefined)
return arr[0]
else
return arr
}
function reviveVersion(bytes) {
let array = Array.from(bytes).slice(1)
if (array[1] > 0x0f)
array = array.map(code => String.fromCharCode(code))
if (array[2] === '0' || array[2] === 0) array.pop()
return array.join('.')
}
// can be '2009-09-23 17:40:52 UTC' or '2010:07:06 20:45:12'
function reviveDate(string) {
if (typeof string !== 'string') return undefined
var [year, month, day, hours, minutes, seconds] = string.trim().split(/[-: ]/g).map(Number)
var date = new Date(year, month - 1, day)
if (!Number.isNaN(hours) && !Number.isNaN(minutes) && !Number.isNaN(seconds)) {
date.setHours(hours)
date.setMinutes(minutes)
date.setSeconds(seconds)
}
if (Number.isNaN(+date))
return string
else
return date
}
function reviveUcs2String(arg) {
if (typeof arg === 'string') return arg
let codePoints = []
let le = arg[1] === 0 && arg[arg.length - 1] === 0 // little endian
if (le) {
for (let i = 0; i < arg.length; i += 2)
codePoints.push(mergeBytes(arg[i + 1], arg[i]))
} else {
for (let i = 0; i < arg.length; i += 2)
codePoints.push(mergeBytes(arg[i], arg[i + 1]))
}
return normalizeString(String.fromCodePoint(...codePoints))
}
function mergeBytes(byte1, byte2) {
return (byte1 << 8) | byte2
}
+217
View File
@@ -0,0 +1,217 @@
import {fileParsers} from '../plugins.mjs'
import {FileParserBase} from '../parser.mjs'
// Only HEIC uses BufferView.getUint64
import '../util/BufferView-get64.mjs'
import {BufferView} from '../util/BufferView.mjs'
// 4 length + 4 kind + 8 (not always) for additional 64b length field
const boxHeaderLength = 16
// boxes with full head: meta, iinf, iref
export class IsoBmffParser extends FileParserBase {
parseBoxes(offset = 0) {
let boxes = []
while (offset < this.file.byteLength - 4) {
let box = this.parseBoxHead(offset)
boxes.push(box)
if (box.length === 0) break
offset += box.length
}
return boxes
}
parseSubBoxes(box) {
box.boxes = this.parseBoxes(box.start)
}
findBox(box, kind) {
if (box.boxes === undefined) this.parseSubBoxes(box)
return box.boxes.find(box => box.kind === kind)
}
parseBoxHead(offset) {
let length = this.file.getUint32(offset)
let kind = this.file.getString(offset + 4, 4)
let start = offset + 8 // 4+4 bytes
// length can be larger than 32b number in which case it is the first 64bits after header
if (length === 1) {
length = this.file.getUint64(offset + 8)
start += 8
}
return {offset, length, kind, start}
}
parseBoxFullHead(box) {
// ISO boxes come in 'old' and 'full' variants.
// The 'full' variant also contains version and flags information.
if (box.version !== undefined) return
let vflags = this.file.getUint32(box.start)
box.version = vflags >> 24
box.start += 4
}
}
export class HeifFileParser extends IsoBmffParser {
// NOTE: most parsers check if bytes 4-8 are 'ftyp' and then if 8-12 is one of heic/heix/hevc/hevx/heim/heis/hevm/hevs/mif1/msf1
// but bytes 20-24 are actually always 'heic' for all of these formats
static canHandle(file, firstTwoBytes) {
// The file starts with 4 byte FTYP number. The value is unlikely more than 30, let alone 2^32 FTYPs.
// So it's safe to assume that if first two bytes are 0, then this is HEIC.
if (firstTwoBytes !== 0) return false
let ftypLength = file.getUint16(2)
if (ftypLength > 50) return false
let offset = 16
let compatibleBrands = []
while (offset < ftypLength) {
compatibleBrands.push(file.getString(offset, 4))
offset += 4
}
return compatibleBrands.includes(this.type)
}
async parse() {
let nextBoxOffset = this.file.getUint32(0)
let meta = this.parseBoxHead(nextBoxOffset)
while (meta.kind !== 'meta') {
nextBoxOffset += meta.length
await this.file.ensureChunk(nextBoxOffset, boxHeaderLength)
meta = this.parseBoxHead(nextBoxOffset)
}
await this.file.ensureChunk(meta.offset, meta.length)
this.parseBoxFullHead(meta)
this.parseSubBoxes(meta)
//await this.findThumb(meta)
if (this.options.icc.enabled) await this.findIcc(meta)
if (this.options.tiff.enabled) await this.findExif(meta)
}
async registerSegment(key, offset, length) {
await this.file.ensureChunk(offset, length)
let chunk = this.file.subarray(offset, length)
this.createParser(key, chunk)
}
/*
async findThumb(meta) {
let iref = this.findBox(meta, 'iref')
if (iref === undefined) return
this.parseBoxFullHead(iref)
let thmb = this.findBox(iref, 'thmb')
if (thmb === undefined) return
let thumbLocId = this.file.getUint16(thmb.offset + 8)
let iloc = this.findBox(meta, 'iloc')
if (iloc === undefined) return
let extent = this.findExtentInIloc(iloc, thumbLocId)
if (extent === undefined) return
let [thumbOffset, thumbLength] = extent
console.log('thumbOffset', thumbOffset)
console.log('thumbLength', thumbLength)
await this.file.ensureChunk(thumbOffset, thumbLength)
let chunk = this.file.subarray(thumbOffset, thumbLength)
return chunk.toUint8()
}
*/
async findIcc(meta) {
let iprp = this.findBox(meta, 'iprp')
if (iprp === undefined) return
let ipco = this.findBox(iprp, 'ipco')
if (ipco === undefined) return
let colr = this.findBox(ipco, 'colr')
if (colr === undefined) return
await this.registerSegment('icc', colr.offset + 12, colr.length)
}
async findExif(meta) {
let iinf = this.findBox(meta, 'iinf')
if (iinf === undefined) return
let iloc = this.findBox(meta, 'iloc')
if (iloc === undefined) return
let exifLocId = this.findExifLocIdInIinf(iinf)
let extent = this.findExtentInIloc(iloc, exifLocId)
if (extent === undefined) return
let [exifOffset, exifLength] = extent
await this.file.ensureChunk(exifOffset, exifLength)
let nameSize = this.file.getUint32(exifOffset)
//let name = this.file.getString(exifOffset + 4, nameSize)
let extentContentShift = 4 + nameSize
exifOffset += extentContentShift
exifLength -= extentContentShift
await this.registerSegment('tiff', exifOffset, exifLength)
}
findExifLocIdInIinf(box) {
this.parseBoxFullHead(box)
let offset = box.start
let count = this.file.getUint16(offset)
let infe, infeOffset, idSize, name
offset += 2
while (count--) {
infe = this.parseBoxHead(offset)
this.parseBoxFullHead(infe)
infeOffset = infe.start
if (infe.version >= 2) {
idSize = infe.version === 3 ? 4 : 2
name = this.file.getString(infeOffset + idSize + 2, 4)
if (name === 'Exif')
return this.file.getUintBytes(infeOffset, idSize)
}
offset += infe.length
}
}
get8bits(offset) {
let n = this.file.getUint8(offset)
let n0 = n >> 4
let n1 = n & 0xf
return [n0, n1]
}
findExtentInIloc(box, wantedLocId) {
this.parseBoxFullHead(box)
let offset = box.start
let [offsetSize, lengthSize] = this.get8bits(offset++)
let [baseOffsetSize, indexSize] = this.get8bits(offset++)
let itemIdSize = box.version === 2 ? 4 : 2
let constMethodSize = box.version === 1 || box.version === 2 ? 2 : 0
let extentSize = indexSize + offsetSize + lengthSize
let itemCountSize = box.version === 2 ? 4 : 2
let itemCount = this.file.getUintBytes(offset, itemCountSize)
offset += itemCountSize
while (itemCount--) {
let itemId = this.file.getUintBytes(offset, itemIdSize)
offset += itemIdSize + constMethodSize + 2 + baseOffsetSize // itemId + construction_method + data_reference_index + base_offset
let extentCount = this.file.getUint16(offset)
offset += 2
if (itemId === wantedLocId) {
if (extentCount > 1) {
console.warn(`ILOC box has more than one extent but we're only processing one\nPlease create an issue at https://github.com/MikeKovarik/exifr with this file`)
// iloc contains items array, each of which contains extents.
// theres usually only one extent in each item but if there's more
}
return [
// extent offset
this.file.getUintBytes(offset + indexSize, offsetSize),
// extent length
this.file.getUintBytes(offset + indexSize + offsetSize, lengthSize),
]
}
offset += extentCount * extentSize
}
}
}
export class HeicFileParser extends HeifFileParser {
static type = 'heic'
}
export class AvifFileParser extends HeifFileParser {
static type = 'avif'
}
fileParsers.set('heic', HeicFileParser)
fileParsers.set('avif', AvifFileParser)
+238
View File
@@ -0,0 +1,238 @@
import {FileParserBase, AppSegmentParserBase} from '../parser.mjs'
import {fileParsers, segmentParsers} from '../plugins.mjs'
const JPEG_SOI = 0xffd8
const MARKER_1 = 0xff
const MARKER_2_APP0 = 0xe0 // ff e0
const MARKER_2_APP15 = 0xef // ff ef
const MARKER_2_SOF0 = 0xc0 // ff c0
const MARKER_2_SOF2 = 0xc2 // ff c2
const MARKER_2_DHT = 0xc4 // ff c4
const MARKER_2_DQT = 0xdb // ff db
const MARKER_2_DRI = 0xdd // ff dd
const MARKER_2_SOS = 0xda // ff da
const MARKER_2_COMMENT = 0xfe // ff fe
function isJpgMarker(marker2) {
return marker2 === MARKER_2_SOF0
|| marker2 === MARKER_2_SOF2
|| marker2 === MARKER_2_DHT
|| marker2 === MARKER_2_DQT
|| marker2 === MARKER_2_DRI
|| marker2 === MARKER_2_SOS
|| marker2 === MARKER_2_COMMENT
}
function isAppMarker(marker2) {
return marker2 >= MARKER_2_APP0
&& marker2 <= MARKER_2_APP15
}
function getSegmentType(buffer, offset, length) {
for (let [type, Parser] of segmentParsers)
if (Parser.canHandle(buffer, offset, length))
return type
}
// https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format
// https://sno.phy.queensu.ca/~phil/exiftool/TagNames/JPEG.html
// http://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_JPEG_files
// JPG contains SOI, APP1, [APP2, ... APPn], DQT, DHT, and more segments
// APPn contain metadata about the image in various formats. There can be multiple APPn segments,
// even multiple segments of the same type.
// APP1 contains the basic and most important EXIF data.
// APP2 contains ICC
// APP13 contains IPTC
// the main APP1 (the one with EXIF) is often followed by another APP1 with XMP data (in XML format).
// Structure of APPn (APP1, APP2, APP13, etc...):
// - First two bytes are the marker FF En (e.g. FF E1 for APP1)
// - 3rd & 4th bytes are length of the APPn segment
// - Followed by a few bytes of segment itentification - describing what type of content is there.
// Structure of TIFF (APP1-EXIF):
// - FF 01 - marker
// - xx xx - Size
// - 45 78 69 66 00 00 / ASCII string 'Exif\0\0'
// - TIFF HEADER
// - 0th IFD + value
// - 1th IFD + value
// - may contain additional GPS, Interop, SubExif blocks (pointed to from IFD0)
export class JpegFileParser extends FileParserBase {
static type = 'jpeg'
static canHandle(file, firstTwoBytes) {
return firstTwoBytes === JPEG_SOI
}
appSegments = []
jpegSegments = []
unknownSegments = []
async parse() {
await this.findAppSegments()
await this.readSegments(this.appSegments)
this.mergeMultiSegments()
this.createParsers(this.mergedAppSegments || this.appSegments)
}
setupSegmentFinderArgs(wanted) {
if (wanted === true) {
this.findAll = true
this.wanted = new Set(segmentParsers.keyList())
} else {
if (wanted === undefined)
wanted = segmentParsers.keyList().filter(key => this.options[key].enabled)
else
wanted = wanted.filter(key => this.options[key].enabled && segmentParsers.has(key))
this.findAll = false
this.remaining = new Set(wanted)
this.wanted = new Set(wanted)
}
this.unfinishedMultiSegment = false
}
async findAppSegments(offset = 0, wantedArray) {
this.setupSegmentFinderArgs(wantedArray)
let {file, findAll, wanted, remaining} = this
if (!findAll && this.file.chunked) {
findAll = Array.from(wanted).some(type => {
let Parser = segmentParsers.get(type)
let segOpts = this.options[type]
return Parser.multiSegment && segOpts.multiSegment
})
if (findAll) await this.file.readWhole()
}
// findAppSegmentsInRange() returns offset where next segment starts. If we didn't store it, next time we continue
// we might start in middle of data segment and would uselessly read & parse through noise.
offset = this.findAppSegmentsInRange(offset, file.byteLength)
// If user only requests TIFF it's not necessary to read any more chunks. Because EXIF in jpg is always near the start of the file.
if (this.options.onlyTiff) return
if (file.chunked) {
// We're in chunked mode and couldn't find all wanted segments.
// We'll read couple more chunks and parse them until we've found everything or hit chunk limit.
// EOF = End Of File
let eof = false
while (remaining.size > 0 && !eof && (file.canReadNextChunk || this.unfinishedMultiSegment)) {
let {nextChunkOffset} = file
// We might have previously found beginning of segment, but only fitst half of it be read in memory.
let hasIncompleteSegments = this.appSegments.some(seg => !this.file.available(seg.offset || seg.start, seg.length || seg.size))
// Start reading where we the next block begins. That way we avoid reading part of file where some jpeg image data may be.
// Unless there's an incomplete segment. In this case start reading right where the last chunk ends to get the whole segment.
if (offset > nextChunkOffset && !hasIncompleteSegments)
eof = !await file.readNextChunk(offset)
else
eof = !await file.readNextChunk(nextChunkOffset)
offset = this.findAppSegmentsInRange(offset, file.byteLength)
// search for APP segments was cancelled because we reached raw jpeg image data.
if (offset === undefined) return
}
}
}
findAppSegmentsInRange(offset, end) {
// TLDR: Make space for MARKER and LENGTH.
// Don't read right till end. If the last byte is marker, then length is out of bounds and crashes.
end -= 2
let {file, findAll, wanted, remaining, options} = this
let marker2, length, type, Parser, seg, segOpts
for (; offset < end; offset++) {
if (file.getUint8(offset) !== MARKER_1) continue
// Reading uint8 instead of uint16 to prevent re-reading subsequent bytes.
marker2 = file.getUint8(offset + 1)
if (isAppMarker(marker2)) {
// WE FOUND APP-N SEGMENT
length = file.getUint16(offset + 2)
type = getSegmentType(file, offset, length)
if (type && wanted.has(type)) {
// known and parseable segment found
Parser = segmentParsers.get(type)
seg = Parser.findPosition(file, offset)
segOpts = options[type]
seg.type = type
this.appSegments.push(seg)
if (!findAll) {
if (Parser.multiSegment && segOpts.multiSegment) {
// Found multisegment segment and options allows to process them.
this.unfinishedMultiSegment = seg.chunkNumber < seg.chunkCount
// Clear the segment from remaining if we've reached the last multi-segment.
if (!this.unfinishedMultiSegment) remaining.delete(type)
} else {
// Not a multisegment or we're not allowed to process them.
remaining.delete(type)
}
// stop parsing alltogether if we've found all requested segments.
if (remaining.size === 0) break
}
} if (options.recordUnknownSegments) {
// either unknown/supported appN segment or just a noise.
seg = AppSegmentParserBase.findPosition(file, offset)
seg.marker = marker2
this.unknownSegments.push(seg)
}
offset += length + 1
} else if (isJpgMarker(marker2)) {
// WE FOUND JPEG FILE STRUCTURE SEGMENT
length = file.getUint16(offset + 2)
// Compressed data follows after SOS. SOS marker does not have (useful) length bytes.
// Lot of FF00 follows but those do not have length either. We can stop reading here.
if (marker2 === MARKER_2_SOS && options.stopAfterSos !== false)
return undefined
if (options.recordJpegSegments)
this.jpegSegments.push({offset, length, marker: marker2})
offset += length + 1
}
}
return offset
}
// Goes through this.appSegments and merge all segments that are split between multiple chunks.
// The processed array is written to this.mergedAppSegments.
mergeMultiSegments() {
let hasMultiSegments = this.appSegments.some(seg => seg.multiSegment)
if (!hasMultiSegments) return
let grouped = groupBy(this.appSegments, 'type')
this.mergedAppSegments = grouped.map(([type, typeSegments]) => {
let Parser = segmentParsers.get(type, this.options)
if (Parser.handleMultiSegments) {
let chunk = Parser.handleMultiSegments(typeSegments)
return {type, chunk}
} else {
return typeSegments[0]
}
})
}
getSegment(type) {
return this.appSegments.find(seg => seg.type === type)
}
async getOrFindSegment(type) {
let seg = this.getSegment(type)
if (seg === undefined) {
await this.findAppSegments(0, [type])
seg = this.getSegment(type)
}
return seg
}
}
function groupBy(array, key) {
let groups = new Map
let item, groupKey, group
for (let i = 0; i < array.length; i++) {
item = array[i]
groupKey = item[key]
if (groups.has(groupKey))
group = groups.get(groupKey)
else
groups.set(groupKey, group = [])
group.push(item)
}
return Array.from(groups)
}
fileParsers.set('jpeg', JpegFileParser)
+139
View File
@@ -0,0 +1,139 @@
import {FileParserBase} from '../parser.mjs'
import {fileParsers, segmentParsers} from '../plugins.mjs'
import * as platform from '../util/platform.mjs'
import dynamicImport from '../util/import.mjs'
let zlibPromise = dynamicImport('zlib')
// https://dev.exiv2.org/projects/exiv2/wiki/The_Metadata_in_PNG_files
// http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html
const PNG_MAGIC_BYTES = '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a'
const PNG_XMP_PREFIX = 'XML:com.adobe.xmp'
const LENGTH_SIZE = 4
const TYPE_SIZE = 4
const CRC_SIZE = 4
const IHDR = 'ihdr'
const ICCP = 'iccp'
const TEXT = 'text'
const ITXT = 'itxt'
const EXIF = 'exif' // eXIf
const pngMetaChunks = [IHDR, ICCP, TEXT, ITXT, EXIF]
export class PngFileParser extends FileParserBase {
static type = 'png'
static canHandle(file, firstTwoBytes) {
return firstTwoBytes === 0x8950
&& file.getUint32(0) === 0x89504e47
&& file.getUint32(4) === 0x0d0a1a0a
}
async parse() {
let {file} = this
await this.findPngChunksInRange(PNG_MAGIC_BYTES.length, file.byteLength)
await this.readSegments(this.metaChunks)
this.findIhdr()
this.parseTextChunks()
await this.findExif().catch(this.catchError)
await this.findXmp().catch(this.catchError)
await this.findIcc().catch(this.catchError)
}
catchError = err => this.errors.push(err)
metaChunks = []
unknownChunks = []
async findPngChunksInRange(offset, end) {
let {file} = this
while (offset < end) {
let size = file.getUint32(offset) // size without crc
let marker = file.getUint32(offset + LENGTH_SIZE)
let name = file.getString(offset + LENGTH_SIZE, 4)
let type = name.toLowerCase()
let start = offset + LENGTH_SIZE + TYPE_SIZE
let length = size + LENGTH_SIZE + TYPE_SIZE + CRC_SIZE
let seg = {type, offset, length, start, size, marker}
if (pngMetaChunks.includes(type))
this.metaChunks.push(seg)
else
this.unknownChunks.push(seg)
offset += length
}
}
// PNG additionally stores simple string key:value pairs each in separate tEXt chunks.
// There can be many of them, the format is simple enough to not mandate custom segment-parser class.
// For simplicity's and performance's sake. And these chunks do not specifically belong (like for example into iptc, exif, etc...)
// So we're just parse it all here and merge the output into ihdr (rest of PNG header data).
parseTextChunks() {
let textChunks = this.metaChunks.filter(info => info.type === TEXT)
for (let seg of textChunks) {
let [key, val] = this.file.getString(seg.start, seg.size).split('\0')
this.injectKeyValToIhdr(key, val)
}
}
injectKeyValToIhdr(key, val) {
let parser = this.parsers.ihdr
if (parser) parser.raw.set(key, val)
}
findIhdr() {
let seg = this.metaChunks.find(seg => seg.type === IHDR)
if (!seg) return
// ihdr option is undefined by default (because we don't want jpegs and heic files to pick it up)
// so here we create it for every png file. But only if user didn't explicitly disabled it.
if (this.options[IHDR].enabled !== false)
this.createParser(IHDR, seg.chunk)
}
async findExif() {
let seg = this.metaChunks.find(info => info.type === 'exif')
if (!seg) return
this.injectSegment('tiff', seg.chunk)
}
// http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.iTXt
// iTXt chunk header is slightly complicated. It contains multiple null-terminator-separated info.
// The XMP data is present after third null-terminator.
async findXmp() {
let itxtChunks = this.metaChunks.filter(info => info.type === ITXT)
for (let seg of itxtChunks) {
let prefix = seg.chunk.getString(0, PNG_XMP_PREFIX.length)
if (prefix === PNG_XMP_PREFIX)
this.injectSegment('xmp', seg.chunk)
}
}
async findIcc() {
let seg = this.metaChunks.find(info => info.type === ICCP)
if (!seg) return
let {chunk} = seg
let chunkHead = chunk.getUint8Array(0, 81)
// icc profile has variable length (up to 80B) followed by null terminator.
let nameLength = 0
// Get length of the profile name by looking for the null terminator.
while (nameLength < 80 && chunkHead[nameLength] !== 0) nameLength++
// Recalculate actual ICC data position.
let iccpHeaderLength = nameLength + 2 // 1 byte null terminator, + 1 byte compression
let profileName = chunk.getString(0, nameLength)
this.injectKeyValToIhdr('ProfileName', profileName)
// ICC data is zlib compressed by default. Spec doesn't even allow raw data.
if (platform.node) {
let zlib = await zlibPromise
let dataChunk = chunk.getUint8Array(iccpHeaderLength)
dataChunk = zlib.inflateSync(dataChunk)
this.injectSegment('icc', dataChunk)
}
}
}
fileParsers.set('png', PngFileParser)
+55
View File
@@ -0,0 +1,55 @@
import {FileParserBase} from '../parser.mjs'
import {TAG_XMP, TAG_IPTC, TAG_ICC} from '../tags.mjs'
import {fileParsers} from '../plugins.mjs'
import {estimateMetadataSize} from '../util/helpers.mjs'
import {TIFF_LITTLE_ENDIAN, TIFF_BIG_ENDIAN} from '../util/helpers.mjs'
export class TiffFileParser extends FileParserBase {
static type = 'tiff'
static canHandle(file, firstTwoBytes) {
return firstTwoBytes === TIFF_LITTLE_ENDIAN
|| firstTwoBytes === TIFF_BIG_ENDIAN
}
extendOptions(options) {
// note: skipping is done on global level in Options class
let {ifd0, xmp, iptc, icc} = options
if (xmp.enabled) ifd0.deps.add(TAG_XMP)
if (iptc.enabled) ifd0.deps.add(TAG_IPTC)
if (icc.enabled) ifd0.deps.add(TAG_ICC)
ifd0.finalizeFilters()
}
async parse() {
let {tiff, xmp, iptc, icc} = this.options
if (tiff.enabled || xmp.enabled || iptc.enabled || icc.enabled) {
// TODO: refactor this in the future
// Tiff files start with TIFF structure (instead of JPEGs FF D8) but offsets can point to any place in the file.
// even wihin single block. Crude option is to just read as big chunk as possible.
// TODO: in the future, block reading will be recursive or looped until all pointers are resolved.
// SIDE NOTE: .tif files stor XMP as ApplicationNotes tag in TIFF structure as well.
let length = Math.max(estimateMetadataSize(this.options), this.options.chunkSize)
await this.file.ensureChunk(0, length)
this.createParser('tiff', this.file)
this.parsers.tiff.parseHeader()
await this.parsers.tiff.parseIfd0Block()
this.adaptTiffPropAsSegment('xmp')
this.adaptTiffPropAsSegment('iptc')
this.adaptTiffPropAsSegment('icc')
}
}
adaptTiffPropAsSegment(type) {
if (this.parsers.tiff[type]) {
// TIFF stores all other segments as tags in IFD0 object. Get the tag.
let raw = this.parsers.tiff[type]
this.injectSegment(type, raw)
}
}
}
fileParsers.set('tiff', TiffFileParser)
+61
View File
@@ -0,0 +1,61 @@
import {fileReaders} from '../plugins.mjs'
import {ChunkedReader} from './ChunkedReader.mjs'
import * as platform from '../util/platform.mjs'
import {Buffer} from '../util/platform.mjs'
export class Base64Reader extends ChunkedReader {
constructor(...args) {
super(...args)
// Remove the mime type and base64 marker at the beginning so that we're left off with clear b64 string.
this.input = this.input.replace(/^data:([^;]+);base64,/gmi, '')
this.size = (this.input.length / 4) * 3
if (this.input.endsWith('==')) this.size -= 2
else if (this.input.endsWith('=')) this.size -= 1
}
// Accepts base64 or base64 URL and converts it to DataView and trims if needed.
async _readChunk(offset, length) {
let base64 = this.input
// Base64 encodes 3 bytes of data into string of 4 characters.
// To extract bytes at certain offset and length we need to take that into account,
// recalculate the offset and length into blocks of 4 characters, slice the input base64 string
// from these first and last of these blocks, and finally adjust correct offset in these blocks.
// NOTE: Each 4 character block of base64 string represents 3 bytes of data.
let blockStart, offsetInBlock
if (offset === undefined) {
// Start from begining of the 4-letter block.
offset = 0
blockStart = 0
offsetInBlock = 0
} else {
// Adjust offset from the start of the 4-letter block.
blockStart = Math.floor(offset / 3) * 4
offsetInBlock = offset - ((blockStart / 4) * 3)
}
if (length === undefined) {
length = this.size
}
let end = offset + length
let blockEnd = blockStart + Math.ceil(end / 3) * 4
base64 = base64.slice(blockStart, blockEnd)
let clampedLength = Math.min(length, this.size - offset)
if (platform.hasBuffer) {
let slice = Buffer.from(base64, 'base64').slice(offsetInBlock, offsetInBlock + clampedLength)
return this.set(slice, offset, true)
} else {
let chunk = this.subarray(offset, clampedLength, true)
let binary = atob(base64)
let uint8view = chunk.toUint8()
for (let i = 0; i < clampedLength; i++)
uint8view[i] = binary.charCodeAt(offsetInBlock + i)
return chunk
}
}
}
fileReaders.set('base64', Base64Reader)
+29
View File
@@ -0,0 +1,29 @@
import {fileReaders} from '../plugins.mjs'
import {readBlobAsArrayBuffer} from '../reader.mjs'
import {ChunkedReader} from './ChunkedReader.mjs'
export class BlobReader extends ChunkedReader {
async readWhole() {
this.chunked = false
let arrayBuffer = await readBlobAsArrayBuffer(this.input)
this._swapArrayBuffer(arrayBuffer)
}
readChunked() {
this.chunked = true
this.size = this.input.size
return super.readChunked()
}
async _readChunk(offset, length) {
let end = length ? offset + length : undefined
let blob = this.input.slice(offset, end)
let abChunk = await readBlobAsArrayBuffer(blob)
return this.set(abChunk, offset, true)
}
}
fileReaders.set('blob', BlobReader)
+100
View File
@@ -0,0 +1,100 @@
import {DynamicBufferView} from '../util/DynamicBufferView.mjs'
// This method came through three iterations. Tested with 4MB file with EXIF at the beginning.
// iteration #1 - Fetch whole file.
// - Took about 23ms on average.
// - It meant unnecessary conversion of whole 4MB
// iteration #2 - Fetch first 512 bytes, find exif, then fetch additional kilobytes of exif to be parsed.
// - Exactly like what we do with Node's readFile() method.
// - Slightly faster. 18ms on average.
// - Certainly more efficient processing-wise. Only beginning of the file was read and converted.
// - But the additional read of the exif chunk is expensive time-wise because browser's fetch and
// - Blob<->ArrayBuffer manipulations are not as fast as Node's low-level fs.open() & fs.read().
// iteration #3 - This one we landed on.
// - 11ms on average. (As fast as Node)
// - Compromise between time and processing costs.
// - Fetches first 64KB of the file. In most cases, EXIF isn't larger than that.
// - In most cases, the 64KB is enough and we don't need additional fetch/convert operation.
// - But we can do the second read if needed (edge cases) where the performance wouldn't be great anyway.
// It can be used with Blobs, URLs, Base64 (URL).
// blobs and fetching from url uses larger chunks with higher chances of having the whole exif within (iteration 3).
// base64 string (and base64 based url) uses smaller chunk at first (iteration 2).
// Accepts file path and uses lower-level FS APIs to open the file, read the first 512 bytes
// trying to locate EXIF and then reading only the portion of the file where EXIF is if found.
// If the EXIF is not found within the first 512 Bytes. the range can be adjusted by user,
// or it falls back to reading the whole file if enabled with options.allowWholeFile.
export class ChunkedReader extends DynamicBufferView {
constructor(input, options) {
super(0)
this.input = input
this.options = options
}
chunksRead = 0
async readWhole() {
this.chunked = false
await this.readChunk(this.nextChunkOffset)
}
async readChunked() {
this.chunked = true
await this.readChunk(0, this.options.firstChunkSize)
}
async readNextChunk(offset = this.nextChunkOffset) {
if (this.fullyRead) {
this.chunksRead++
return false
}
let sizeToRead = this.options.chunkSize
let chunk = await this.readChunk(offset, sizeToRead)
if (chunk) return chunk.byteLength === sizeToRead
return false
}
// todo: only read unread bytes. ignore overlaping bytes.
async readChunk(offset, length) {
this.chunksRead++
length = this.safeWrapAddress(offset, length)
if (length === 0) return undefined
return this._readChunk(offset, length)
}
safeWrapAddress(offset, length) {
if (this.size !== undefined && offset + length > this.size)
return Math.max(0, this.size - offset)
return length
}
get nextChunkOffset() {
if (this.ranges.list.length !== 0)
return this.ranges.list[0].length
}
get canReadNextChunk() {
return this.chunksRead < this.options.chunkLimit
}
get fullyRead() {
if (this.size === undefined) return false
return this.nextChunkOffset === this.size
}
read() {
if (this.options.chunked)
return this.readChunked()
else
return this.readWhole()
}
// DO NOT REMOVE!
// Some inheriting readers need additional method for cleanup.
// This dummy method makes sure anyone can safely call exifr.file.close() and not have to worry.
close() {}
}
+56
View File
@@ -0,0 +1,56 @@
import {fileReaders} from '../plugins.mjs'
import {ChunkedReader} from './ChunkedReader.mjs'
import * as platform from '../util/platform.mjs'
import dynamicImport from '../util/import.mjs'
let fsPromise = dynamicImport('fs', fs => fs.promises)
export class FsReader extends ChunkedReader {
async readWhole() {
this.chunked = false
this.fs = await fsPromise
let buffer = await this.fs.readFile(this.input)
this._swapBuffer(buffer)
}
async readChunked() {
this.chunked = true
this.fs = await fsPromise
await this.open()
await this.readChunk(0, this.options.firstChunkSize)
}
async open() {
if (this.fh === undefined) {
this.fh = await this.fs.open(this.input, 'r')
this.size = (await this.fh.stat(this.input)).size
}
}
async _readChunk(offset, length) {
// reopen if needed
if (this.fh === undefined) await this.open()
// stay within file-size boundaries
if (offset + length > this.size)
length = this.size - offset
// read the chunk into newly created/extended chunk of the dynamic buffer.
var chunk = this.subarray(offset, length, true)
await this.fh.read(chunk.dataView, 0, length, offset)
return chunk
}
// TODO: auto close file handle when reading and parsing is over
// (app can read more chunks after parsing the first)
async close() {
if (this.fh) {
let fh = this.fh
this.fh = undefined
await fh.close()
}
}
}
fileReaders.set('fs', FsReader)
+33
View File
@@ -0,0 +1,33 @@
import {fileReaders} from '../plugins.mjs'
import {fetchUrlAsArrayBuffer} from '../reader.mjs'
import {ChunkedReader} from './ChunkedReader.mjs'
import {fetch} from '../polyfill/fetch.mjs'
export class UrlFetcher extends ChunkedReader {
async readWhole() {
this.chunked = false
let chunk = await fetchUrlAsArrayBuffer(this.input)
if (chunk instanceof ArrayBuffer)
this._swapArrayBuffer(chunk)
else if (chunk instanceof Uint8Array)
this._swapBuffer(chunk)
}
async _readChunk(offset, length) {
let end = length ? offset + length - 1 : undefined
// note: end in http range is inclusive, unlike APIs in node,
let headers = this.options.httpHeaders || {};
if (offset || end) headers.range = `bytes=${[offset, end].join('-')}`
let res = await fetch(this.input, {headers})
let abChunk = await res.arrayBuffer()
let bytesRead = abChunk.byteLength
if (res.status === 416) return undefined
if (bytesRead !== length) this.size = offset + bytesRead
return this.set(abChunk, offset, true)
}
}
fileReaders.set('url', UrlFetcher)
+13
View File
@@ -0,0 +1,13 @@
export const disableAllOptions = {
ifd0: false,
ifd1: false,
exif: false,
gps: false,
interop: false,
// turning off all unnecessary steps and transformation to get the needed data ASAP
sanitize: false,
reviveValues: true,
translateKeys: false,
translateValues: false,
mergeOutput: false,
}
+19
View File
@@ -0,0 +1,19 @@
import {Exifr} from '../Exifr.mjs'
import {TAG_GPS_LATREF, TAG_GPS_LAT, TAG_GPS_LONREF, TAG_GPS_LON} from '../tags.mjs'
import {disableAllOptions} from './disableAllOptions.mjs'
export const gpsOnlyOptions = Object.assign({}, disableAllOptions, {
firstChunkSize: 40000,
gps: [TAG_GPS_LATREF, TAG_GPS_LAT, TAG_GPS_LONREF, TAG_GPS_LON],
})
export async function gps(input) {
let exr = new Exifr(gpsOnlyOptions)
await exr.read(input)
let output = await exr.parse()
if (output && output.gps) {
let {latitude, longitude} = output.gps
return {latitude, longitude}
}
}
+66
View File
@@ -0,0 +1,66 @@
import {Exifr} from '../Exifr.mjs'
import {TAG_ORIENTATION} from '../tags.mjs'
import {disableAllOptions} from './disableAllOptions.mjs'
export const orientationOnlyOptions = Object.assign({}, disableAllOptions, {
firstChunkSize: 40000,
ifd0: [TAG_ORIENTATION],
})
export async function orientation(input) {
let exr = new Exifr(orientationOnlyOptions)
await exr.read(input)
let output = await exr.parse()
if (output && output.ifd0) {
return output.ifd0[TAG_ORIENTATION]
}
}
export const rotations = Object.freeze({
1: {dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 0, rad: 0 },
2: {dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 0, rad: 0 },
3: {dimensionSwapped: false, scaleX: 1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180},
4: {dimensionSwapped: false, scaleX: -1, scaleY: 1, deg: 180, rad: 180 * Math.PI / 180},
5: {dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 90, rad: 90 * Math.PI / 180},
6: {dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 90, rad: 90 * Math.PI / 180},
7: {dimensionSwapped: true, scaleX: 1, scaleY: -1, deg: 270, rad: 270 * Math.PI / 180},
8: {dimensionSwapped: true, scaleX: 1, scaleY: 1, deg: 270, rad: 270 * Math.PI / 180}
})
export let rotateCanvas = true
export let rotateCss = true
if (typeof navigator === 'object') {
let ua = navigator.userAgent
if (ua.includes('iPad') || ua.includes('iPhone')) {
// doesn't always match in webview: https://github.com/MikeKovarik/exifr/pull/42
let matchArray = ua.match(/OS (\d+)_(\d+)/)
if (matchArray) {
let [, major, minor] = matchArray
let version = Number(major) + Number(minor) * 0.1
// before ios 13.4, orientation is needed for canvas
// since ios 13.4, the data passed to canvas is already rotated
rotateCanvas = version < 13.4
rotateCss = false
}
} else if (ua.includes('OS X 10')) {
let [, version] = ua.match(/OS X 10[_.](\d+)/)
rotateCanvas = rotateCss = Number(version) < 15
}
if (ua.includes('Chrome/')) {
let [, version] = ua.match(/Chrome\/(\d+)/)
rotateCanvas = rotateCss = Number(version) < 81
} else if (ua.includes('Firefox/')) {
let [, version] = ua.match(/Firefox\/(\d+)/)
rotateCanvas = rotateCss = Number(version) < 77
}
}
export async function rotation(input) {
let or = await orientation(input)
return Object.assign({
canvas: rotateCanvas,
css: rotateCss,
}, rotations[or])
}
+59
View File
@@ -0,0 +1,59 @@
import {segmentParsers} from '../plugins.mjs'
import {Options} from '../options.mjs'
import {read} from '../reader.mjs'
import {throwError} from '../util/helpers.mjs'
const allowedSidecars = ['xmp', 'icc', 'iptc', 'tiff']
const noop = () => {}
export async function sidecar(input, opts, segType) {
let options = new Options(opts)
options.chunked = false
if (segType === undefined && typeof input === 'string')
segType = guessTypeFromName(input)
let chunk = await read(input, options)
if (segType) {
if (allowedSidecars.includes(segType))
return handleSeg(segType, chunk, options)
else
throwError(`Invalid segment type`)
} else {
if (isXmpData(chunk))
return handleSeg('xmp', chunk, options)
for (let [type] of segmentParsers) {
// skip unsupported sidecar types
if (!allowedSidecars.includes(type)) continue
// break the loop if parsing succeeded
let output = await handleSeg(type, chunk, options).catch(noop)
if (output) return output
}
throwError(`Unknown file format`)
}
}
function isXmpData(chunk) {
let string = chunk.getString(0, 50).trim()
return string.includes('<?xpacket')
|| string.includes('<x:')
}
async function handleSeg(type, chunk, options) {
let segOptions = options[type]
segOptions.enabled = true
segOptions.parse = true
let Parser = segmentParsers.get(type)
return Parser.parse(chunk, segOptions)
}
function guessTypeFromName(filename) {
let ext = filename.toLowerCase().split('.').pop()
if (isTiffExt(ext)) return 'tiff'
if (allowedSidecars.includes(ext)) return ext
}
function isTiffExt(ext) {
return ext === 'exif'
|| ext === 'tiff'
|| ext === 'tif'
}
+32
View File
@@ -0,0 +1,32 @@
import * as platform from '../util/platform.mjs'
import {Buffer} from '../util/platform.mjs'
import {Exifr} from '../Exifr.mjs'
import {disableAllOptions} from './disableAllOptions.mjs'
export const thumbnailOnlyOptions = Object.assign({}, disableAllOptions, {
tiff: false,
ifd1: true,
// needed to prevent options from disabling ifd1
mergeOutput: false
})
export async function thumbnail(input) {
let exr = new Exifr(thumbnailOnlyOptions)
await exr.read(input)
let u8arr = await exr.extractThumbnail()
if (u8arr && platform.hasBuffer)
return Buffer.from(u8arr)
else
return u8arr
}
// only available in browser
export async function thumbnailUrl(input) {
let u8arr = await this.thumbnail(input)
if (u8arr !== undefined) {
let blob = new Blob([u8arr]) // note: dont use AB directly, because of byteOffset
return URL.createObjectURL(blob)
}
}
+391
View File
@@ -0,0 +1,391 @@
import {TAG_MAKERNOTE, TAG_USERCOMMENT} from './tags.mjs'
import {TAG_IFD_EXIF, TAG_IFD_GPS, TAG_IFD_INTEROP} from './tags.mjs'
import {TAG_XMP, TAG_IPTC, TAG_ICC} from './tags.mjs'
import {tagKeys} from './tags.mjs'
import * as platform from './util/platform.mjs'
import {throwError} from './util/helpers.mjs'
import {segmentParsers, throwNotLoaded} from './plugins.mjs'
export const chunkedProps = [
'chunked',
'firstChunkSize',
'firstChunkSizeNode',
'firstChunkSizeBrowser',
'chunkSize',
'chunkLimit',
]
// List of other segments besides the tiff/exif itself
export const otherSegments = ['jfif', 'xmp', 'icc', 'iptc', 'ihdr']
// List of all other segments
export const segments = ['tiff', ...otherSegments]
// WARNING: this order is necessary for correctly assigning pick tags.
export const tiffBlocks = ['ifd0', 'ifd1', 'exif', 'gps', 'interop']
export const segmentsAndBlocks = [...segments, ...tiffBlocks]
export const tiffExtractables = ['makerNote', 'userComment']
export const inheritables = ['translateKeys', 'translateValues', 'reviveValues', 'multiSegment']
export const allFormatters = [...inheritables, 'sanitize', 'mergeOutput', 'silentErrors']
class SharedOptions {
get translate() {
return this.translateKeys
|| this.translateValues
|| this.reviveValues
}
}
class SubOptions extends SharedOptions {
enabled = false
skip = new Set
pick = new Set
deps = new Set // tags required by other blocks or segments (IFD pointers, makernotes)
translateKeys = false
translateValues = false
reviveValues = false
get needed() {
return this.enabled
|| this.deps.size > 0
}
constructor(key, defaultValue, userValue, parent) {
super()
this.key = key
this.enabled = defaultValue // todo: rename to extract
this.parse = this.enabled
this.applyInheritables(parent)
this.canBeFiltered = tiffBlocks.includes(key)
if (this.canBeFiltered)
this.dict = tagKeys.get(key)
if (userValue !== undefined) {
if (Array.isArray(userValue)) {
this.parse = this.enabled = true
if (this.canBeFiltered && userValue.length > 0)
this.translateTagSet(userValue, this.pick)
} else if (typeof userValue === 'object') {
this.enabled = true
this.parse = userValue.parse !== false
if (this.canBeFiltered) {
let {pick, skip} = userValue
if (pick && pick.length > 0) this.translateTagSet(pick, this.pick)
if (skip && skip.length > 0) this.translateTagSet(skip, this.skip)
}
this.applyInheritables(userValue)
} else if (userValue === true || userValue === false) {
this.parse = this.enabled = userValue
} else {
throwError(`Invalid options argument: ${userValue}`)
}
}
}
applyInheritables(origin) {
let key, val
for (key of inheritables) {
val = origin[key]
if (val !== undefined) this[key] = val
}
}
translateTagSet(inputArray, outputSet) {
if (this.dict) {
let {tagKeys, tagValues} = this.dict
let tag, index
for (tag of inputArray) {
if (typeof tag === 'string') {
index = tagValues.indexOf(tag)
if (index === -1) index = tagKeys.indexOf(Number(tag))
if (index !== -1) outputSet.add(Number(tagKeys[index]))
} else {
outputSet.add(tag)
}
}
} else {
for (let tag of inputArray) outputSet.add(tag)
}
}
finalizeFilters() {
if (!this.enabled && this.deps.size > 0) {
this.enabled = true
addToSet(this.pick, this.deps)
} else if (this.enabled && this.pick.size > 0) {
addToSet(this.pick, this.deps)
}
}
}
var defaults = {
// APP Segments
jfif: false, // jpeg only (jpeg file header)
tiff: true,
xmp: false,
icc: false,
iptc: false,
// TIFF BLOCKS
ifd0: true, // image
ifd1: false, // thumbnail
exif: true,
gps: true,
interop: false, // jpeg only
// undefined because we don't want Jpeg or Heic file parser to pick it up.
// Png parser will use Ihdr implicitly unless it's disabled by user.
ihdr: undefined, // png only (png file header)
// Notable TIFF tags
makerNote: false,
userComment: false,
// TODO: to be developed in future version, this is just a proposal for future api
multiSegment: false,
// FILTERS
// Array of tags that will be excluded when parsing.
// Saves performance because the tags aren't read at all and thus not further processed.
// Cannot be used along with 'pick' array.
skip: [],
// Array of the only tags that will be parsed. Those that are not specified will be ignored.
// Extremely saves performance because only selected few tags are processed.
// Useful for extracting few informations from a batch of many photos.
// Cannot be used along with 'skip' array.
pick: [],
// OUTPUT FORMATTERS
translateKeys: true,
translateValues: true,
reviveValues: true,
// Removes IFD pointers and other artifacts (useless for user) from output.
sanitize: true,
// Changes output format by merging all segments and blocks into single object.
// NOTE = Causes loss of thumbnail EXIF data.
mergeOutput: true,
// Fails silently and logs the file errors in output.errors instead of throwing error.
silentErrors: true,
// CHUNKED READER
// true - forces reading the whole file
// undefined - allows reading additional chunks of size `chunkSize` (chunked mode)
// false - does not allow reading additional chunks beyond `firstChunkSize` (chunked mode)
chunked: true,
// Size of the chunk that can be scanned for EXIF.
firstChunkSize: undefined,
// Size of the chunk that can be scanned for EXIF. Used by node.js.
firstChunkSizeNode: 512,
// In browser its sometimes better to download larger chunk in hope that it contains the
// whole EXIF (and not just its begining like in case of firstChunkSizeNode) in prevetion
// of additional loading and fetching.
firstChunkSizeBrowser: 65536, // 64kb
// Size of subsequent chunks that are read after first chunk (if needed)
chunkSize: 65536, // 64kb
// Maximum amount of additional chunks allowed to read in chunk mode.
// If the requested segments aren't parsed within N chunks (64*3 = 192kb) they probably aren't in the file.
chunkLimit: 5,
}
var existingInstances = new Map
export class Options extends SharedOptions {
// exporting for user to change
static default = defaults
static useCached(userOptions) {
let options = existingInstances.get(userOptions)
if (options !== undefined) return options
options = new this(userOptions)
existingInstances.set(userOptions, options)
return options
}
constructor(userOptions) {
super()
if (userOptions === true)
this.setupFromTrue()
else if (userOptions === undefined)
this.setupFromUndefined()
else if (Array.isArray(userOptions))
this.setupFromArray(userOptions)
else if (typeof userOptions === 'object')
this.setupFromObject(userOptions)
else
throwError(`Invalid options argument ${userOptions}`)
if (this.firstChunkSize === undefined)
this.firstChunkSize = platform.browser ? this.firstChunkSizeBrowser : this.firstChunkSizeNode
// thumbnail contains the same tags as ifd0. they're not necessary when `mergeOutput`
if (this.mergeOutput) this.ifd1.enabled = false
// translate global pick/skip tags & copy them to local segment/block settings
// handle the tiff->ifd0->exif->makernote pick dependency tree.
// this also adds picks to blocks & segments to efficiently parse through tiff.
this.filterNestedSegmentTags()
this.traverseTiffDependencyTree()
this.checkLoadedPlugins()
}
setupFromUndefined() {
let key
for (key of chunkedProps) this[key] = defaults[key]
for (key of allFormatters) this[key] = defaults[key]
for (key of tiffExtractables) this[key] = defaults[key]
for (key of segmentsAndBlocks) this[key] = new SubOptions(key, defaults[key], undefined, this)
}
setupFromTrue() {
let key
for (key of chunkedProps) this[key] = defaults[key]
for (key of allFormatters) this[key] = defaults[key]
for (key of tiffExtractables) this[key] = true
for (key of segmentsAndBlocks) this[key] = new SubOptions(key, true, undefined, this)
}
setupFromArray(userOptions) {
let key
for (key of chunkedProps) this[key] = defaults[key]
for (key of allFormatters) this[key] = defaults[key]
for (key of tiffExtractables) this[key] = defaults[key]
for (key of segmentsAndBlocks) this[key] = new SubOptions(key, false, undefined, this)
this.setupGlobalFilters(userOptions, undefined, tiffBlocks)
}
setupFromObject(userOptions) {
tiffBlocks.ifd0 = tiffBlocks.ifd0 || tiffBlocks.image
tiffBlocks.ifd1 = tiffBlocks.ifd1 || tiffBlocks.thumbnail
let key
// needed for adding additional (and internal options properties like stopAfterSos for jpg)
Object.assign(this, userOptions)
for (key of chunkedProps) this[key] = getDefined(userOptions[key], defaults[key])
for (key of allFormatters) this[key] = getDefined(userOptions[key], defaults[key])
for (key of tiffExtractables) this[key] = getDefined(userOptions[key], defaults[key])
for (key of segments) this[key] = new SubOptions(key, defaults[key], userOptions[key], this)
for (key of tiffBlocks) this[key] = new SubOptions(key, defaults[key], userOptions[key], this.tiff)
this.setupGlobalFilters(userOptions.pick, userOptions.skip, tiffBlocks, segmentsAndBlocks)
if (userOptions.tiff === true)
this.batchEnableWithBool(tiffBlocks, true)
else if (userOptions.tiff === false)
this.batchEnableWithUserValue(tiffBlocks, userOptions)
else if (Array.isArray(userOptions.tiff))
this.setupGlobalFilters(userOptions.tiff, undefined, tiffBlocks)
else if (typeof userOptions.tiff === 'object')
this.setupGlobalFilters(userOptions.tiff.pick, userOptions.tiff.skip, tiffBlocks)
}
batchEnableWithBool(keys, value) {
for (let key of keys)
this[key].enabled = value
}
batchEnableWithUserValue(keys, userOptions) {
for (let key of keys) {
let userOption = userOptions[key]
this[key].enabled = userOption !== false && userOption !== undefined
}
}
setupGlobalFilters(pick, skip, dictKeys, disableableSegsAndBlocks = dictKeys) {
if (pick && pick.length) {
// if we're only picking, we can safely disable all other blocks and segments
for (let blockKey of disableableSegsAndBlocks)
this[blockKey].enabled = false
let entries = findScopesForGlobalTagArray(pick, dictKeys)
for (let [blockKey, tags] of entries) {
addToSet(this[blockKey].pick, tags)
// the blocks of tags from global picks are the only blocks we'll parse.
this[blockKey].enabled = true
}
} else if (skip && skip.length) {
let entries = findScopesForGlobalTagArray(skip, dictKeys)
for (let [segKey, tags] of entries)
addToSet(this[segKey].skip, tags)
}
}
// XMP, IPTC can ICC can be stored as a tag in TIFF (in .tif files).
// This method adds them to skip list if these segments are not requested.
// Also applies to MakerNote and UserComment
filterNestedSegmentTags() {
let {ifd0, exif, xmp, iptc, icc} = this
// not segments, regular but notable TIFF tags
if (this.makerNote) exif.deps.add(TAG_MAKERNOTE)
else exif.skip.add(TAG_MAKERNOTE)
if (this.userComment) exif.deps.add(TAG_USERCOMMENT)
else exif.skip.add(TAG_USERCOMMENT)
// segments that can be stored as tags (but only?? in .tiff)
// note: not adding as deps because that is requested only in .tif file parser
if (!xmp.enabled) ifd0.skip.add(TAG_XMP)
if (!iptc.enabled) ifd0.skip.add(TAG_IPTC)
if (!icc.enabled) ifd0.skip.add(TAG_ICC)
}
// INVESTIGATE: can this be moved to Tiff Segment parser?
traverseTiffDependencyTree() {
let {ifd0, exif, gps, interop} = this
// interop pointer can be often found in EXIF besides IFD0.
if (interop.needed) {
exif.deps.add(TAG_IFD_INTEROP)
ifd0.deps.add(TAG_IFD_INTEROP)
}
// exif needs to go after interop. Exif may be needed for interop, and then ifd0 for exif
if (exif.needed) ifd0.deps.add(TAG_IFD_EXIF)
if (gps.needed) ifd0.deps.add(TAG_IFD_GPS)
this.tiff.enabled = tiffBlocks.some(key => this[key].enabled === true)
|| this.makerNote
|| this.userComment
// reenable all the blocks with pick or deps and lock in deps into picks if needed.
for (let key of tiffBlocks) this[key].finalizeFilters()
}
get onlyTiff() {
let bools = otherSegments.map(key => this[key].enabled)
if (bools.some(bool => bool === true)) return false
return this.tiff.enabled
}
checkLoadedPlugins() {
for (let key of segments)
if (this[key].enabled && !segmentParsers.has(key))
throwNotLoaded('segment parser', key)
}
}
function findScopesForGlobalTagArray(tagArray, dictKeys) {
let scopes = []
let dict, scopedTags, blockKey, tagEntry
for (blockKey of dictKeys) {
dict = tagKeys.get(blockKey)
scopedTags = []
for (tagEntry of dict) {
// NOTE: not expading tagEntry into [key, val] because of performance
if (tagArray.includes(tagEntry[0]) || tagArray.includes(tagEntry[1]))
scopedTags.push(tagEntry[0])
}
if (scopedTags.length)
scopes.push([blockKey, scopedTags])
}
return scopes
}
function getDefined(arg1, arg2) {
if (arg1 !== undefined) return arg1
if (arg2 !== undefined) return arg2
}
function addToSet(target, source) {
for (let item of source)
target.add(item)
}
+212
View File
@@ -0,0 +1,212 @@
import {BufferView} from './util/BufferView.mjs'
import {Options} from './options.mjs'
import {tagKeys, tagValues, tagRevivers} from './tags.mjs'
import {throwError} from './util/helpers.mjs'
import {segmentParsers} from './plugins.mjs'
const MAX_APP_SIZE = 65536 // 64kb
const DEFAULT = 'DEFAULT'
export class FileParserBase {
constructor(options, file, parsers) {
if (this.extendOptions)
this.extendOptions(options)
this.options = options
this.file = file
this.parsers = parsers
}
errors = []
injectSegment(type, chunk) {
if (this.options[type].enabled)
this.createParser(type, chunk)
}
createParser(type, chunk) {
let Parser = segmentParsers.get(type)
let parser = new Parser(chunk, this.options, this.file)
return this.parsers[type] = parser
}
// NOTE: This method was created to be reusable and not just one off. Mainly due to parsing ifd0 before thumbnail extraction.
// But also because we want to enable advanced users selectively add and execute parser on the fly.
createParsers(segments) {
// IDEA: dynamic loading through import(parser.type) ???
// We would need to know the type of segment, but we dont since its implemented in parser itself.
// I.E. Unless we first load apropriate parser, the segment is of unknown type.
for (let segment of segments) {
let {type, chunk} = segment
let segOpts = this.options[type]
if (segOpts && segOpts.enabled) {
let parser = this.parsers[type]
if (parser && parser.append) {
// TODO multisegment: to be implemented. or deleted. some types of data may be split into multiple APP segments (FLIR, maybe ICC)
//parser.append(chunk)
} else if (!parser) {
this.createParser(type, chunk)
}
}
}
}
async readSegments(segments) {
//let ranges = new Ranges(this.appSegments)
//await Promise.all(ranges.list.map(range => this.file.ensureChunk(range.offset, range.length)))
let promises = segments.map(this.ensureSegmentChunk)
await Promise.all(promises)
}
// TODO: deprecate
ensureSegmentChunk = async seg => {
let start = seg.start
let size = seg.size || MAX_APP_SIZE
if (this.file.chunked) {
if (this.file.available(start, size)) {
seg.chunk = this.file.subarray(start, size)
} else {
try {
seg.chunk = await this.file.readChunk(start, size)
} catch (err) {
throwError(`Couldn't read segment: ${JSON.stringify(seg)}. ${err.message}`)
}
}
} else if (this.file.byteLength > start + size) {
seg.chunk = this.file.subarray(start, size)
} else if (seg.size === undefined) {
// we dont know the length of segment and the file is much smaller than the fallback size of 64kbs (MAX_APP_SIZE)
seg.chunk = this.file.subarray(start)
} else {
throwError(`Segment unreachable: ` + JSON.stringify(seg))
}
return seg.chunk
}
}
/*
offset = where FF En starts
length = size of the whole APPn segment (header/marker + content)
start = start of the content
size = size of the content. i.e. from start till end
end = end of the content (as well as the APPn segment)
*/
export class AppSegmentParserBase {
static headerLength = 4
// name. Couldn't use static name property because it is used by contructor name
static type = undefined
// The data may span multiple APP segments.
static multiSegment = false
static canHandle = () => false
// offset + length === end | begining and end of the whole segment, including the segment header 0xFF 0xEn + two lenght bytes.
// start + size === end | begining and end of parseable content
static findPosition(buffer, offset) {
// length at offset+2 is the size of APPn content plus the two appN length bytes. it does not include te appN 0xFF 0xEn marker.
let length = buffer.getUint16(offset + 2) + 2
let headerLength = typeof this.headerLength === 'function'
? this.headerLength(buffer, offset, length)
: this.headerLength
let start = offset + headerLength
let size = length - headerLength
let end = start + size
return {offset, length, headerLength, start, size, end}
}
static parse(input, segOptions = {}) {
let options = new Options({[this.type]: segOptions})
let instance = new this(input, options, input)
return instance.parse()
}
normalizeInput(input) {
return input instanceof BufferView
? input
: new BufferView(input)
}
errors = []
// raw parsed tags
raw = new Map
constructor(chunk, options = {}, file) {
// BufferView instance of the segment chunk. Possibly a subview of the same memory shared with this.file
this.chunk = this.normalizeInput(chunk)
// BufferView instance of the whole file.
this.file = file
this.type = this.constructor.type
this.globalOptions = this.options = options // todo: rename to fileOptions ???
this.localOptions = options[this.type] // todo: rename to this.options
this.canTranslate = this.localOptions && this.localOptions.translate
}
// can be overriden by parses (namely TIFF) that inherits from this base class.
translate() {
if (this.canTranslate)
this.translated = this.translateBlock(this.raw, this.type)
}
get output() {
if (this.translated)
return this.translated
else if (this.raw)
return Object.fromEntries(this.raw)
}
// split into separate function so that it can be used by TIFF but shared with other parsers.
translateBlock(rawTags, blockKey) {
let revivers = tagRevivers.get(blockKey)
let valDict = tagValues.get(blockKey)
let keyDict = tagKeys.get(blockKey)
let blockOptions = this.options[blockKey] // todo: refactor tiff so this isn't needed anymore (in favor of segOptions & options)
let canRevive = blockOptions.reviveValues && !!revivers
let canTranslateVal = blockOptions.translateValues && !!valDict
let canTranslateKey = blockOptions.translateKeys && !!keyDict
let output = {}
for (let [key, val] of rawTags) {
if (canRevive && revivers.has(key))
val = revivers.get(key)(val)
else if (canTranslateVal && valDict.has(key))
val = this.translateValue(val, valDict.get(key))
if (canTranslateKey && keyDict.has(key))
key = keyDict.get(key) || key
output[key] = val
}
return output
}
// can be overriden by parses (namely ICC) that inherits from this base class.
translateValue(val, tagEnum) {
return tagEnum[val] || tagEnum[DEFAULT] || val
}
handleError = error => {
if (this.options.silentErrors)
this.errors.push(error.message)
else
throw error
}
assignToOutput(root, parserOutput) {
this.assignObjectToOutput(root, this.constructor.type, parserOutput)
}
assignObjectToOutput(root, key, parserOutput) {
if (this.globalOptions.mergeOutput)
return Object.assign(root, parserOutput)
if (root[key])
Object.assign(root[key], parserOutput)
else
root[key] = parserOutput
}
}
const isDefined = val => val !== undefined
const findDefined = (...values) => values.find(isDefined)
+40
View File
@@ -0,0 +1,40 @@
import {throwError} from './util/helpers.mjs'
export function throwUnknown(kind, key) {
throwError(`Unknown ${kind} '${key}'.`)
}
export function throwNotLoaded(kind, key) {
throwError(`${kind} '${key}' was not loaded, try using full build of exifr.`)
}
class PluginList extends Map {
constructor(kind) {
super()
this.kind = kind
}
// INVESTIGATE: move this check from runtime to options constructor
get(key, options) {
if (!this.has(key))
throwNotLoaded(this.kind, key)
if (options) {
if (!(key in options))
throwUnknown(this.kind, key)
if (!options[key].enabled)
throwNotLoaded(this.kind, key)
}
return super.get(key)
}
keyList() {
return Array.from(this.keys())
}
}
export var fileParsers = new PluginList('file parser')
export var segmentParsers = new PluginList('segment parser')
export var fileReaders = new PluginList('file reader')
+44
View File
@@ -0,0 +1,44 @@
import dynamicImport from '../util/import.mjs'
import global from './global.mjs'
import {set as setFetch} from './fetch.mjs'
if (!global.fetch) {
const httpPromise = dynamicImport('http', http => http)
const httpsPromise = dynamicImport('https', https => https)
const fetch = (url, {headers} = {}) => {
return new Promise(async (resolve, reject) => {
let {port, hostname, pathname, protocol, search} = new URL(url)
const options = {
method: 'GET',
hostname,
path: encodeURI(pathname) + search,
headers
}
if (port !== '') options.port = Number(port)
let lib = protocol === 'https:' ? await httpsPromise : await httpPromise
const req = lib.request(options, res => {
if (res.statusCode === 301 || res.statusCode === 302) {
let location = (new URL(res.headers.location, url)).toString()
return fetch(location, {headers}).then(resolve).catch(reject)
}
resolve({
status: res.statusCode,
arrayBuffer: () => new Promise(resolveAb => {
let buffers = []
res.on('data', buffer => buffers.push(buffer))
res.on('end', () => resolveAb(Buffer.concat(buffers)))
})
})
})
req.on('error', reject)
req.end()
})
}
setFetch(fetch)
}
+24
View File
@@ -0,0 +1,24 @@
import global from './global.mjs'
import {set as setFetch} from './fetch.mjs'
if (!global.fetch) {
setFetch(function(url, options = {}) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('get', url, true)
xhr.responseType = 'arraybuffer'
xhr.onerror = reject
if (options.headers)
for (const key in options.headers)
xhr.setRequestHeader(key, options.headers[key])
xhr.onload = () => {
resolve({
status: xhr.status,
arrayBuffer: () => Promise.resolve(xhr.response),
})
}
xhr.send(null)
})
})
}
+5
View File
@@ -0,0 +1,5 @@
import global from './global.mjs'
export let fetch = global.fetch
export const set = f => fetch = f
+1
View File
@@ -0,0 +1 @@
export default typeof self !== 'undefined' ? self : global
+160
View File
@@ -0,0 +1,160 @@
import global from './global.mjs'
export var ObjectKeys = Object.keys || (object => {
let keys = []
for (let key in object) keys.push(key)
return keys
})
export var ObjectValues = Object.values || (object => {
let values = []
for (let key in object) values.push(object[key])
return values
})
export var ObjectEntries = Object.entries || (object => {
let entries = []
for (let key in object) entries.push([key, object[key]])
return entries
})
export var ObjectAssign = Object.assign || ((target, ...objects) => {
objects.forEach(object => {
for (let key in object)
target[key] = object[key]
})
return target
})
export var ObjectFromEntries = Object.fromEntries || (entries => {
let object = {}
// not using for-of because it would transpile to use of Symbol.iterator
ArrayFrom(entries).forEach(([key, val]) => {
object[key] = val
})
return object
})
export var ArrayFrom = Array.from || (arg => {
if (arg instanceof Map) {
let entries = []
arg.forEach((val, key) => entries.push([key, val]))
return entries
// todo iterators (map.keys(), map.values())
} else {
return Array.prototype.slice.call(arg)
//return [].slice.call(arg)
}
})
function includes(item) {
return this.indexOf(item) !== -1
}
if (!Array.prototype.includes) Array.prototype.includes = includes
if (!String.prototype.includes) String.prototype.includes = includes
if (!String.prototype.startsWith) String.prototype.startsWith = function(search, pos = 0) {
return this.substring(pos, pos + search.length) === search
}
if (!String.prototype.endsWith) String.prototype.endsWith = function(search, len = this.length) {
return this.substring(len - search.length, len) === search
}
// IE doesnt support initialization with constructor argument
export var NewSet = arr => {
let set = []
Object.defineProperties(set, {
size: {
get() {
return this.length
}
},
has: {
value(item) {
return this.indexOf(item) !== -1
}
},
add: {
value(item) {
if (!this.has(item)) this.push(item)
}
},
delete: {
value(item) {
if (this.has(item)) {
let index = this.indexOf(item)
this.splice(index, 1)
}
}
},
})
if (Array.isArray(arr))
for (let i = 0; i < arr.length; i++)
set.add(arr[i])
return set
}
export var NewMap = arr => {
return new Map(arr)
}
var hasFullyImplementedMap = typeof global.Map !== 'undefined' && global.Map.prototype.keys !== undefined
export var Map = hasFullyImplementedMap ? global.Map : class Map {
constructor(init) {
this.clear()
if (init)
for (var i = 0; i < init.length; i++)
this.set(init[i][0], init[i][1])
}
clear() {
this._map = {}
this._keys = []
}
get size() {
return this._keys.length
}
get(key) {
return this._map["map_"+key];
}
set(key, value) {
this._map["map_"+key]=value;
if(this._keys.indexOf(key)<0)this._keys.push(key);
return this;
}
has(key) {
return this._keys.indexOf(key)>=0;
}
delete(key) {
var idx=this._keys.indexOf(key)
if (idx < 0) return false
delete this._map["map_" + key]
this._keys.splice(idx, 1)
return true
}
keys() {
return this._keys.slice(0)
}
values() {
return this._keys.map(key => this.get(key))
}
entries() {
return this._keys.map(key => [key, this.get(key)])
}
forEach(callback, thisArg) {
for (var i = 0; i < this._keys.length; i++)
callback.call(thisArg, this._map["map_" + this._keys[i]], this._keys[i], this);
}
}
+75
View File
@@ -0,0 +1,75 @@
import * as platform from './util/platform.mjs'
import {BufferView} from './util/BufferView.mjs'
import {throwError} from './util/helpers.mjs'
import {fileReaders} from './plugins.mjs'
import {fetch} from './polyfill/fetch.mjs'
// TODO: - API for including 3rd party XML parser
const INVALID_INPUT = 'Invalid input argument'
export function read(arg, options) {
if (typeof arg === 'string')
return readString(arg, options)
else if (platform.browser && !platform.worker && arg instanceof HTMLImageElement)
return readString(arg.src, options)
else if (arg instanceof Uint8Array || arg instanceof ArrayBuffer || arg instanceof DataView)
return new BufferView(arg)
else if (platform.browser && arg instanceof Blob)
return callReader(arg, options, 'blob', readBlobAsArrayBuffer)
else
throwError(INVALID_INPUT)
}
function readString(arg, options) {
if (isBase64Url(arg))
return callReaderClass(arg, options, 'base64')
else if (platform.node && arg.includes('://')) // fs.read takes precedence over fetch but node can now fetch as well. This needs to be before fs.
return callReader(arg, options, 'url', fetchUrlAsArrayBuffer)
else if (platform.node) // Keep node before browser platform check due to electron/nwjs where node's fs should take priority over fetch and file:///
return callReaderClass(arg, options, 'fs')
else if (platform.browser) // All other string here are just urls and we can safely fetch them
return callReader(arg, options, 'url', fetchUrlAsArrayBuffer)
else
throwError(INVALID_INPUT)
}
async function callReader(url, options, readerName, readerFn) {
if (fileReaders.has(readerName))
return callReaderClass(url, options, readerName)
else if (readerFn)
return callReaderFunction(url, readerFn)
else
throwError(`Parser ${readerName} is not loaded`)
}
async function callReaderClass(input, options, readerName) {
let Reader = fileReaders.get(readerName)
let file = new Reader(input, options)
await file.read()
return file
}
async function callReaderFunction(input, readerFn) {
let rawData = await readerFn(input)
return new BufferView(rawData)
}
// FALLBACK FULL-FILE READERS (when ChunkedReader and the classes aren't available)
export const fetchUrlAsArrayBuffer = url => fetch(url).then(res => res.arrayBuffer())
export const readBlobAsArrayBuffer = blob => new Promise((resolve, reject) => {
let reader = new FileReader()
reader.onloadend = () => resolve(reader.result || new ArrayBuffer)
reader.onerror = reject
reader.readAsArrayBuffer(blob)
})
// HELPER FUNCTIONS
function isBase64Url(string) {
return string.startsWith('data:')
|| string.length > 10000 // naive
}
+203
View File
@@ -0,0 +1,203 @@
import {AppSegmentParserBase} from '../parser.mjs'
import {segmentParsers} from '../plugins.mjs'
import {throwError, normalizeString} from '../util/helpers.mjs'
import {BufferView} from '../util/BufferView.mjs'
const PROFILE_HEADER_LENGTH = 84
const TAG_TYPE_DESC = 'desc'
const TAG_TYPE_MLUC = 'mluc'
const TAG_TYPE_TEXT = 'text'
const TAG_TYPE_SIG = 'sig '
// TODO: other types 'mft2', 'XYZ '
const EMPTY_VALUE = '\x00\x00\x00\x00'
export default class Icc extends AppSegmentParserBase {
static type = 'icc'
static multiSegment = true
static headerLength = 18
static canHandle(chunk, offset) {
return chunk.getUint8(offset + 1) === 0xE2
&& chunk.getUint32(offset + 4) === 0x4943435f // ICC_
// full header is: ICC_PROFILE
}
static findPosition(chunk, offset) {
let seg = super.findPosition(chunk, offset)
seg.chunkNumber = chunk.getUint8(offset + 16)
seg.chunkCount = chunk.getUint8(offset + 17)
seg.multiSegment = seg.chunkCount > 1
return seg
}
static handleMultiSegments(segments) {
return concatChunks(segments)
}
parse() {
this.raw = new Map
this.parseHeader()
this.parseTags()
this.translate()
return this.output
}
parseHeader() {
let {raw} = this
if (this.chunk.byteLength < PROFILE_HEADER_LENGTH)
throwError('ICC header is too short')
for (let [offset, parse] of Object.entries(headerParsers)) {
offset = parseInt(offset, 10)
let val = parse(this.chunk, offset)
if (val === EMPTY_VALUE) continue
raw.set(offset, val)
}
}
parseTags() {
let {raw} = this
let tagCount = this.chunk.getUint32(128)
let offset = 132
let chunkLength = this.chunk.byteLength
let code, valueOffset, valueLength, type, value
while (tagCount--) {
code = this.chunk.getString(offset, 4)
valueOffset = this.chunk.getUint32(offset + 4)
valueLength = this.chunk.getUint32(offset + 8)
type = this.chunk.getString(valueOffset, 4)
if (valueOffset + valueLength > chunkLength) {
console.warn('reached the end of the first ICC chunk. Enable options.tiff.multiSegment to read all ICC segments.')
return
}
value = this.parseTag(type, valueOffset, valueLength)
// Not all the type parsers are implemented.
if (value !== undefined && value !== EMPTY_VALUE)
raw.set(code, value)
offset += 12
}
}
parseTag(type, offset, length) {
switch (type) {
case TAG_TYPE_DESC: return this.parseDesc(offset)
case TAG_TYPE_MLUC: return this.parseMluc(offset)
case TAG_TYPE_TEXT: return this.parseText(offset, length)
case TAG_TYPE_SIG: return this.parseSig(offset)
// TODO: implement more types
}
if (offset + length > this.chunk.byteLength) {
// TODO: handle these when multi-segment ICC is being implemented
// look out for issue-metadata-extractor-65.jpg
} else {
return this.chunk.getUint8Array(offset, length)
}
}
parseDesc(offset) {
let length = this.chunk.getUint32(offset + 8) - 1 // last byte is null termination
return normalizeString(this.chunk.getString(offset + 12, length))
}
parseText(offset, length) {
return normalizeString(this.chunk.getString(offset + 8, length - 8))
}
// NOTE: some tags end with empty space. TODO: investigate. maybe add .trim()
parseSig(offset) {
return normalizeString(this.chunk.getString(offset + 8, 4))
}
// Multi Localized Unicode Type
parseMluc(tagOffset) {
let {chunk} = this
let entryCount = chunk.getUint32(tagOffset + 8)
let entrySize = chunk.getUint32(tagOffset + 12)
let entryOffset = tagOffset + 16
let values = []
for (let i = 0; i < entryCount; i++) {
let lang = chunk.getString(entryOffset + 0, 2)
let country = chunk.getString(entryOffset + 2, 2)
let length = chunk.getUint32(entryOffset + 4)
let offset = chunk.getUint32(entryOffset + 8) + tagOffset
let text = normalizeString(chunk.getUnicodeString(offset, length))
values.push({lang, country, text})
entryOffset += entrySize
}
if (entryCount === 1)
return values[0].text
else
return values
}
translateValue(val, tagEnum) {
if (typeof val === 'string')
return tagEnum[val] || tagEnum[val.toLowerCase()] || val
else
return tagEnum[val] || val
}
}
const headerParsers = {
4: parseString,
8: parseVersion,
12: parseString,
16: parseString,
20: parseString,
24: parseDate,
36: parseString,
40: parseString,
48: parseString,
52: parseString,
64: (view, offset) => view.getUint32(offset),
80: parseString
}
function parseString(view, offset) {
return normalizeString(view.getString(offset, 4))
}
function parseVersion(view, offset) {
return [
view.getUint8(offset),
view.getUint8(offset + 1) >> 4,
view.getUint8(offset + 1) % 16,
]
.map(num => num.toString(10))
.join('.')
}
function parseDate(view, offset) {
const year = view.getUint16(offset)
const month = view.getUint16(offset + 2) - 1
const day = view.getUint16(offset + 4)
const hours = view.getUint16(offset + 6)
const minutes = view.getUint16(offset + 8)
const seconds = view.getUint16(offset + 10)
return new Date(Date.UTC(year, month, day, hours, minutes, seconds))
}
function concatChunks(chunks) {
let buffers = chunks.map(s => s.chunk.toUint8())
let combined = concatBuffers(buffers)
return new BufferView(combined)
}
function concatBuffers(buffers) {
let ArrayType = buffers[0].constructor
let totalLength = 0
for (let buffer of buffers) totalLength += buffer.length
let result = new ArrayType(totalLength)
let offset = 0
for (let buffer of buffers) {
result.set(buffer, offset)
offset += buffer.length
}
return result
}
segmentParsers.set('icc', Icc)
+35
View File
@@ -0,0 +1,35 @@
import {AppSegmentParserBase} from '../parser.mjs'
import {segmentParsers} from '../plugins.mjs'
export default class Ihdr extends AppSegmentParserBase {
static type = 'ihdr'
parse() {
this.parseTags()
this.translate()
return this.output
}
parseTags() {
this.raw = new Map([
[0, this.chunk.getUint32(0)],
[4, this.chunk.getUint32(4)],
[8, this.chunk.getUint8(8)],
[9, this.chunk.getUint8(9)],
[10, this.chunk.getUint8(10)],
[11, this.chunk.getUint8(11)],
[12, this.chunk.getUint8(12)],
// PNG contains additional string data in free tEXt chunks.
// These kinda belong to IHDR, but are not part of the IHDR chunk
// and would require additional segment-parser class. Instead these
// chunks are handled in the PNG file parser itself and injected
// into this.raw map. Here, we're making sure they're included in output.
...Array.from(this.raw)
])
}
}
segmentParsers.set('ihdr', Ihdr)
+114
View File
@@ -0,0 +1,114 @@
import {AppSegmentParserBase} from '../parser.mjs'
import {segmentParsers} from '../plugins.mjs'
/*
http://fileformats.archiveteam.org/wiki/Photoshop_Image_Resources
In a TIFF file, tag 34377 contains Photoshop Image Resources.
In a JPEG file, an APP13 marker with an identifier of "Photoshop 3.0" contains Photoshop Image Resources.
Resource ID 0x0404 contains IPTC data.
Resource ID 0x040c may contain a thumbnail in JPEG/JFIF format.
Resource ID 0x040F contains an ICC profile.
Resource ID 0x0422 contains Exif data.
Resource ID 0x0424 contains XMP data.
*/
const HEADER_8 = 0x38
const HEADER_8BIM = 0x3842494D
const HEADER_IPTC = 0x0404
const MARKER = 0xED
const PHOTOSHOP = 'Photoshop'
export default class Iptc extends AppSegmentParserBase {
static type = 'iptc'
static translateValues = false
static reviveValues = false
// APP13 very complicated and doesn't just simply contain IPTC data.
// It is in fact Photoshop format, which contains it's own chunks, each starting with 8BIM header.
// IPTC is just one of those chunks and may start several hundreds of bytes into the segment.
// IPTC chunk in the format starts with 8BIM followed by 4 4 (0x0404)
// TLDR: We can't just compare bytes. The chunk has to be traversed.
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_38034
static canHandle(file, offset, length) {
let isApp13 = file.getUint8(offset + 1) === MARKER
&& file.getString(offset + 4, 9) === PHOTOSHOP
if (!isApp13) return false
let i = this.containsIptc8bim(file, offset, length)
return i !== undefined
}
// WARNING: There can be files with APP13 segment, containing various Photoshop related
// data, but no IPTC. We musn't falsely accept these segments as IPTC!
static headerLength(chunk, offset, length) {
let nameHeaderLength
let i = this.containsIptc8bim(chunk, offset, length)
if (i !== undefined) {
// Get the length of the name header (which is padded to an even number of bytes)
nameHeaderLength = chunk.getUint8(offset + i + 7)
if (nameHeaderLength % 2 !== 0) nameHeaderLength += 1
// Check for pre photoshop 6 format
if (nameHeaderLength === 0) nameHeaderLength = 4
return i + 8 + nameHeaderLength
}
}
static containsIptc8bim(chunk, offset, length) {
for (let i = 0; i < length; i++)
if (this.isIptcSegmentHead(chunk, offset + i))
return i
}
static isIptcSegmentHead(chunk, offset) {
// isIptcSegmentHead is called on each byte while traversing the file.
// This could be hundreds of times. We don't want to read the same overlaping range
// over and over, so just read the first byte and only then continue.
return chunk.getUint8(offset) === HEADER_8 // 8 - photoshop segment start
&& chunk.getUint32(offset) === HEADER_8BIM // 8BIM - photoshop segment start
&& chunk.getUint16(offset + 4) === HEADER_IPTC // IPTC segment head
}
parse() {
let {raw} = this
let iterableLength = this.chunk.byteLength - 1
let foundFirstProp = false
for (let offset = 0; offset < iterableLength; offset++) {
// NOTE: IPTC has wariable header. data can start immediately or after couple of bytes. So we need to seek
// through the data until we find the first 1C02 marker.
// reading Uint8 and then another to prevent unnecessarry read of two subsequent bytes, when iterating
if (this.chunk.getUint8(offset) === 0x1C && this.chunk.getUint8(offset + 1) === 0x02) {
foundFirstProp = true
let size = this.chunk.getUint16(offset + 3)
let key = this.chunk.getUint8(offset + 2)
let val = this.chunk.getLatin1String(offset + 5, size)
raw.set(key, this.pluralizeValue(raw.get(key), val))
// skip iterating over the bytes we've already read
offset += 4 + size
} else if (foundFirstProp) {
// We would infinately loop through the rest of the chunk (due to the dynamic header length).
break
}
}
this.translate()
return this.output
}
pluralizeValue(existingVal, newVal) {
if (existingVal !== undefined) {
if (existingVal instanceof Array) {
existingVal.push(newVal)
return existingVal
} else {
return [existingVal, newVal]
}
} else {
return newVal
}
}
}
segmentParsers.set('iptc', Iptc)
+46
View File
@@ -0,0 +1,46 @@
import {AppSegmentParserBase} from '../parser.mjs'
import {segmentParsers} from '../plugins.mjs'
// tags https://exiftool.org/TagNames/JFIF.html
export default class Jfif extends AppSegmentParserBase {
static type = 'jfif'
static headerLength = 9
static canHandle(buffer, offset) {
return buffer.getUint8(offset + 1) === 0xE0
&& buffer.getUint32(offset + 4) === 0x4A464946 // 'JFIF'
&& buffer.getUint8(offset + 8) === 0x00 // followed by '\0'
}
parse() {
this.parseTags()
this.translate()
return this.output
}
parseTags() {
this.raw = new Map([
[0, this.chunk.getUint16(0)],
[2, this.chunk.getUint8(2)],
[3, this.chunk.getUint16(3)],
[5, this.chunk.getUint16(5)],
[7, this.chunk.getUint8(7)],
[8, this.chunk.getUint8(8)],
])
}
// TODO: hook this in into revive/translate API
/*
static prettify(jfif) {
let versionInt = jfif.JFIFVersion
jfif.JFIFVersion = ((versionInt & 0xFF00) >> 8).toString(16) + '.' + (versionInt & 0x00FF).toString(16).padStart(2, '0')
jfif.ResolutionUnit = jfif.ResolutionUnit === 2 ? 'cm' : jfif.ResolutionUnit === 1 ? 'inches' : jfif.ResolutionUnit
return jfif
}
*/
}
segmentParsers.set('jfif', Jfif)
+427
View File
@@ -0,0 +1,427 @@
import {AppSegmentParserBase} from '../parser.mjs'
import {segmentParsers} from '../plugins.mjs'
import {TAG_IFD_EXIF, TAG_IFD_GPS, TAG_IFD_INTEROP, TAG_MAKERNOTE, TAG_USERCOMMENT, TAG_XMP, TAG_IPTC, TAG_ICC} from '../tags.mjs'
import {TAG_GPS_LATREF, TAG_GPS_LAT, TAG_GPS_LONREF, TAG_GPS_LON} from '../tags.mjs'
import {TIFF_LITTLE_ENDIAN, TIFF_BIG_ENDIAN} from '../util/helpers.mjs'
import {isEmpty, normalizeString} from '../util/helpers.mjs'
import {throwError, estimateMetadataSize} from '../util/helpers.mjs'
import {tiffBlocks} from '../options.mjs'
const MALFORMED = 'Malformed EXIF data'
const THUMB_OFFSET = 0x0201
const THUMB_LENGTH = 0x0202
const BYTE = 1
const ASCII = 2
const SHORT = 3
const LONG = 4
const RATIONAL = 5
const SBYTE = 6
const UNDEFINED = 7
const SSHORT = 8
const SLONG = 9
const SRATIONAL = 10
const FLOAT = 11
const DOUBLE = 12
const IFD = 13
const SIZE_LOOKUP = [
undefined, // nothing at index 0
1, // BYTE - 8-bit unsigned integer
1, // ASCII - 8-bit bytes w/ last byte null
2, // SHORT - 16-bit unsigned integer
4, // LONG - 32-bit unsigned integer
8, // RATIONAL - 64-bit unsigned fraction of two 32-bit unsigned integers
1, // SBYTE - 8-bit signed integer
1, // UNDEFINED - 8-bit untyped data
2, // SSHORT - 16-bit signed integer
4, // SLONG - 32-bit signed integer
8, // SRATIONAL - 64-bit signed fraction of two 32-bit signed integers
4, // FLOAT, - 32-bit IEEE floating point
8, // DOUBLE - 64-bit IEEE floating point
// https://sno.phy.queensu.ca/~phil/exiftool/standards.html
4 // IFD (sometimes used instead of 4 LONG)
]
function getTypedArray(type) {
switch (type) {
case BYTE : return Uint8Array
case SHORT : return Uint16Array
case LONG : return Uint32Array
case RATIONAL : return Array
case SBYTE : return Int8Array
case SSHORT : return Int16Array
case SLONG : return Int32Array
case SRATIONAL: return Array
case FLOAT : return Float32Array
case DOUBLE : return Float64Array
default: return Array
}
}
// WARNING: In .tif files, exif can be before ifd0
// - namely issue-metadata-extractor-152.tif offsets are: EXIF 2468122, IFD0 2468716, GPS 2468550
// jpg wraps tiff into app1 segment.
export class TiffCore extends AppSegmentParserBase {
// TODO: future API
//tagsOutsideChunk = []
parseHeader() {
// Detect endian 11th byte of TIFF (1st after header)
var byteOrder = this.chunk.getUint16()
if (byteOrder === TIFF_LITTLE_ENDIAN)
this.le = true // little endian
else if (byteOrder === TIFF_BIG_ENDIAN)
this.le = false // big endian
// else
// throwError('Invalid EXIF data: expected byte order marker (0x4949 or 0x4D4D).')
this.chunk.le = this.le
/*
// Bytes 8 & 9 are expected to be 00 2A.
if (this.chunk.getUint16(2) !== 0x002A)
throwError('Invalid EXIF data: expected 0x002A.')
*/
this.headerParsed = true
}
parseTags(offset, blockKey, block = new Map) {
let {pick, skip} = this.options[blockKey]
pick = new Set(pick) // clone data from options because we will modify it here
let onlyPick = pick.size > 0
let nothingToSkip = skip.size === 0
let entriesCount = this.chunk.getUint16(offset)
offset += 2
for (let i = 0; i < entriesCount; i++) {
let tag = this.chunk.getUint16(offset)
if (onlyPick) {
if (pick.has(tag)) {
// We have a list only of tags to pick, this tag is one of them, so read it.
block.set(tag, this.parseTag(offset, tag, blockKey))
pick.delete(tag)
if (pick.size === 0) break
}
} else if (nothingToSkip || !skip.has(tag)) {
// We're not limiting what tags to pick. Also this tag is not on a blacklist.
block.set(tag, this.parseTag(offset, tag, blockKey))
}
offset += 12
}
return block
}
parseTag(offset, tag, blockKey) {
let {chunk} = this
let type = chunk.getUint16(offset + 2)
let valueCount = chunk.getUint32(offset + 4)
let valueSize = SIZE_LOOKUP[type]
let totalSize = valueSize * valueCount
if (totalSize <= 4)
offset = offset + 8
else
offset = chunk.getUint32(offset + 8)
if (type < BYTE || type > IFD)
throwError(`Invalid TIFF value type. block: ${blockKey.toUpperCase()}, tag: ${tag.toString(16)}, type: ${type}, offset ${offset}`)
if (offset > chunk.byteLength) {
// TODO: future API
//this.tagsOutsideChunk.push({tag, offset, type, valueCount, valueSize, totalSize})
throwError(`Invalid TIFF value offset. block: ${blockKey.toUpperCase()}, tag: ${tag.toString(16)}, type: ${type}, offset ${offset} is outside of chunk size ${chunk.byteLength}`)
}
if (type === BYTE) // type 1
return chunk.getUint8Array(offset, valueCount)
// ascii strings, array of 8bits/1byte values.
if (type === ASCII) // type 2
return normalizeString(chunk.getString(offset, valueCount))
// undefined/buffers of 8bit/1byte values.
if (type === UNDEFINED) // type 7
return chunk.getUint8Array(offset, valueCount)
// Now that special cases are solved, we can return the normal uint/int value(s).
if (valueCount === 1) {
// Return single value.
return this.parseTagValue(type, offset)
} else {
// Return array of values.
let ArrayType = getTypedArray(type)
let arr = new ArrayType(valueCount)
// rational numbers are stored as two integers that we divide when parsing.
let offsetIncrement = valueSize
for (let i = 0; i < valueCount; i++) {
arr[i] = this.parseTagValue(type, offset)
offset += offsetIncrement
}
return arr
}
}
parseTagValue(type, offset) {
let {chunk} = this
switch (type) {
case BYTE : return chunk.getUint8(offset)
case SHORT : return chunk.getUint16(offset)
case LONG : return chunk.getUint32(offset)
case RATIONAL : return chunk.getUint32(offset) / chunk.getUint32(offset + 4)
case SBYTE : return chunk.getInt8(offset)
case SSHORT : return chunk.getInt16(offset)
case SLONG : return chunk.getInt32(offset)
case SRATIONAL: return chunk.getInt32(offset) / chunk.getInt32(offset + 4)
case FLOAT : return chunk.getFloat(offset)
case DOUBLE : return chunk.getDouble(offset)
case 13: return chunk.getUint32(offset)
default: throwError(`Invalid tiff type ${type}`)
}
}
}
const TAG_FILESOURCE = 0xa300
const TAG_SCENETYPE = 0xa301
/*
JPEG with EXIF segment starts with App1 header (FF E1, length, 'Exif\0\0') and then follows the TIFF.
Whereas .tif file format starts with the TIFF structure right away.
APP1 HEADER (only in JPEG)
- FF E1 - segment marker
- 2Bytes - segment length
- 45 78 69 66 00 00 - string 'Exif\0\0'
APP1 CONTENT
- TIFF HEADER (2b byte order, 2b tiff id, 4b offset of ifd1)
- IFD0
- Exif IFD
- Interop IFD
- GPS IFD
- IFD1
*/
export class TiffExif extends TiffCore {
static type = 'tiff'
static headerLength = 10
// .tif files do no have any APPn segments. and usually start right with TIFF header
// .jpg files can have multiple APPn segments. They always have APP1 whic is a wrapper for TIFF.
// We support both jpg and tiff so we're not looking for app1 segment but directly for TIFF
// because app1 in jpg is only container for tiff.
static canHandle(view, offset) {
return view.getUint8(offset + 1) === 0xE1
&& view.getUint32(offset + 4) === 0x45786966 // 'Exif'
&& view.getUint16(offset + 8) === 0x0000 // followed by '\0'
}
// APP1 includes TIFF formatted values, grouped into IFD blocks (IFD0, Exif, Interop, GPS, IFD1)
async parse() {
this.parseHeader()
let {options} = this
// WARNING: In .tif files, exif can be before ifd0 (issue-metadata-extractor-152.tif has: EXIF 2468122, IFD0 2468716)
if (options.ifd0.enabled) await this.parseIfd0Block() // APP1 - IFD0
if (options.exif.enabled) await this.safeParse('parseExifBlock') // APP1 - EXIF IFD
if (options.gps.enabled) await this.safeParse('parseGpsBlock') // APP1 - GPS IFD
if (options.interop.enabled) await this.safeParse('parseInteropBlock') // APP1 - Interop IFD
if (options.ifd1.enabled) await this.safeParse('parseThumbnailBlock') // APP1 - IFD1
return this.createOutput()
//return this.output
}
// this is ugly but needed for async-to-promise babel plugin to work
safeParse(methodName) {
let result = this[methodName]()
// Ugly IE fix, async functions always return promises, but not when transpiled.
if (result.catch !== undefined) result = result.catch(this.handleError)
return result
}
findIfd0Offset() {
if (this.ifd0Offset === undefined)
this.ifd0Offset = this.chunk.getUint32(4)
}
findIfd1Offset() {
if (this.ifd1Offset === undefined) {
this.findIfd0Offset()
let ifd0Entries = this.chunk.getUint16(this.ifd0Offset)
let temp = this.ifd0Offset + 2 + (ifd0Entries * 12)
// IFD1 offset is number of bytes from start of TIFF header where thumbnail info is.
this.ifd1Offset = this.chunk.getUint32(temp)
}
}
parseBlock(offset, blockKey) {
let block = new Map
this[blockKey] = block
this.parseTags(offset, blockKey, block)
return block
}
async parseIfd0Block() {
if (this.ifd0) return
let {file} = this
// Read the IFD0 segment with basic info about the image
// (width, height, maker, model and pointers to another segments)
this.findIfd0Offset()
if (this.ifd0Offset < 8)
throwError(MALFORMED)
if (!file.chunked && this.ifd0Offset > file.byteLength)
throwError(`IFD0 offset points to outside of file.\nthis.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${file.byteLength}`)
//await this.ensureBlockChunk(this.ifd0Offset, estimateMetadataSize(this.options))
if (file.tiff)
await file.ensureChunk(this.ifd0Offset, estimateMetadataSize(this.options))
// Parse IFD0 block.
let ifd0 = this.parseBlock(this.ifd0Offset, 'ifd0')
// Cancel if the ifd0 is empty (imaged created from scratch in photoshop).
if (ifd0.size === 0) return
// Store offsets of other blocks in the TIFF segment.
this.exifOffset = ifd0.get(TAG_IFD_EXIF)
this.interopOffset = ifd0.get(TAG_IFD_INTEROP)
this.gpsOffset = ifd0.get(TAG_IFD_GPS)
this.xmp = ifd0.get(TAG_XMP)
this.iptc = ifd0.get(TAG_IPTC)
this.icc = ifd0.get(TAG_ICC)
//this.photoshop = ifd0.get(0x8649)
// IFD0 segment also contains offset pointers to another segments deeper within the EXIF.
if (this.options.sanitize) {
ifd0.delete(TAG_IFD_EXIF)
ifd0.delete(TAG_IFD_INTEROP)
ifd0.delete(TAG_IFD_GPS)
ifd0.delete(TAG_XMP)
ifd0.delete(TAG_IPTC)
ifd0.delete(TAG_ICC)
}
return ifd0
}
// EXIF block of TIFF of APP1 segment
// 0x8769
async parseExifBlock() {
if (this.exif) return
if (!this.ifd0) await this.parseIfd0Block()
if (this.exifOffset === undefined) return
if (this.file.tiff)
await this.file.ensureChunk(this.exifOffset, estimateMetadataSize(this.options))
let exif = this.parseBlock(this.exifOffset, 'exif')
if (!this.interopOffset) this.interopOffset = exif.get(TAG_IFD_INTEROP)
this.makerNote = exif.get(TAG_MAKERNOTE)
this.userComment = exif.get(TAG_USERCOMMENT)
if (this.options.sanitize) {
exif.delete(TAG_IFD_INTEROP)
exif.delete(TAG_MAKERNOTE)
exif.delete(TAG_USERCOMMENT)
}
this.unpack(exif, TAG_FILESOURCE)
this.unpack(exif, TAG_SCENETYPE)
return exif
}
unpack(map, key) {
let value = map.get(key)
if (value && value.length === 1)
map.set(key, value[0])
}
// GPS block of TIFF of APP1 segment
// 0x8825
async parseGpsBlock() {
if (this.gps) return
if (!this.ifd0) await this.parseIfd0Block()
if (this.gpsOffset === undefined) return
let gps = this.parseBlock(this.gpsOffset, 'gps')
if (gps && gps.has(TAG_GPS_LAT) && gps.has(TAG_GPS_LON)) {
// TODO: assign this to this.translated or this.output when blocks are broken down to separate classes
//gps.latitude = ConvertDMSToDD(...gps.get(TAG_GPS_LAT), gps.get(TAG_GPS_LATREF))
//gps.longitude = ConvertDMSToDD(...gps.get(TAG_GPS_LON), gps.get(TAG_GPS_LONREF))
gps.set('latitude', ConvertDMSToDD(...gps.get(TAG_GPS_LAT), gps.get(TAG_GPS_LATREF)))
gps.set('longitude', ConvertDMSToDD(...gps.get(TAG_GPS_LON), gps.get(TAG_GPS_LONREF)))
}
return gps
}
// INTEROP block of TIFF of APP1 segment
// 0xA005
async parseInteropBlock() {
if (this.interop) return
if (!this.ifd0) await this.parseIfd0Block()
if (this.interopOffset === undefined && !this.exif) await this.parseExifBlock()
if (this.interopOffset === undefined) return
return this.parseBlock(this.interopOffset, 'interop')
}
// THUMBNAIL block of TIFF of APP1 segment
// parsing this block is skipped when mergeOutput is true because thumbnail block contains with the same tags like ifd0 block
// and one would override the other.
async parseThumbnailBlock(force = false) {
if (this.ifd1 || this.ifd1Parsed) return
if (this.options.mergeOutput && !force) return
this.findIfd1Offset()
if (this.ifd1Offset > 0) {
this.parseBlock(this.ifd1Offset, 'ifd1')
this.ifd1Parsed = true
}
return this.ifd1
}
// THUMBNAIL buffer of TIFF of APP1 segment
async extractThumbnail() {
if (!this.headerParsed) this.parseHeader()
if (!this.ifd1Parsed) await this.parseThumbnailBlock(true)
if (this.ifd1 === undefined) return
// TODO: replace 'ThumbnailOffset' & 'ThumbnailLength' by raw keys (when tag dict is not included)
let offset = this.ifd1.get(THUMB_OFFSET)
let length = this.ifd1.get(THUMB_LENGTH)
return this.chunk.getUint8Array(offset, length)
}
get image() {return this.ifd0}
get thumbnail() {return this.ifd1}
createOutput() {
let tiff = {}
let block, blockKey, blockOutput
for (blockKey of tiffBlocks) {
block = this[blockKey]
if (isEmpty(block)) continue
if (this.canTranslate)
blockOutput = this.translateBlock(block, blockKey)
else
blockOutput = Object.fromEntries(block)
if (this.options.mergeOutput) {
// NOTE: Not assigning thumbnail because it contains the same tags as ifd0.
if (blockKey === 'ifd1') continue
Object.assign(tiff, blockOutput)
} else {
tiff[blockKey] = blockOutput
}
}
if (this.makerNote) tiff.makerNote = this.makerNote
if (this.userComment) tiff.userComment = this.userComment
return tiff
}
assignToOutput(root, tiff) {
if (this.globalOptions.mergeOutput) {
// xmp contains only properties
Object.assign(root, tiff)
} else {
for (let [blockKey, block] of Object.entries(tiff))
this.assignObjectToOutput(root, blockKey, block)
}
}
}
function ConvertDMSToDD(degrees, minutes, seconds, direction) {
var dd = degrees + (minutes / 60) + (seconds / (60*60))
if (direction === 'S' || direction === 'W') dd *= -1
return dd
}
segmentParsers.set('tiff', TiffExif)
+328
View File
@@ -0,0 +1,328 @@
import {AppSegmentParserBase} from '../parser.mjs'
import {segmentParsers} from '../plugins.mjs'
import {undefinedIfEmpty} from '../util/helpers.mjs'
import {BufferView} from '../util/BufferView.mjs'
const XMP_CORE_HEADER = 'http://ns.adobe.com/'
const XMP_MAIN_HEADER = 'http://ns.adobe.com/xap/1.0/'
const XMP_EXTENDED_HEADER = 'http://ns.adobe.com/xmp/extension/'
// 2 bytes for markers + 2 bytes length
const TIFF_HEADER_LENGTH = 4
// Each XMP Extended segment starts with guid, length and offset (of its own, not just the one in TIFF header)
const XMP_EXTENDED_DATA_OFFSET = 79
export default class Xmp extends AppSegmentParserBase {
static type = 'xmp'
static multiSegment = true
static canHandle(chunk, offset) {
return chunk.getUint8(offset + 1) === 0xE1
&& chunk.getUint32(offset + 4) === 0x68747470 // 'http'
&& chunk.getString(offset + 4, XMP_CORE_HEADER.length) === XMP_CORE_HEADER
}
static headerLength(chunk, offset) {
let headerString = chunk.getString(offset + 4, XMP_EXTENDED_HEADER.length)
if (headerString === XMP_EXTENDED_HEADER)
return XMP_EXTENDED_DATA_OFFSET
else
return TIFF_HEADER_LENGTH + XMP_MAIN_HEADER.length + 1 // 1 for null termination between header and data
}
static findPosition(chunk, offset) {
let seg = super.findPosition(chunk, offset)
// first is the main XMP, then the extended starts counting from 0.
// We could determine that the XMP has extension if we looked for 'HasExtendedXMP'
// but we don't want to read the segment here just yet.
seg.multiSegment = seg.extended = seg.headerLength === XMP_EXTENDED_DATA_OFFSET
if (seg.multiSegment) {
seg.chunkCount = chunk.getUint8(offset + 72)
seg.chunkNumber = chunk.getUint8(offset + 76)
// first and second chunk both have 0 as the chunk number.
// the true first chunk (the one with <x:xmpme) has zeroes in the last two bytes of the chunk header.
if (chunk.getUint8(offset + 77) !== 0) seg.chunkNumber++
} else {
// The main XMP segment is not numbered and we can't determine if there's any XMP Extended chunks without
// parsing and looking for 'HasExtendedXMP'. We don't want to read in this simple due to 1) side effects
// and 2) chunked reader. For now we can only tell "there's a possibility of more chunks"
seg.chunkCount = Infinity
seg.chunkNumber = -1
}
return seg
}
static handleMultiSegments(allSegments) {
return allSegments.map(seg => seg.chunk.getString()).join('')
}
// WARNING: XMP as IFD0 tag in TIFF can be either Uint8Array or string.
// We need to be ready to accept any input data and turn it into string.
normalizeInput(input) {
return typeof input === 'string'
? input
: BufferView.from(input).getString()
}
// warning: The content may or may not be wrapped into <?xpacket.
// So far i've seen all of these:
// '<?xpacket><x:xmpmeta><rdf:RDF>'
// '<?xpacket><rdf:RDF>'
// '<x:xmpmeta><rdf:RDF>'
parse(xmpString = this.chunk) {
if (!this.localOptions.parse)
return xmpString
xmpString = idNestedTags(xmpString)
let tags = XmlTag.findAll(xmpString, 'rdf', 'Description')
if (tags.length === 0)
tags.push(new XmlTag('rdf', 'Description', undefined, xmpString))
let xmp = {}
let namespace
for (let tag of tags) {
for (let prop of tag.properties) {
namespace = getNamespace(prop.ns, xmp)
assignToObject(prop, namespace)
}
}
return pruneObject(xmp)
}
assignToOutput(root, xmp) {
if (!this.localOptions.parse) {
// xmp is not parsed, we include the string into output as is
root.xmp = xmp
} else {
// properties are grouped into separate namespace objects
// XMP TIFF namespace is merged into IFD0 block of TIFF segment
// XMP EXIF namespace is merged into EXIF block of TIFF segment
// All other namespaces are assigned
for (let [ns, nsObject] of Object.entries(xmp)) {
switch (ns) {
case 'tiff':
this.assignObjectToOutput(root, 'ifd0', nsObject)
break
case 'exif':
this.assignObjectToOutput(root, 'exif', nsObject)
break
case 'xmlns':
// XMLNS attributes aren't links but namespace identifiers in the URI form.
// TLDR: It's a useless bullshit. Don't need it. Get over it.
break
default:
this.assignObjectToOutput(root, ns, nsObject)
break
}
}
}
}
}
// removes undefined properties and empty objects
function pruneObject(object) {
let val
for (let key in object) {
val = object[key] = undefinedIfEmpty(object[key])
if (val === undefined)
delete object[key]
}
return undefinedIfEmpty(object)
}
segmentParsers.set('xmp', Xmp)
// ----- ATTRIBUTES -----
export class XmlAttr {
static findAll(string) {
// NOTE: regex has to be recreated each time because it's stateful due to use in exec()
let regex = /([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm
return matchAll(string, regex).map(XmlAttr.unpackMatch)
}
static unpackMatch(match) {
let ns = match[1]
let name = match[2]
let value = match[3].slice(1, -1)
value = normalizeValue(value)
return new XmlAttr(ns, name, value)
}
constructor(ns, name, value) {
this.ns = ns
this.name = name
this.value = value
}
serialize() {
return this.value
}
}
// ----- TAGS -----
const tagNamePartRegex = '[\\w\\d-]+'
const VALUE_PROP = 'value'
export class XmlTag {
static findAll(xmpString, ns, name) {
// NOTE: regex has to be recreated each time because it's stateful due to use in exec()
// handles both pair and self-closing tags.
if (ns !== undefined || name !== undefined) {
ns = ns || tagNamePartRegex
name = name || tagNamePartRegex
var regex = new RegExp(`<(${ns}):(${name})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`, 'gm')
} else {
var regex = /<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm
}
return matchAll(xmpString, regex).map(XmlTag.unpackMatch)
}
static unpackMatch(match) {
let ns = match[1]
let name = match[2]
let attrString = match[4]
let innerXml = match[8]
return new XmlTag(ns, name, attrString, innerXml)
}
constructor(ns, name, attrString, innerXml) {
this.ns = ns
this.name = name
this.attrString = attrString
this.innerXml = innerXml
this.attrs = XmlAttr.findAll(attrString)
this.children = XmlTag.findAll(innerXml)
this.value = this.children.length === 0 ? normalizeValue(innerXml) : undefined
this.properties = [...this.attrs, ...this.children]
}
get isPrimitive() {
return this.value !== undefined
&& this.attrs.length === 0
&& this.children.length === 0
}
get isListContainer() {
return this.children.length === 1
&& this.children[0].isList
}
get isList() {
let {ns, name} = this
return ns === 'rdf'
&& (name === 'Seq' || name === 'Bag' || name === 'Alt')
}
get isListItem() {
return this.ns === 'rdf' && this.name === 'li'
}
serialize() {
// invalid and undefined
if (this.properties.length === 0 && this.value === undefined)
return undefined
// primitive property
if (this.isPrimitive)
return this.value
// tag containing list tag <ns:tag><rdf:Seq>...</rdf:Seq></ns:tag>
if (this.isListContainer)
return this.children[0].serialize()
// list tag itself <rdf:Seq>...</rdf:Seq>
if (this.isList)
return unwrapArray(this.children.map(serialize))
// sometimes <rdf:li> may have a single object-tag child. We need that object returned.
if (this.isListItem && this.children.length === 1 && this.attrs.length === 0)
return this.children[0].serialize()
// process attributes and children tags into object
let output = {}
for (let prop of this.properties)
assignToObject(prop, output)
if (this.value !== undefined)
output[VALUE_PROP] = this.value
return undefinedIfEmpty(output)
}
}
// ----- UTILS -----
function assignToObject(prop, target) {
let serialized = prop.serialize()
if (serialized !== undefined)
target[prop.name] = serialized
}
var serialize = prop => prop.serialize()
var unwrapArray = array => array.length === 1 ? array[0] : array
var getNamespace = (ns, root) => root[ns] ? root[ns] : root[ns] = {}
function matchAll(string, regex) {
let matches = []
if (!string) return matches
let match
while ((match = regex.exec(string)) !== null)
matches.push(match)
return matches
}
export function normalizeValue(value) {
if (isUndefinable(value)) return undefined
let num = Number(value)
if (!Number.isNaN(num)) return num
let lowercase = value.toLowerCase()
if (lowercase === 'true') return true
if (lowercase === 'false') return false
return value.trim()
}
function isUndefinable(value) {
return value === null
|| value === undefined
|| value === 'null'
|| value === 'undefined'
|| value === ''
|| value.trim() === ''
}
const identifiableTags = [
// Basic lists and items
'rdf:li', 'rdf:Seq', 'rdf:Bag', 'rdf:Alt',
// This is special case when list items can immediately contain nested rdf:Description
// e.g. <rdf:Bag><rdf:li><rdf:Description mwg-rs:Name="additional data"><... actual inner tag ...></rdf:Description></rdf:li></rdf:Bag>
'rdf:Description'
]
const nestedLiRegex = new RegExp(`(<|\\/)(${identifiableTags.join('|')})`, 'g')
export function idNestedTags(xmpString) {
let stacks = {}
let counts = {}
for (let tag of identifiableTags) {
stacks[tag] = []
counts[tag] = 0
}
return xmpString.replace(nestedLiRegex, (match, prevChar, tag) => {
if (prevChar === '<') {
let id = ++counts[tag]
stacks[tag].push(id)
return `${match}#${id}`
} else {
let id = stacks[tag].pop()
return `${match}#${id}`
}
})
}
+56
View File
@@ -0,0 +1,56 @@
class Dictionary extends Map {
get tagKeys() {
if (!this.allKeys)
this.allKeys = Array.from(this.keys())
return this.allKeys
}
get tagValues() {
if (!this.allValues)
this.allValues = Array.from(this.values())
return this.allValues
}
}
export function createDictionary(group, key, entries) {
//let dict = new Dictionary(entries)
let dict = new Dictionary()
// ie doesnt support constructor initialization
for (let [key, val] of entries)
dict.set(key, val)
if (Array.isArray(key))
for (let k of key) group.set(k, dict)
else
group.set(key, dict)
return dict
}
export function extendDictionary(group, blockName, newTags) {
let map = group.get(blockName)
let entry
for (entry of newTags) map.set(entry[0], entry[1])
}
export const tagKeys = new Map
export const tagValues = new Map
export const tagRevivers = new Map
export const TAG_MAKERNOTE = 0x927C
export const TAG_USERCOMMENT = 0x9286
export const TAG_XMP = 0x02BC
export const TAG_IPTC = 0x83bb
export const TAG_PHOTOSHOP = 0x8649
export const TAG_ICC = 0x8773
export const TAG_IFD_EXIF = 0x8769
export const TAG_IFD_GPS = 0x8825
export const TAG_IFD_INTEROP = 0xA005
export const TAG_GPS_LATREF = 0x0001
export const TAG_GPS_LAT = 0x0002
export const TAG_GPS_LONREF = 0x0003
export const TAG_GPS_LON = 0x0004
export const TAG_ORIENTATION = 0x0112
+26
View File
@@ -0,0 +1,26 @@
import {BufferView} from './BufferView.mjs'
import {BigInt} from '../util/platform.mjs'
import {throwError} from '../util/helpers.mjs'
const FULL_20_BITS = 0b11111111111111111111
BufferView.prototype.getUint64 = function(offset) {
let part1 = this.getUint32(offset)
let part2 = this.getUint32(offset + 4)
if (part1 < FULL_20_BITS) {
// Warning: JS cannot handle 64-bit integers. The number will overflow and cause unexpected result
// if the number is larger than 53. We try to handle numbers up to 52 bits. 32+21 = 53 out of which
// one bit is needed for sign. Becase js only does 32 unsinged int (through bitwise operators).
return (part1 << 32) | part2
} else if (typeof BigInt !== undefined) {
// If the environment supports BigInt we'll try to use it. Though it may break user functionality
// (for example can't do mixed math with numbers & bigints)
console.warn(`Using BigInt because of type 64uint but JS can only handle 53b numbers.`)
return (BigInt(part1) << BigInt(32)) | BigInt(part2)
} else {
// The value (when both 32b parts combined) is larger than 53 bits so we can't just use Number type
// and this environment doesn't support BigInt... throw error.
throwError(`Trying to read 64b value but JS can only handle 53b numbers.`)
}
}
+173
View File
@@ -0,0 +1,173 @@
import {throwError} from './helpers.mjs'
import {hasBuffer} from '../util/platform.mjs'
const arrayToCharCode = arr => String.fromCharCode.apply(null, arr)
const utf8decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8') : undefined
export function uint8ArrayToUtf8String(uint8array) {
if (utf8decoder)
return utf8decoder.decode(uint8array)
else if (hasBuffer)
return Buffer.from(uint8array).toString('utf8')
else
return decodeURIComponent(escape(arrayToCharCode(uint8array)))
}
// NOTE: EXIF strings are ASCII encoded, but since ASCII is subset of UTF-8
// we can safely use it along with TextDecoder API.
export function toAsciiString(arg) {
if (typeof arg !== 'string')
return uint8ArrayToUtf8String(arg)
else
return arg
}
export class BufferView {
static from(arg, le) {
if (arg instanceof this && arg.le === le)
return arg
else
return new BufferView(arg, undefined, undefined, le)
}
constructor(arg, offset = 0, length, le) {
if (typeof le === 'boolean') this.le = le
if (Array.isArray(arg)) arg = new Uint8Array(arg)
if (arg === 0) {
this.byteOffset = 0
this.byteLength = 0
} else if (arg instanceof ArrayBuffer) {
if (length === undefined) length = arg.byteLength - offset
let dataView = new DataView(arg, offset, length)
this._swapDataView(dataView)
} else if (arg instanceof Uint8Array || arg instanceof DataView || arg instanceof BufferView) {
// Node.js Buffer is also instance of Uint8Array, but small ones are backed
// by single large ArrayBuffer pool, so we always need to check for arg.byteOffset.
if (length === undefined) length = arg.byteLength - offset
offset += arg.byteOffset
if (offset + length > arg.byteOffset + arg.byteLength)
throwError('Creating view outside of available memory in ArrayBuffer')
let dataView = new DataView(arg.buffer, offset, length)
this._swapDataView(dataView)
} else if (typeof arg === 'number') {
let dataView = new DataView(new ArrayBuffer(arg))
this._swapDataView(dataView)
} else {
throwError('Invalid input argument for BufferView: ' + arg)
}
}
_swapArrayBuffer(arrayBuffer) {
this._swapDataView(new DataView(arrayBuffer))
}
_swapBuffer(uint8) {
this._swapDataView(new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength))
}
_swapDataView(dataView) {
this.dataView = dataView
this.buffer = dataView.buffer
this.byteOffset = dataView.byteOffset
this.byteLength = dataView.byteLength
}
_lengthToEnd(offset) {
return this.byteLength - offset
}
set(arg, offset, Class = BufferView) {
if (arg instanceof DataView || arg instanceof BufferView)
arg = new Uint8Array(arg.buffer, arg.byteOffset, arg.byteLength)
else if (arg instanceof ArrayBuffer)
arg = new Uint8Array(arg)
if (!(arg instanceof Uint8Array))
throwError(`BufferView.set(): Invalid data argument.`)
let uintView = this.toUint8()
uintView.set(arg, offset)
return new Class(this, offset, arg.byteLength)
}
// Use this to get BufferView of specific subset of this BufferView.
subarray(offset, length) {
length = length || this._lengthToEnd(offset)
return new BufferView(this, offset, length)
}
// Use this for working with the same memory.
// Returns Uint8Array view over the same memory of ArrayBuffer as the internal DataView.
toUint8() {
return new Uint8Array(this.buffer, this.byteOffset, this.byteLength)
}
// Use this for reading data.
// Returns Uint8Array from given point in the chunk. Properly start at the begining of the chunk,
// regardles of where the chunk is in the ArrayBuffer.
getUint8Array(offset, length) {
return new Uint8Array(this.buffer, this.byteOffset + offset, length)
}
getString(offset = 0, length = this.byteLength) {
let arr = this.getUint8Array(offset, length)
return uint8ArrayToUtf8String(arr)
}
getLatin1String(offset = 0, length = this.byteLength) {
let arr = this.getUint8Array(offset, length)
return arrayToCharCode(arr)
}
// TODO: refactor
getUnicodeString(offset = 0, length = this.byteLength) {
// cannot use Uint16Array because it uses the other fucking endian order.
const chars = []
for (let i = 0; i < length && offset + i < this.byteLength; i += 2)
chars.push(this.getUint16(offset + i))
return arrayToCharCode(chars)
}
getInt8(offset) {return this.dataView.getInt8(offset)}
getUint8(offset) {return this.dataView.getUint8(offset)}
getInt16(offset, le = this.le) {return this.dataView.getInt16(offset, le)}
getInt32(offset, le = this.le) {return this.dataView.getInt32(offset, le)}
getUint16(offset, le = this.le) {return this.dataView.getUint16(offset, le)}
getUint32(offset, le = this.le) {return this.dataView.getUint32(offset, le)}
getFloat32(offset, le = this.le) {return this.dataView.getFloat32(offset, le)}
getFloat64(offset, le = this.le) {return this.dataView.getFloat64(offset, le)}
getFloat(offset, le = this.le) {return this.dataView.getFloat32(offset, le)}
getDouble(offset, le = this.le) {return this.dataView.getFloat64(offset, le)}
// todo: investiage - can this be removed?
getUintBytes(offset, bytes, le) {
switch (bytes) {
case 1: return this.getUint8(offset, le)
case 2: return this.getUint16(offset, le)
case 4: return this.getUint32(offset, le)
// Extension only required for parsing HEIC, implemented in separate file.
case 8: return this.getUint64 && this.getUint64(offset, le)
}
}
// todo: investiage - can this be removed?
getUint(offset, size, le) {
switch (size) {
case 8: return this.getUint8(offset, le)
case 16: return this.getUint16(offset, le)
case 32: return this.getUint32(offset, le)
// Extension only required for parsing HEIC, implemented in separate file.
case 64: return this.getUint64 && this.getUint64(offset, le)
}
}
toString(arg) {
return this.dataView.toString(arg, this.constructor.name)
}
// do not delete
ensureChunk() {}
}
+109
View File
@@ -0,0 +1,109 @@
import * as platform from './platform.mjs'
import {BufferView} from './BufferView.mjs'
//import {throwError} from './helpers.mjs'
import {Buffer} from './platform.mjs'
export class DynamicBufferView extends BufferView {
ranges = new Ranges
constructor(...args) {
super(...args)
if (this.byteLength !== 0)
this.ranges.add(0, this.byteLength)
}
_tryExtend(offset, length, abChunk) {
if (offset === 0 && this.byteLength === 0 && abChunk) {
// we can receive ArrayBuffer or Buffer
let dataView = new DataView(abChunk.buffer || abChunk, abChunk.byteOffset, abChunk.byteLength)
this._swapDataView(dataView)
} else {
let end = offset + length
if (end > this.byteLength) {
let {dataView} = this._extend(end)
this._swapDataView(dataView)
}
}
}
_extend(newLength) {
let uintView
if (platform.hasBuffer)
uintView = Buffer.allocUnsafe(newLength)
else
uintView = new Uint8Array(newLength)
let dataView = new DataView(uintView.buffer, uintView.byteOffset, uintView.byteLength)
uintView.set(new Uint8Array(this.buffer, this.byteOffset, this.byteLength), 0)
return {uintView, dataView}
}
subarray(offset, length, canExtend = false) {
length = length || this._lengthToEnd(offset)
if (canExtend) this._tryExtend(offset, length)
this.ranges.add(offset, length)
return super.subarray(offset, length)
}
// TODO: write tests for extending .set()
set(arg, offset, canExtend = false) {
if (canExtend) this._tryExtend(offset, arg.byteLength, arg)
let chunk = super.set(arg, offset)
this.ranges.add(offset, chunk.byteLength)
return chunk
}
async ensureChunk(offset, length) {
if (!this.chunked) return
if (this.ranges.available(offset, length)) return
await this.readChunk(offset, length)
}
// Returns bool indicating wheter buffer contains useful data (read from file) at given offset/length
// or if its so far only allocated & unitialized memory ready to be written into.
available(offset, length) {
return this.ranges.available(offset, length)
}
}
export class Ranges {
list = []
get length() {
return this.list.length
}
// TODO: add padding - because it's better to do just one disk read instead of two
// even though there are a few unused bytes between the two needed ranges
add(offset, length, padding = 0) {
let end = offset + length
let within = this.list.filter(range => isBetween(offset, range.offset, end) || isBetween(offset, range.end, end))
if (within.length > 0) {
offset = Math.min(offset, ...within.map(range => range.offset))
end = Math.max(end, ...within.map(range => range.end))
length = end - offset
let range = within.shift()
range.offset = offset
range.length = length
range.end = end
this.list = this.list.filter(range => !within.includes(range))
} else {
this.list.push({offset, length, end})
}
}
// Returns bool indicating wheter buffer contains useful data (read from file) at given offset/length
// or if its so far only allocated & unitialized memory ready to be written into.
available(offset, length) {
let end = offset + length
return this.list.some(range => range.offset <= offset && end <= range.end)
}
}
function isBetween(min, val, max) {
return min <= val && val <= max
}
+44
View File
@@ -0,0 +1,44 @@
const DEFAULT_SIZE = 16
// TODO: delete me before releasing.
// This is for debugging only
DataView.prototype.toString = function(size = DEFAULT_SIZE, name = this.constructor.name) {
if (typeof size !== 'number') size = DEFAULT_SIZE
size = Math.min(size, this.byteLength)
let values = (new Array(size))
.fill(0)
.map((val, i) => this.getUint8(i))
.map(val => val.toString(16).padStart(2, '0'))
.join(' ')
if (size < this.byteLength)
return `<${name} ${values} ... ${this.byteLength - size} more bytes>`
else
return `<${name} ${values}>`
}
ArrayBuffer.prototype.toString = function(arg) {
let view = new DataView(this)
return view.toString(arg, 'ArrayBuffer')
}
Uint8Array.prototype.toString = function(size = 10) {
if (typeof size !== 'number') size = DEFAULT_SIZE
size = Math.min(size, this.byteLength)
let values = (new Array(size))
.fill(0)
.map((val, i) => this[i])
.map(val => val.toString(16).padStart(2, '0'))
.join(' ')
return `<Uint8Array ${values}>`
}
Uint16Array.prototype.toString = function(size = 10) {
if (typeof size !== 'number') size = DEFAULT_SIZE
size = Math.min(size, this.byteLength)
let values = (new Array(size))
.fill(0)
.map((val, i) => this[i])
.map(val => val.toString(16).padStart(4, '0'))
.join(' ')
return `<Uint16Array ${values}>`
}
+54
View File
@@ -0,0 +1,54 @@
export const TIFF_LITTLE_ENDIAN = 0x4949
export const TIFF_BIG_ENDIAN = 0x4D4D
export const undefinedIfEmpty = object => isEmpty(object) ? undefined : object
const isDefined = val => val !== undefined
export function isEmpty(arg) {
if (arg === undefined) return true
if (arg instanceof Map)
return arg.size === 0
else
return Object.values(arg).filter(isDefined).length === 0
}
export function throwError(message) {
let err = new Error(message)
delete err.stack
throw err
}
export function removeNullTermination(string) {
while (string.endsWith('\0'))
string = string.slice(0, -1)
return string
}
// normalizes and sanitizes string for output. removes null termination. returns undefined if its empty.
export function normalizeString(string) {
// remove remaining spaces (need to be after null termination!)
string = removeNullTermination(string).trim()
return string === '' ? undefined : string
}
export function estimateTiffSize(options) {
let bytes = 0
if (options.ifd0.enabled) bytes += 1024
if (options.exif.enabled) bytes += 2048
if (options.makerNote) bytes += 2048
if (options.userComment) bytes += 1024
if (options.gps.enabled) bytes += 512
if (options.interop.enabled) bytes += 100
if (options.ifd1.enabled) bytes += 1024
return bytes + 2048 // issue-exif-js-124.tiff
}
export function estimateMetadataSize(options) {
let bytes = estimateTiffSize(options)
if (options.jfif.enabled) bytes += 50
if (options.xmp.enabled) bytes += 20000
if (options.iptc.enabled) bytes += 14000
if (options.icc.enabled) bytes += 6000
return bytes
}
+15
View File
@@ -0,0 +1,15 @@
import * as platform from './platform.mjs'
const pass = arg => arg
export default function(name, wrapper = pass) {
if (platform.node) {
try {
return typeof require === 'function'
? Promise.resolve(wrapper(require(name)))
: import(/* webpackIgnore: true */ name).then(wrapper)
} catch(err) {
console.warn(`Couldn't load ${name}`)
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import g from '../polyfill/global.mjs'
export const browser = typeof navigator !== 'undefined'
export const worker = browser && typeof HTMLImageElement === 'undefined'
export const node = !!(typeof global !== 'undefined' && typeof process !== 'undefined' && process.versions && process.versions.node)
// Needed for webpack. It otherwise packs 'buffer' npm module with the code
export const Buffer = g.Buffer
// Needed for ESLint. It doesn't yet support global BigInt.
export const BigInt = g.BigInt
export const hasBuffer = !!Buffer