generateImages_browserless.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. Render each OSMD sample, grab the generated images, and
  3. dump them into a local directory as PNG files.
  4. inspired by Vexflow's generate_png_images and vexflow-tests.js
  5. This can be used to generate PNGs from OSMD without a browser.
  6. It's also used with the visual regression test system in
  7. `tools/visual_regression.sh`.
  8. Note: this script needs to "fake" quite a few browser elements, like window, document, and a Canvas HTMLElement.
  9. For that it needs the canvas package installed.
  10. There are also some hacks needed to set the container size (offsetWidth) correctly.
  11. Otherwise you'd need to run a headless browser, which is way slower,
  12. see the semi-obsolete generateDiffImagesPuppeteerLocalhost.js
  13. */
  14. function sleep (ms) {
  15. return new Promise((resolve) => {
  16. setTimeout(resolve, ms)
  17. })
  18. }
  19. async function init () {
  20. console.log('[OSMD.generate] init')
  21. let [osmdBuildDir, sampleDir, imageDir, pageWidth, pageHeight, filterRegex, debugFlag, debugSleepTimeString] = process.argv.slice(2, 10)
  22. if (!osmdBuildDir || !sampleDir || !imageDir) {
  23. console.log('usage: ' +
  24. 'node test/Util/generateImages_browserless.js osmdBuildDir sampleDirectory imageDirectory [width|0] [height|0] [filterRegex|all|allSmall] [--debug] [debugSleepTime]')
  25. console.log(' (use "all" to skip filterRegex parameter. "allSmall" skips two huge OSMD samples that take forever to render)')
  26. console.log('example: node test/Util/generateImages_browserless.js ../../build ./test/data/ ./export 210 297 allSmall --debug 5000')
  27. console.log('Error: need osmdBuildDir, sampleDir and imageDir. Exiting.')
  28. process.exit(1)
  29. }
  30. const DEBUG = debugFlag === '--debug'
  31. // const debugSleepTime = Number.parseInt(process.env.GENERATE_DEBUG_SLEEP_TIME) || 0; // 5000 works for me [sschmidTU]
  32. if (DEBUG) {
  33. console.log(' (note that --debug slows down the script by about 0.3s per file, through logging)')
  34. const debugSleepTimeMs = Number.parseInt(debugSleepTimeString)
  35. if (debugSleepTimeMs > 0) {
  36. console.log('debug sleep time: ' + debugSleepTimeString)
  37. await sleep(Number.parseInt(debugSleepTimeMs))
  38. // [VSCode] apparently this is necessary for the debugger to attach itself in time before the program closes.
  39. // sometimes this is not enough, so you may have to try multiple times or increase the sleep timer. Unfortunately debugging nodejs isn't easy.
  40. }
  41. }
  42. debug('sampleDir: ' + sampleDir, DEBUG)
  43. debug('imageDir: ' + imageDir, DEBUG)
  44. let pageFormat = 'Endless'
  45. pageWidth = Number.parseInt(pageWidth)
  46. pageHeight = Number.parseInt(pageHeight)
  47. const endlessPage = !(pageHeight > 0 && pageWidth > 0)
  48. if (!endlessPage) {
  49. pageFormat = `${pageWidth}x${pageHeight}`
  50. }
  51. // ---- hacks to fake Browser elements OSMD and Vexflow need, like window, document, and a canvas HTMLElement ----
  52. const { JSDOM } = require('jsdom')
  53. const dom = new JSDOM('<!DOCTYPE html></html>')
  54. // eslint-disable-next-line no-global-assign
  55. window = dom.window
  56. // eslint-disable-next-line no-global-assign
  57. document = dom.window.document
  58. // eslint-disable-next-line no-global-assign
  59. global.window = dom.window
  60. // eslint-disable-next-line no-global-assign
  61. global.document = window.document
  62. global.HTMLElement = window.HTMLElement
  63. global.HTMLAnchorElement = window.HTMLAnchorElement
  64. global.XMLHttpRequest = window.XMLHttpRequest
  65. global.DOMParser = window.DOMParser
  66. global.Node = window.Node
  67. global.Canvas = window.Canvas
  68. // fix Blob not found (to support external modules like is-blob)
  69. global.Blob = require('cross-blob')
  70. const div = document.createElement('div')
  71. div.id = 'browserlessDiv'
  72. document.body.appendChild(div)
  73. // const canvas = document.createElement('canvas')
  74. // div.canvas = document.createElement('canvas')
  75. const zoom = 1.0
  76. // width of the div / PNG generated
  77. let width = pageWidth * zoom
  78. // TODO sometimes the width is way too small for the score, may need to adjust zoom.
  79. if (endlessPage) {
  80. width = 1440
  81. }
  82. let height = pageHeight
  83. if (endlessPage) {
  84. height = 32767
  85. }
  86. div.width = width
  87. div.height = height
  88. div.offsetWidth = width // doesn't work, offsetWidth is always 0 from this. see below
  89. div.clientWidth = width
  90. div.clientHeight = height
  91. div.scrollHeight = height
  92. div.scrollWidth = width
  93. div.setAttribute('width', width)
  94. div.setAttribute('height', height)
  95. div.setAttribute('offsetWidth', width)
  96. debug('div.offsetWidth: ' + div.offsetWidth, DEBUG)
  97. debug('div.height: ' + div.height, DEBUG)
  98. // hack: set offsetWidth reliably
  99. Object.defineProperties(window.HTMLElement.prototype, {
  100. offsetLeft: {
  101. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0 }
  102. },
  103. offsetTop: {
  104. get: function () { return parseFloat(window.getComputedStyle(this).marginTop) || 0 }
  105. },
  106. offsetHeight: {
  107. get: function () { return height }
  108. },
  109. offsetWidth: {
  110. get: function () { return width }
  111. }
  112. })
  113. debug('div.offsetWidth: ' + div.offsetWidth, DEBUG)
  114. debug('div.height: ' + div.height, DEBUG)
  115. if (!DEBUG) {
  116. // deactivate console logs (mostly)
  117. console.log = (msg) => {}
  118. }
  119. // ---- end browser hacks (hopefully) ----
  120. const OSMD = require(`${osmdBuildDir}/opensheetmusicdisplay.min.js`)
  121. const fs = require('fs')
  122. // Create the image directory if it doesn't exist.
  123. fs.mkdirSync(imageDir, { recursive: true })
  124. const sampleDirFilenames = fs.readdirSync(sampleDir)
  125. let samplesToProcess = [] // samples we want to process/generate pngs of, excluding the filtered out files/filenames
  126. for (const sampleFilename of sampleDirFilenames) {
  127. if (filterRegex === 'allSmall') {
  128. if (sampleFilename.match('^(Actor)|(Gounod)')) { // TODO maybe filter by file size instead
  129. debug('filtering big file: ' + sampleFilename, DEBUG)
  130. continue
  131. }
  132. }
  133. // eslint-disable-next-line no-useless-escape
  134. if (sampleFilename.match('^.*(\.xml)|(\.musicxml)|(\.mxl)$')) {
  135. // console.log('found musicxml/mxl: ' + sampleFilename)
  136. samplesToProcess.push(sampleFilename)
  137. } else {
  138. debug('discarded file/directory: ' + sampleFilename, DEBUG)
  139. }
  140. }
  141. // filter samples to process by regex if given
  142. if (filterRegex && filterRegex !== '' && filterRegex !== 'all' && filterRegex !== 'allSmall') {
  143. debug('filtering samples for regex: ' + filterRegex, DEBUG)
  144. samplesToProcess = samplesToProcess.filter((filename) => filename.match(filterRegex))
  145. debug(`found ${samplesToProcess.length} matches: `, DEBUG)
  146. for (let i = 0; i < samplesToProcess.length; i++) {
  147. debug(samplesToProcess[i], DEBUG)
  148. }
  149. }
  150. const osmdInstance = new OSMD.OpenSheetMusicDisplay(div, {
  151. autoResize: false,
  152. backend: 'canvas',
  153. pageBackgroundColor: '#FFFFFF',
  154. pageFormat: pageFormat
  155. // defaultFontFamily: 'Arial',
  156. // drawTitle: false
  157. })
  158. // for more options check OSMDOptions.ts
  159. // you can set finer-grained rendering/engraving settings in EngravingRules:
  160. osmdInstance.EngravingRules.TitleTopDistance = 5.0 // 9.0 is default
  161. osmdInstance.EngravingRules.PageTopMargin = 5.0 // 5 is default
  162. osmdInstance.EngravingRules.PageBottomMargin = 5.0 // 5 is default. <5 can cut off scores that extend in the last staffline
  163. // note that for now the png and canvas will still have the height given in the script argument,
  164. // so even with a margin of 0 the image will be filled to the full height.
  165. osmdInstance.EngravingRules.PageLeftMargin = 5.0 // 5 is default
  166. osmdInstance.EngravingRules.PageRightMargin = 5.0 // 5 is default
  167. // osmdInstance.EngravingRules.MetronomeMarkXShift = -8; // -6 is default
  168. // osmdInstance.EngravingRules.DistanceBetweenVerticalSystemLines = 0.15; // 0.35 is default
  169. // for more options check EngravingRules.ts (though not all of these are meant and fully supported to be changed at will)
  170. // await sleep(5000)
  171. if (DEBUG) {
  172. osmdInstance.setLogLevel('debug')
  173. // console.log(`osmd PageFormat: ${osmdInstance.EngravingRules.PageFormat.width}x${osmdInstance.EngravingRules.PageFormat.height}`)
  174. console.log(`osmd PageFormat idString: ${osmdInstance.EngravingRules.PageFormat.idString}`)
  175. console.log('PageHeight: ' + osmdInstance.EngravingRules.PageHeight)
  176. } else {
  177. osmdInstance.setLogLevel('info') // doesn't seem to work, log.debug still logs
  178. }
  179. debug('generateImages', DEBUG)
  180. for (let i = 0; i < samplesToProcess.length; i++) {
  181. var sampleFilename = samplesToProcess[i]
  182. debug('sampleFilename: ' + sampleFilename, DEBUG)
  183. let loadParameter = fs.readFileSync(sampleDir + '/' + sampleFilename)
  184. if (sampleFilename.endsWith('.mxl')) {
  185. loadParameter = await OSMD.MXLHelper.MXLtoXMLstring(loadParameter)
  186. } else {
  187. loadParameter = loadParameter.toString()
  188. }
  189. // console.log('loadParameter: ' + loadParameter)
  190. // console.log('typeof loadParameter: ' + typeof loadParameter)
  191. await osmdInstance.load(loadParameter).then(function () {
  192. debug('xml loaded', DEBUG)
  193. try {
  194. osmdInstance.render()
  195. } catch (ex) {
  196. console.log('renderError: ' + ex)
  197. }
  198. debug('rendered', DEBUG)
  199. const dataUrls = []
  200. let canvasImage
  201. for (let pageNumber = 1; pageNumber < 999; pageNumber++) {
  202. canvasImage = document.getElementById('osmdCanvasVexFlowBackendCanvas' + pageNumber)
  203. if (!canvasImage) {
  204. break
  205. }
  206. if (!canvasImage.toDataURL) {
  207. console.log(`error: could not get canvas image for page ${pageNumber} for file: ${sampleFilename}`)
  208. break
  209. }
  210. dataUrls.push(canvasImage.toDataURL())
  211. }
  212. for (let urlIndex = 0; urlIndex < dataUrls.length; urlIndex++) {
  213. const pageNumberingString = `_${urlIndex + 1}`
  214. // pageNumberingString = dataUrls.length > 0 ? pageNumberingString : '' // don't put '_1' at the end if only one page. though that may cause more work
  215. var pageFilename = `${imageDir}/${sampleFilename}${pageNumberingString}.png`
  216. const dataUrl = dataUrls[urlIndex]
  217. if (!dataUrl || !dataUrl.split) {
  218. console.log(`error: could not get dataUrl (imageData) for page ${urlIndex + 1} of sample: ${sampleFilename}`)
  219. continue
  220. }
  221. const imageData = dataUrl.split(';base64,').pop()
  222. const imageBuffer = Buffer.from(imageData, 'base64')
  223. debug('got image data, saving to: ' + pageFilename, DEBUG)
  224. fs.writeFileSync(pageFilename, imageBuffer, { encoding: 'base64' })
  225. }
  226. }) // end render then
  227. // },
  228. // function (e) {
  229. // console.log('error while rendering: ' + e)
  230. // }) // end load then
  231. // }) // end read file
  232. }
  233. console.log('[OSMD.generate_browserless] exit')
  234. }
  235. function debug (msg, debugEnabled) {
  236. if (debugEnabled) {
  237. console.log(msg)
  238. }
  239. }
  240. init()