generateImages_browserless.js 17 KB

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