generateImages_browserless.js 15 KB

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