generateImages_browserless.js 19 KB

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