UltraHDRLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import {
  2. ClampToEdgeWrapping,
  3. DataTexture,
  4. DataUtils,
  5. FileLoader,
  6. HalfFloatType,
  7. LinearFilter,
  8. LinearMipMapLinearFilter,
  9. LinearSRGBColorSpace,
  10. Loader,
  11. RGBAFormat,
  12. UVMapping,
  13. } from 'three';
  14. // UltraHDR Image Format - https://developer.android.com/media/platform/hdr-image-format
  15. // HDR/EXR to UltraHDR Converter - https://gainmap-creator.monogrid.com/
  16. /**
  17. *
  18. * Short format brief:
  19. *
  20. * [JPEG headers]
  21. * [XMP metadata describing the MPF container and *both* SDR and gainmap images]
  22. * [Optional metadata] [EXIF] [ICC Profile]
  23. * [SDR image]
  24. * [XMP metadata describing only the gainmap image]
  25. * [Gainmap image]
  26. *
  27. * Each section is separated by a 0xFFXX byte followed by a descriptor byte (0xFFE0, 0xFFE1, 0xFFE2.)
  28. * Binary image storages are prefixed with a unique 0xFFD8 16-bit descriptor.
  29. */
  30. /**
  31. * Current feature set:
  32. * - JPEG headers (required)
  33. * - XMP metadata (required)
  34. * - XMP validation (not implemented)
  35. * - EXIF profile (not implemented)
  36. * - ICC profile (not implemented)
  37. * - Binary storage for SDR & HDR images (required)
  38. * - Gainmap metadata (required)
  39. * - Non-JPEG image formats (not implemented)
  40. * - Primary image as an HDR image (not implemented)
  41. */
  42. /* Calculating this SRGB powers is extremely slow for 4K images and can be sufficiently precalculated for a 3-4x speed boost */
  43. const SRGB_TO_LINEAR = Array( 1024 )
  44. .fill( 0 )
  45. .map( ( _, value ) =>
  46. Math.pow( ( value / 255 ) * 0.9478672986 + 0.0521327014, 2.4 )
  47. );
  48. class UltraHDRLoader extends Loader {
  49. constructor( manager ) {
  50. super( manager );
  51. this.type = HalfFloatType;
  52. }
  53. setDataType( value ) {
  54. this.type = value;
  55. return this;
  56. }
  57. parse( buffer, onLoad ) {
  58. const xmpMetadata = {
  59. version: null,
  60. baseRenditionIsHDR: null,
  61. gainMapMin: null,
  62. gainMapMax: null,
  63. gamma: null,
  64. offsetSDR: null,
  65. offsetHDR: null,
  66. hdrCapacityMin: null,
  67. hdrCapacityMax: null,
  68. };
  69. const textDecoder = new TextDecoder();
  70. const data = new DataView( buffer );
  71. let byteOffset = 0;
  72. const sections = [];
  73. while ( byteOffset < data.byteLength ) {
  74. const byte = data.getUint8( byteOffset );
  75. if ( byte === 0xff ) {
  76. const leadingByte = data.getUint8( byteOffset + 1 );
  77. if (
  78. [
  79. /* Valid section headers */
  80. 0xd8, // SOI
  81. 0xe0, // APP0
  82. 0xe1, // APP1
  83. 0xe2, // APP2
  84. ].includes( leadingByte )
  85. ) {
  86. sections.push( {
  87. sectionType: leadingByte,
  88. section: [ byte, leadingByte ],
  89. sectionOffset: byteOffset + 2,
  90. } );
  91. byteOffset += 2;
  92. } else {
  93. sections[ sections.length - 1 ].section.push( byte, leadingByte );
  94. byteOffset += 2;
  95. }
  96. } else {
  97. sections[ sections.length - 1 ].section.push( byte );
  98. byteOffset ++;
  99. }
  100. }
  101. let primaryImage, gainmapImage;
  102. for ( let i = 0; i < sections.length; i ++ ) {
  103. const { sectionType, section, sectionOffset } = sections[ i ];
  104. if ( sectionType === 0xe0 ) {
  105. /* JPEG Header - no useful information */
  106. } else if ( sectionType === 0xe1 ) {
  107. /* XMP Metadata */
  108. this._parseXMPMetadata(
  109. textDecoder.decode( new Uint8Array( section ) ),
  110. xmpMetadata
  111. );
  112. } else if ( sectionType === 0xe2 ) {
  113. /* Data Sections - MPF / EXIF / ICC Profile */
  114. const sectionData = new DataView(
  115. new Uint8Array( section.slice( 2 ) ).buffer
  116. );
  117. const sectionHeader = sectionData.getUint32( 2, false );
  118. if ( sectionHeader === 0x4d504600 ) {
  119. /* MPF Section */
  120. /* Section contains a list of static bytes and ends with offsets indicating location of SDR and gainmap images */
  121. /* First bytes after header indicate little / big endian ordering (0x49492A00 - LE / 0x4D4D002A - BE) */
  122. /*
  123. ... 60 bytes indicating tags, versions, etc. ...
  124. bytes | bits | description
  125. 4 32 primary image size
  126. 4 32 primary image offset
  127. 2 16 0x0000
  128. 2 16 0x0000
  129. 4 32 0x00000000
  130. 4 32 gainmap image size
  131. 4 32 gainmap image offset
  132. 2 16 0x0000
  133. 2 16 0x0000
  134. */
  135. const mpfLittleEndian = sectionData.getUint32( 6 ) === 0x49492a00;
  136. const mpfBytesOffset = 60;
  137. /* SDR size includes the metadata length, SDR offset is always 0 */
  138. const primaryImageSize = sectionData.getUint32(
  139. mpfBytesOffset,
  140. mpfLittleEndian
  141. );
  142. const primaryImageOffset = sectionData.getUint32(
  143. mpfBytesOffset + 4,
  144. mpfLittleEndian
  145. );
  146. /* Gainmap size is an absolute value starting from its offset, gainmap offset needs 6 bytes padding to take into account 0x00 bytes at the end of XMP */
  147. const gainmapImageSize = sectionData.getUint32(
  148. mpfBytesOffset + 16,
  149. mpfLittleEndian
  150. );
  151. const gainmapImageOffset =
  152. sectionData.getUint32( mpfBytesOffset + 20, mpfLittleEndian ) +
  153. sectionOffset +
  154. 6;
  155. primaryImage = new Uint8Array(
  156. data.buffer,
  157. primaryImageOffset,
  158. primaryImageSize
  159. );
  160. gainmapImage = new Uint8Array(
  161. data.buffer,
  162. gainmapImageOffset,
  163. gainmapImageSize
  164. );
  165. }
  166. }
  167. }
  168. /* Minimal sufficient validation - https://developer.android.com/media/platform/hdr-image-format#signal_of_the_format */
  169. if ( ! xmpMetadata.version ) {
  170. throw new Error( 'THREE.UltraHDRLoader: Not a valid UltraHDR image' );
  171. }
  172. if ( primaryImage && gainmapImage ) {
  173. this._applyGainmapToSDR(
  174. xmpMetadata,
  175. primaryImage,
  176. gainmapImage,
  177. ( hdrBuffer, width, height ) => {
  178. onLoad( {
  179. width,
  180. height,
  181. data: hdrBuffer,
  182. format: RGBAFormat,
  183. type: this.type,
  184. } );
  185. },
  186. ( error ) => {
  187. throw new Error( error );
  188. }
  189. );
  190. } else {
  191. throw new Error( 'THREE.UltraHDRLoader: Could not parse UltraHDR images' );
  192. }
  193. }
  194. load( url, onLoad, onError ) {
  195. const texture = new DataTexture(
  196. this.type === HalfFloatType ? new Uint16Array() : new Float32Array(),
  197. 0,
  198. 0,
  199. RGBAFormat,
  200. this.type,
  201. UVMapping,
  202. ClampToEdgeWrapping,
  203. ClampToEdgeWrapping,
  204. LinearFilter,
  205. LinearMipMapLinearFilter,
  206. 1,
  207. LinearSRGBColorSpace
  208. );
  209. texture.generateMipmaps = true;
  210. texture.flipY = true;
  211. const loader = new FileLoader( this.manager );
  212. loader.setResponseType( 'arraybuffer' );
  213. loader.setRequestHeader( this.requestHeader );
  214. loader.setPath( this.path );
  215. loader.setWithCredentials( this.withCredentials );
  216. loader.load( url, ( buffer ) => {
  217. try {
  218. this.parse(
  219. buffer,
  220. ( texData ) => {
  221. texture.image = {
  222. data: texData.data,
  223. width: texData.width,
  224. height: texData.height,
  225. };
  226. texture.needsUpdate = true;
  227. if ( onLoad ) onLoad( texture, texData );
  228. },
  229. onError
  230. );
  231. } catch ( error ) {
  232. if ( onError ) onError( error );
  233. console.error( error );
  234. }
  235. } );
  236. return texture;
  237. }
  238. _parseXMPMetadata( xmpDataString, xmpMetadata ) {
  239. const domParser = new DOMParser();
  240. const xmpXml = domParser.parseFromString(
  241. xmpDataString.substring(
  242. xmpDataString.indexOf( '<' ),
  243. xmpDataString.lastIndexOf( '>' ) + 1
  244. ),
  245. 'text/xml'
  246. );
  247. /* Determine if given XMP metadata is the primary GContainer descriptor or a gainmap descriptor */
  248. const [ hasHDRContainerDescriptor ] = xmpXml.getElementsByTagName(
  249. 'Container:Directory'
  250. );
  251. if ( hasHDRContainerDescriptor ) {
  252. /* There's not much useful information in the container descriptor besides memory-validation */
  253. } else {
  254. /* Gainmap descriptor - defaults from https://developer.android.com/media/platform/hdr-image-format#HDR_gain_map_metadata */
  255. const [ gainmapNode ] = xmpXml.getElementsByTagName( 'rdf:Description' );
  256. xmpMetadata.version = gainmapNode.getAttribute( 'hdrgm:Version' );
  257. xmpMetadata.baseRenditionIsHDR =
  258. gainmapNode.getAttribute( 'hdrgm:BaseRenditionIsHDR' ) === 'True';
  259. xmpMetadata.gainMapMin = parseFloat(
  260. gainmapNode.getAttribute( 'hdrgm:GainMapMin' ) || 0.0
  261. );
  262. xmpMetadata.gainMapMax = parseFloat(
  263. gainmapNode.getAttribute( 'hdrgm:GainMapMax' ) || 1.0
  264. );
  265. xmpMetadata.gamma = parseFloat(
  266. gainmapNode.getAttribute( 'hdrgm:Gamma' ) || 1.0
  267. );
  268. xmpMetadata.offsetSDR = parseFloat(
  269. gainmapNode.getAttribute( 'hdrgm:OffsetSDR' ) / ( 1 / 64 )
  270. );
  271. xmpMetadata.offsetHDR = parseFloat(
  272. gainmapNode.getAttribute( 'hdrgm:OffsetHDR' ) / ( 1 / 64 )
  273. );
  274. xmpMetadata.hdrCapacityMin = parseFloat(
  275. gainmapNode.getAttribute( 'hdrgm:HDRCapacityMin' ) || 0.0
  276. );
  277. xmpMetadata.hdrCapacityMax = parseFloat(
  278. gainmapNode.getAttribute( 'hdrgm:HDRCapacityMax' ) || 1.0
  279. );
  280. }
  281. }
  282. _srgbToLinear( value ) {
  283. if ( value / 255 < 0.04045 ) {
  284. return ( value / 255 ) * 0.0773993808;
  285. }
  286. if ( value < 1024 ) {
  287. return SRGB_TO_LINEAR[ ~ ~ value ];
  288. }
  289. return Math.pow( ( value / 255 ) * 0.9478672986 + 0.0521327014, 2.4 );
  290. }
  291. _applyGainmapToSDR(
  292. xmpMetadata,
  293. sdrBuffer,
  294. gainmapBuffer,
  295. onSuccess,
  296. onError
  297. ) {
  298. const getImageDataFromBuffer = ( buffer ) =>
  299. new Promise( ( resolve, reject ) => {
  300. const imageLoader = document.createElement( 'img' );
  301. imageLoader.onload = () => {
  302. const image = {
  303. width: imageLoader.naturalWidth,
  304. height: imageLoader.naturalHeight,
  305. source: imageLoader,
  306. };
  307. URL.revokeObjectURL( imageLoader.src );
  308. resolve( image );
  309. };
  310. imageLoader.onerror = () => {
  311. URL.revokeObjectURL( imageLoader.src );
  312. reject();
  313. };
  314. imageLoader.src = URL.createObjectURL(
  315. new Blob( [ buffer ], { type: 'image/jpeg' } )
  316. );
  317. } );
  318. Promise.all( [
  319. getImageDataFromBuffer( sdrBuffer ),
  320. getImageDataFromBuffer( gainmapBuffer ),
  321. ] )
  322. .then( ( [ sdrImage, gainmapImage ] ) => {
  323. const sdrImageAspect = sdrImage.width / sdrImage.height;
  324. const gainmapImageAspect = gainmapImage.width / gainmapImage.height;
  325. if ( sdrImageAspect !== gainmapImageAspect ) {
  326. onError(
  327. 'THREE.UltraHDRLoader Error: Aspect ratio mismatch between SDR and Gainmap images'
  328. );
  329. return;
  330. }
  331. const canvas = document.createElement( 'canvas' );
  332. const ctx = canvas.getContext( '2d', {
  333. willReadFrequently: true,
  334. colorSpace: 'srgb',
  335. } );
  336. canvas.width = sdrImage.width;
  337. canvas.height = sdrImage.height;
  338. /* Use out-of-the-box interpolation of Canvas API to scale gainmap to fit the SDR resolution */
  339. ctx.drawImage(
  340. gainmapImage.source,
  341. 0,
  342. 0,
  343. gainmapImage.width,
  344. gainmapImage.height,
  345. 0,
  346. 0,
  347. sdrImage.width,
  348. sdrImage.height
  349. );
  350. const gainmapImageData = ctx.getImageData(
  351. 0,
  352. 0,
  353. sdrImage.width,
  354. sdrImage.height,
  355. { colorSpace: 'srgb' }
  356. );
  357. ctx.drawImage( sdrImage.source, 0, 0 );
  358. const sdrImageData = ctx.getImageData(
  359. 0,
  360. 0,
  361. sdrImage.width,
  362. sdrImage.height,
  363. { colorSpace: 'srgb' }
  364. );
  365. /* HDR Recovery formula - https://developer.android.com/media/platform/hdr-image-format#use_the_gain_map_to_create_adapted_HDR_rendition */
  366. let hdrBuffer;
  367. if ( this.type === HalfFloatType ) {
  368. hdrBuffer = new Uint16Array( sdrImageData.data.length ).fill( 23544 );
  369. } else {
  370. hdrBuffer = new Float32Array( sdrImageData.data.length ).fill( 255 );
  371. }
  372. const maxDisplayBoost = Math.sqrt(
  373. Math.pow(
  374. /* 1.8 instead of 2 near-perfectly rectifies approximations introduced by precalculated SRGB_TO_LINEAR values */
  375. 1.8,
  376. xmpMetadata.hdrCapacityMax
  377. )
  378. );
  379. const unclampedWeightFactor =
  380. ( Math.log2( maxDisplayBoost ) - xmpMetadata.hdrCapacityMin ) /
  381. ( xmpMetadata.hdrCapacityMax - xmpMetadata.hdrCapacityMin );
  382. const weightFactor = Math.min(
  383. Math.max( unclampedWeightFactor, 0.0 ),
  384. 1.0
  385. );
  386. const useGammaOne = xmpMetadata.gamma === 1.0;
  387. for (
  388. let pixelIndex = 0;
  389. pixelIndex < sdrImageData.data.length;
  390. pixelIndex += 4
  391. ) {
  392. const x = ( pixelIndex / 4 ) % sdrImage.width;
  393. const y = Math.floor( pixelIndex / 4 / sdrImage.width );
  394. for ( let channelIndex = 0; channelIndex < 3; channelIndex ++ ) {
  395. const sdrValue = sdrImageData.data[ pixelIndex + channelIndex ];
  396. const gainmapIndex = ( y * sdrImage.width + x ) * 4 + channelIndex;
  397. const gainmapValue = gainmapImageData.data[ gainmapIndex ] / 255.0;
  398. /* Gamma is 1.0 by default */
  399. const logRecovery = useGammaOne
  400. ? gainmapValue
  401. : Math.pow( gainmapValue, 1.0 / xmpMetadata.gamma );
  402. const logBoost =
  403. xmpMetadata.gainMapMin * ( 1.0 - logRecovery ) +
  404. xmpMetadata.gainMapMax * logRecovery;
  405. const hdrValue =
  406. ( sdrValue + xmpMetadata.offsetSDR ) *
  407. ( logBoost * weightFactor === 0.0
  408. ? 1.0
  409. : Math.pow( 2, logBoost * weightFactor ) ) -
  410. xmpMetadata.offsetHDR;
  411. const linearHDRValue = Math.min(
  412. Math.max( this._srgbToLinear( hdrValue ), 0 ),
  413. 65504
  414. );
  415. hdrBuffer[ pixelIndex + channelIndex ] =
  416. this.type === HalfFloatType
  417. ? DataUtils.toHalfFloat( linearHDRValue )
  418. : linearHDRValue;
  419. }
  420. }
  421. onSuccess( hdrBuffer, sdrImage.width, sdrImage.height );
  422. } )
  423. .catch( () => {
  424. throw new Error(
  425. 'THREE.UltraHDRLoader Error: Could not parse UltraHDR images'
  426. );
  427. } );
  428. }
  429. }
  430. export { UltraHDRLoader };