polotno-node 2.6.7 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.html CHANGED
@@ -8,7 +8,7 @@
8
8
  }
9
9
  </style>
10
10
  <meta name="viewport" content="width=device-width, initial-scale=1" />
11
- <script type="module" crossorigin src="./assets/index-1a4d47fd.js"></script>
11
+ <script type="module" crossorigin src="./assets/index-13b6e0f3.js"></script>
12
12
  </head>
13
13
  <body>
14
14
  <div id="root"></div>
package/index.js CHANGED
@@ -49,13 +49,8 @@ const minimal_args = [
49
49
  '--use-mock-keychain',
50
50
  ];
51
51
 
52
- module.exports.createInstance = async ({
53
- key,
54
- url,
55
- useParallelPages,
56
- browserArgs = [],
57
- } = {}) => {
58
- const browser = await puppeteer.launch({
52
+ const createBrowser = async ({ browserArgs }) => {
53
+ return puppeteer.launch({
59
54
  args: [
60
55
  ...chrome.args,
61
56
  ...minimal_args,
@@ -75,9 +70,17 @@ module.exports.createInstance = async ({
75
70
  isMacOs || isWindows ? undefined : await chrome.executablePath(),
76
71
  ignoreHTTPSErrors: true,
77
72
  });
73
+ };
78
74
 
75
+ module.exports.createInstance = async ({
76
+ key,
77
+ url,
78
+ useParallelPages,
79
+ browserArgs = [],
80
+ browser,
81
+ } = {}) => {
79
82
  return await createInstance({
80
- browser,
83
+ browser: browser || (await createBrowser({ browserArgs })),
81
84
  key,
82
85
  url,
83
86
  useParallelPages,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polotno-node",
3
- "version": "2.6.7",
3
+ "version": "2.7.0",
4
4
  "description": "Polotno workflow from NodeJS",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -13,6 +13,7 @@
13
13
  "index.js",
14
14
  "instance.js",
15
15
  "video.js",
16
+ "video-parallel.js",
16
17
  "README.md"
17
18
  ],
18
19
  "browserslist": "> 0.5%, last 2 versions, not dead",
@@ -26,17 +27,17 @@
26
27
  "gifencoder": "^2.0.1",
27
28
  "pixelmatch": "^5.3.0",
28
29
  "pngjs": "^7.0.0",
29
- "polotno": "^2.0.2",
30
+ "polotno": "^2.0.5",
30
31
  "react": "^18.2.0",
31
32
  "react-dom": "^18.2.0",
32
- "vite": "^4.4.11"
33
+ "vite": "^4.5.0"
33
34
  },
34
35
  "author": "Anton Lavrenov",
35
36
  "license": "MIT",
36
37
  "dependencies": {
37
- "@sparticuz/chromium": "117.0.0",
38
- "puppeteer": "^21.3.8",
39
- "puppeteer-core": "^21.3.8"
38
+ "@sparticuz/chromium": "118.0.0",
39
+ "puppeteer": "^20.9.0",
40
+ "puppeteer-core": "^20.9.0"
40
41
  },
41
42
  "bugs": {
42
43
  "url": "https://github.com/polotno-project/polotno-node/issues"
@@ -0,0 +1,254 @@
1
+ const fs = require('fs');
2
+ const ffmpeg = require('fluent-ffmpeg');
3
+ const axios = require('axios');
4
+ const path = require('path');
5
+
6
+ const downloadVideo = async (url, destination) => {
7
+ const response = await axios({
8
+ method: 'GET',
9
+ url: url,
10
+ responseType: 'stream',
11
+ });
12
+
13
+ const writer = response.data.pipe(fs.createWriteStream(destination));
14
+
15
+ return new Promise((resolve, reject) => {
16
+ writer.on('finish', resolve);
17
+ writer.on('error', reject);
18
+ });
19
+ };
20
+
21
+ // 2. Convert it into webm format
22
+
23
+ const convertToWebM = (input, output) => {
24
+ console.log(input, output);
25
+ return new Promise((resolve, reject) => {
26
+ ffmpeg(input)
27
+ .outputOptions(['-c:v libvpx', '-crf 30', '-b:v 1000k'])
28
+ .output(output)
29
+ .on('start', () => {})
30
+ .on('end', () => {
31
+ resolve();
32
+ })
33
+ .on('error', (err) => {
34
+ console.log('Error occurred: ' + err.message);
35
+ reject(err);
36
+ })
37
+ .run();
38
+ });
39
+ };
40
+
41
+ // 3. Serialize file into dataurl string
42
+ const fileToDataUrl = (filename) => {
43
+ return new Promise((resolve, reject) => {
44
+ fs.readFile(filename, 'base64', (err, data) => {
45
+ if (err) reject(err);
46
+ resolve(`data:video/webm;base64,${data}`);
47
+ });
48
+ });
49
+ };
50
+
51
+ const videoToDataURL = async (url) => {
52
+ console.log('downloading', url);
53
+ const filename = Math.random().toString(36).substring(7);
54
+ const destination = path.join('./tmp', filename + '.mp4');
55
+ await downloadVideo(url, destination);
56
+ const webmFile = destination.replace('.mp4', '.webm');
57
+ console.log('converting to webm', url);
58
+ await convertToWebM(destination, webmFile);
59
+ const dataUrl = await fileToDataUrl(webmFile);
60
+ return dataUrl;
61
+ };
62
+
63
+ function printProgress(progress) {
64
+ process.stdout.clearLine(0);
65
+ process.stdout.cursorTo(0);
66
+ process.stdout.write('Rendering frame: ' + progress + '%');
67
+ }
68
+
69
+ module.exports.jsonToVideo = async function jsonToVideo(
70
+ createInstance,
71
+ json,
72
+ attrs
73
+ ) {
74
+ try {
75
+ fs.rmSync('./tmp', { recursive: true });
76
+ } catch (e) {}
77
+
78
+ fs.mkdirSync('./tmp', { recursive: true });
79
+
80
+ for (const page of json.pages) {
81
+ for (const el of page.children) {
82
+ if (el.type === 'video') {
83
+ el.src = await videoToDataURL(el.src);
84
+ }
85
+ }
86
+ }
87
+
88
+ const duration = json.pages.reduce((acc, page) => {
89
+ return acc + page.duration;
90
+ }, 0);
91
+ const parallel = attrs.parallel || 5;
92
+
93
+ const fps = attrs.fps || 15;
94
+ const timePerFrame = 1000 / fps;
95
+
96
+ // loop through the images and add each to the animation
97
+ const framesNumber = Math.floor((duration / 1000) * fps);
98
+ const frames = Array.from(Array(framesNumber).keys());
99
+
100
+ // split frames into parallel chunks
101
+ const chunkSize = Math.ceil(framesNumber / parallel);
102
+ const chunks = [];
103
+ for (let i = 0; i < framesNumber; i += chunkSize) {
104
+ chunks.push(frames.slice(i, i + chunkSize));
105
+ }
106
+
107
+ const pages = json.pages.map((p, index) => {
108
+ const previousPage = json.pages[index - 1];
109
+ const startTime = previousPage
110
+ ? previousPage.startTime + previousPage.duration
111
+ : 0;
112
+ return {
113
+ id: p.id,
114
+ startTime,
115
+ duration: p.duration,
116
+ };
117
+ });
118
+
119
+ let finishedFramesNumber = 0;
120
+
121
+ await Promise.all(
122
+ chunks.map(async (chunk, chunkIndex) => {
123
+ const instance = await createInstance();
124
+ const page = await instance.createPage();
125
+ await page.evaluate(async (json) => {
126
+ store.loadJSON(json);
127
+ }, json);
128
+
129
+ let lastPageIndex = -1;
130
+ for (const frameIndex of chunk) {
131
+ let currentTime = frameIndex * timePerFrame;
132
+ if (frameIndex === 0) {
133
+ // offset the very first frame to enable animation start
134
+ currentTime = 1;
135
+ }
136
+ if (frameIndex === framesNumber - 1) {
137
+ // offset the very last frame to enable animation end
138
+ currentTime = duration - 1;
139
+ }
140
+ const storePageIndex = pages.findIndex((p) => {
141
+ return (
142
+ currentTime >= p.startTime && currentTime < p.startTime + p.duration
143
+ );
144
+ });
145
+ if (storePageIndex !== lastPageIndex) {
146
+ await page.evaluate(async (currentTime) => {
147
+ store.setCurrentTime(currentTime);
148
+ await store.waitLoading();
149
+ if (window.config.unstable_setTextOverflow) {
150
+ window.config.unstable_setTextOverflow('resize');
151
+ } else {
152
+ // console.error(
153
+ // 'Can not set text overflow mode. Define window.config.unstable_setTextOverflow function'
154
+ // );
155
+ }
156
+ });
157
+ }
158
+ const dataURL = await page.evaluate(
159
+ async (json, attrs, currentTime) => {
160
+ store.setCurrentTime(currentTime);
161
+ const currentPage = store.pages.find((p) => {
162
+ return (
163
+ store.currentTime >= p.startTime &&
164
+ store.currentTime < p.startTime + p.duration
165
+ );
166
+ });
167
+ const url = await store.toDataURL({
168
+ pixelRatio: 0.5,
169
+ ...attrs,
170
+ pageId: currentPage?.id,
171
+ });
172
+ return url;
173
+ },
174
+ json,
175
+ attrs || {},
176
+ currentTime
177
+ );
178
+ fs.mkdirSync('./tmp', { recursive: true });
179
+ fs.writeFileSync(
180
+ `./tmp/${frameIndex}.png`,
181
+ dataURL.split(',')[1],
182
+ 'base64'
183
+ );
184
+ finishedFramesNumber += 1;
185
+ const progress = ((finishedFramesNumber / framesNumber) * 100).toFixed(
186
+ 1
187
+ );
188
+ printProgress(progress);
189
+ }
190
+ // TODO: why can't we just close the one created page?
191
+ // const browserPages = await instance.browser.pages();
192
+ // for (let i = 0; i < browserPages.length; i++) {
193
+ // await browserPages[i].close();
194
+ // }
195
+ await page.close();
196
+ if (!attrs.keepInstance) {
197
+ await instance.close();
198
+ }
199
+ })
200
+ );
201
+
202
+ // for (let i = 0; i < frames; i++) {
203
+ // let currentTime = i * timePerFrame;
204
+ // if (i === 0) {
205
+ // // offset the very first frame to enable animation start
206
+ // currentTime = 1;
207
+ // }
208
+ // if (i === frames - 1) {
209
+ // // offset the very last frame to enable animation end
210
+ // currentTime = duration - 1;
211
+ // }
212
+
213
+ // const dataURL = await page.evaluate(
214
+ // async (json, attrs, currentTime) => {
215
+ // store.setCurrentTime(currentTime);
216
+ // const currentPage = store.pages.find((p) => {
217
+ // return (
218
+ // store.currentTime >= p.startTime &&
219
+ // store.currentTime < p.startTime + p.duration
220
+ // );
221
+ // });
222
+ // const url = await store.toDataURL({
223
+ // pixelRatio: 0.5,
224
+ // ...attrs,
225
+ // pageId: currentPage?.id,
226
+ // });
227
+ // return url;
228
+ // },
229
+ // json,
230
+ // attrs || {},
231
+ // currentTime
232
+ // );
233
+ // const progress = ((i / (frames - 1)) * 100).toFixed(1);
234
+ // printProgress(progress);
235
+ // fs.mkdirSync('./tmp', { recursive: true });
236
+ // fs.writeFileSync(`./tmp/${i}.png`, dataURL.split(',')[1], 'base64');
237
+ // }
238
+
239
+ console.log('\nRendering video');
240
+
241
+ await new Promise((resolve, reject) => {
242
+ ffmpeg()
243
+ .input(`./tmp/%d.png`) // Make sure your images are named with numbers, e.g. 1.jpg, 2.jpg, etc.
244
+ .inputFPS(fps)
245
+ .videoCodec('libx264')
246
+ .outputOptions('-pix_fmt yuv420p')
247
+ .format('mp4')
248
+ .on('end', () => resolve())
249
+ .on('error', (err) => reject(err))
250
+ .save(attrs.out);
251
+ });
252
+
253
+ fs.rmSync('./tmp', { recursive: true });
254
+ };
package/video.js CHANGED
@@ -63,7 +63,7 @@ const videoToDataURL = async (url) => {
63
63
  function printProgress(progress) {
64
64
  process.stdout.clearLine(0);
65
65
  process.stdout.cursorTo(0);
66
- process.stdout.write(progress + '%');
66
+ process.stdout.write('Rendering frames: ' + progress + '%');
67
67
  }
68
68
 
69
69
  module.exports.jsonToVideo = async function jsonToGifFile(page, json, attrs) {
@@ -85,6 +85,13 @@ module.exports.jsonToVideo = async function jsonToGifFile(page, json, attrs) {
85
85
  async (json, attrs) => {
86
86
  store.loadJSON(json);
87
87
  await store.waitLoading();
88
+ // TODO: we need to active all pages first
89
+ // disable text fit, as it is already should be processed
90
+ if (window.config.unstable_setTextOverflow) {
91
+ window.config.unstable_setTextOverflow('resize');
92
+ } else {
93
+ console.error('Can not set text overflow mode');
94
+ }
88
95
  },
89
96
  json,
90
97
  attrs || {}
@@ -100,10 +107,19 @@ module.exports.jsonToVideo = async function jsonToGifFile(page, json, attrs) {
100
107
  // loop through the images and add each to the animation
101
108
  const frames = Math.floor((duration / 1000) * fps);
102
109
  for (let i = 0; i < frames; i++) {
103
- const currentTime = i * timePerFrame;
110
+ let currentTime = i * timePerFrame;
111
+ if (i === 0) {
112
+ // offset the very first frame to enable animation start
113
+ currentTime = 1;
114
+ }
115
+ if (i === frames - 1) {
116
+ // offset the very last frame to enable animation end
117
+ currentTime = duration - 1;
118
+ }
119
+
104
120
  const dataURL = await page.evaluate(
105
121
  async (json, attrs, currentTime) => {
106
- store.setCurrentTime(currentTime + 1);
122
+ store.setCurrentTime(currentTime);
107
123
  const currentPage = store.pages.find((p) => {
108
124
  return (
109
125
  store.currentTime >= p.startTime &&
@@ -121,12 +137,14 @@ module.exports.jsonToVideo = async function jsonToGifFile(page, json, attrs) {
121
137
  attrs || {},
122
138
  currentTime
123
139
  );
124
- const progress = ((i / frames) * 100).toFixed(1);
140
+ const progress = ((i / (frames - 1)) * 100).toFixed(1);
125
141
  printProgress(progress);
126
142
  fs.mkdirSync('./tmp', { recursive: true });
127
143
  fs.writeFileSync(`./tmp/${i}.png`, dataURL.split(',')[1], 'base64');
128
144
  }
129
145
 
146
+ console.log('\nRendering video');
147
+
130
148
  await new Promise((resolve, reject) => {
131
149
  ffmpeg()
132
150
  .input(`./tmp/%d.png`) // Make sure your images are named with numbers, e.g. 1.jpg, 2.jpg, etc.