UltraHDRLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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, onProgress, 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. );
  230. } catch ( error ) {
  231. if ( onError ) onError( error );
  232. console.error( error );
  233. }
  234. }, onProgress, onError );
  235. return texture;
  236. }
  237. _parseXMPMetadata( xmpDataString, xmpMetadata ) {
  238. const domParser = new DOMParser();
  239. const xmpXml = domParser.parseFromString(
  240. xmpDataString.substring(
  241. xmpDataString.indexOf( '<' ),
  242. xmpDataString.lastIndexOf( '>' ) + 1
  243. ),
  244. 'text/xml'
  245. );
  246. /* Determine if given XMP metadata is the primary GContainer descriptor or a gainmap descriptor */
  247. const [ hasHDRContainerDescriptor ] = xmpXml.getElementsByTagName(
  248. 'Container:Directory'
  249. );
  250. if ( hasHDRContainerDescriptor ) {
  251. /* There's not much useful information in the container descriptor besides memory-validation */
  252. } else {
  253. /* Gainmap descriptor - defaults from https://developer.android.com/media/platform/hdr-image-format#HDR_gain_map_metadata */
  254. const [ gainmapNode ] = xmpXml.getElementsByTagName( 'rdf:Description' );
  255. xmpMetadata.version = gainmapNode.getAttribute( 'hdrgm:Version' );
  256. xmpMetadata.baseRenditionIsHDR =
  257. gainmapNode.getAttribute( 'hdrgm:BaseRenditionIsHDR' ) === 'True';
  258. xmpMetadata.gainMapMin = parseFloat(
  259. gainmapNode.getAttribute( 'hdrgm:GainMapMin' ) || 0.0
  260. );
  261. xmpMetadata.gainMapMax = parseFloat(
  262. gainmapNode.getAttribute( 'hdrgm:GainMapMax' ) || 1.0
  263. );
  264. xmpMetadata.gamma = parseFloat(
  265. gainmapNode.getAttribute( 'hdrgm:Gamma' ) || 1.0
  266. );
  267. xmpMetadata.offsetSDR = parseFloat(
  268. gainmapNode.getAttribute( 'hdrgm:OffsetSDR' ) / ( 1 / 64 )
  269. );
  270. xmpMetadata.offsetHDR = parseFloat(
  271. gainmapNode.getAttribute( 'hdrgm:OffsetHDR' ) / ( 1 / 64 )
  272. );
  273. xmpMetadata.hdrCapacityMin = parseFloat(
  274. gainmapNode.getAttribute( 'hdrgm:HDRCapacityMin' ) || 0.0
  275. );
  276. xmpMetadata.hdrCapacityMax = parseFloat(
  277. gainmapNode.getAttribute( 'hdrgm:HDRCapacityMax' ) || 1.0
  278. );
  279. }
  280. }
  281. _srgbToLinear( value ) {
  282. if ( value / 255 < 0.04045 ) {
  283. return ( value / 255 ) * 0.0773993808;
  284. }
  285. if ( value < 1024 ) {
  286. return SRGB_TO_LINEAR[ ~ ~ value ];
  287. }
  288. return Math.pow( ( value / 255 ) * 0.9478672986 + 0.0521327014, 2.4 );
  289. }
  290. _applyGainmapToSDR(
  291. xmpMetadata,
  292. sdrBuffer,
  293. gainmapBuffer,
  294. onSuccess,
  295. onError
  296. ) {
  297. const getImageDataFromBuffer = ( buffer ) =>
  298. new Promise( ( resolve, reject ) => {
  299. const imageLoader = document.createElement( 'img' );
  300. imageLoader.onload = () => {
  301. const image = {
  302. width: imageLoader.naturalWidth,
  303. height: imageLoader.naturalHeight,
  304. source: imageLoader,
  305. };
  306. URL.revokeObjectURL( imageLoader.src );
  307. resolve( image );
  308. };
  309. imageLoader.onerror = () => {
  310. URL.revokeObjectURL( imageLoader.src );
  311. reject();
  312. };
  313. imageLoader.src = URL.createObjectURL(
  314. new Blob( [ buffer ], { type: 'image/jpeg' } )
  315. );
  316. } );
  317. Promise.all( [
  318. getImageDataFromBuffer( sdrBuffer ),
  319. getImageDataFromBuffer( gainmapBuffer ),
  320. ] )
  321. .then( ( [ sdrImage, gainmapImage ] ) => {
  322. const sdrImageAspect = sdrImage.width / sdrImage.height;
  323. const gainmapImageAspect = gainmapImage.width / gainmapImage.height;
  324. if ( sdrImageAspect !== gainmapImageAspect ) {
  325. onError(
  326. 'THREE.UltraHDRLoader Error: Aspect ratio mismatch between SDR and Gainmap images'
  327. );
  328. return;
  329. }
  330. const canvas = document.createElement( 'canvas' );
  331. const ctx = canvas.getContext( '2d', {
  332. willReadFrequently: true,
  333. colorSpace: 'srgb',
  334. } );
  335. canvas.width = sdrImage.width;
  336. canvas.height = sdrImage.height;
  337. /* Use out-of-the-box interpolation of Canvas API to scale gainmap to fit the SDR resolution */
  338. ctx.drawImage(
  339. gainmapImage.source,
  340. 0,
  341. 0,
  342. gainmapImage.width,
  343. gainmapImage.height,
  344. 0,
  345. 0,
  346. sdrImage.width,
  347. sdrImage.height
  348. );
  349. const gainmapImageData = ctx.getImageData(
  350. 0,
  351. 0,
  352. sdrImage.width,
  353. sdrImage.height,
  354. { colorSpace: 'srgb' }
  355. );
  356. ctx.drawImage( sdrImage.source, 0, 0 );
  357. const sdrImageData = ctx.getImageData(
  358. 0,
  359. 0,
  360. sdrImage.width,
  361. sdrImage.height,
  362. { colorSpace: 'srgb' }
  363. );
  364. /* HDR Recovery formula - https://developer.android.com/media/platform/hdr-image-format#use_the_gain_map_to_create_adapted_HDR_rendition */
  365. let hdrBuffer;
  366. if ( this.type === HalfFloatType ) {
  367. hdrBuffer = new Uint16Array( sdrImageData.data.length ).fill( 23544 );
  368. } else {
  369. hdrBuffer = new Float32Array( sdrImageData.data.length ).fill( 255 );
  370. }
  371. const maxDisplayBoost = Math.sqrt(
  372. Math.pow(
  373. /* 1.8 instead of 2 near-perfectly rectifies approximations introduced by precalculated SRGB_TO_LINEAR values */
  374. 1.8,
  375. xmpMetadata.hdrCapacityMax
  376. )
  377. );
  378. const unclampedWeightFactor =
  379. ( Math.log2( maxDisplayBoost ) - xmpMetadata.hdrCapacityMin ) /
  380. ( xmpMetadata.hdrCapacityMax - xmpMetadata.hdrCapacityMin );
  381. const weightFactor = Math.min(
  382. Math.max( unclampedWeightFactor, 0.0 ),
  383. 1.0
  384. );
  385. const useGammaOne = xmpMetadata.gamma === 1.0;
  386. for (
  387. let pixelIndex = 0;
  388. pixelIndex < sdrImageData.data.length;
  389. pixelIndex += 4
  390. ) {
  391. const x = ( pixelIndex / 4 ) % sdrImage.width;
  392. const y = Math.floor( pixelIndex / 4 / sdrImage.width );
  393. for ( let channelIndex = 0; channelIndex < 3; channelIndex ++ ) {
  394. const sdrValue = sdrImageData.data[ pixelIndex + channelIndex ];
  395. const gainmapIndex = ( y * sdrImage.width + x ) * 4 + channelIndex;
  396. const gainmapValue = gainmapImageData.data[ gainmapIndex ] / 255.0;
  397. /* Gamma is 1.0 by default */
  398. const logRecovery = useGammaOne
  399. ? gainmapValue
  400. : Math.pow( gainmapValue, 1.0 / xmpMetadata.gamma );
  401. const logBoost =
  402. xmpMetadata.gainMapMin * ( 1.0 - logRecovery ) +
  403. xmpMetadata.gainMapMax * logRecovery;
  404. const hdrValue =
  405. ( sdrValue + xmpMetadata.offsetSDR ) *
  406. ( logBoost * weightFactor === 0.0
  407. ? 1.0
  408. : Math.pow( 2, logBoost * weightFactor ) ) -
  409. xmpMetadata.offsetHDR;
  410. const linearHDRValue = Math.min(
  411. Math.max( this._srgbToLinear( hdrValue ), 0 ),
  412. 65504
  413. );
  414. hdrBuffer[ pixelIndex + channelIndex ] =
  415. this.type === HalfFloatType
  416. ? DataUtils.toHalfFloat( linearHDRValue )
  417. : linearHDRValue;
  418. }
  419. }
  420. onSuccess( hdrBuffer, sdrImage.width, sdrImage.height );
  421. } )
  422. .catch( () => {
  423. throw new Error(
  424. 'THREE.UltraHDRLoader Error: Could not parse UltraHDR images'
  425. );
  426. } );
  427. }
  428. }
  429. export { UltraHDRLoader };