generateImages_browserless.js 13 KB

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