generateImages_browserless.js 16 KB

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