-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautorender.js
278 lines (218 loc) · 9.52 KB
/
autorender.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/**
* Programmatic AutoRender Node.js module.
*/
const nexrender = require('@nexrender/core');
const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const ejs = require('ejs');
const { copyFileAndReturnFileURI } = require('./modules/resolveData');
const {
createCopyAction,
createEncodeAction
} = require('./nexrender_templates/render_modules/actions');
const winston = require('winston');
require('dotenv').config({path: path.resolve(__dirname, './private/opts.env')});
// Create the logger which will be used to output logs to the STDOUT stream
// as well as a logfile.
const logger = winston.createLogger({
level: 'info',
format: winston.format.simple(),
transports: [
new winston.transports.File({ filename: 'autorender.log' }),
new winston.transports.Console(),
]
});
const _PLATFORM = determinePlatform();
const DEFAULT_AE_TEMPLATE_PATH = `./assets/STM_TEMPLATE_AUTORENDER_BUNDLED/`;
const DEFAULT_AE_AUTORENDER_SCRIPT_PATH = './scripts/stm_autorender_trapcode_15.jsx';
const DEFAULT_OUTPUT_PATH = './.output/';
var AE_TEMPLATE_PATH = (process.env.AE_TEMPLATE_PATH ? process.env.AE_TEMPLATE_PATH : DEFAULT_AE_TEMPLATE_PATH);
AE_TEMPLATE_PATH += `STM_TEMPLATE_AUTORENDER_TRAPCODE_15_NO_PSD_${process.platform === 'win32' ? 'WIN' : 'MAC'}.aep`;
if (process.env.AE_TEMPLATE) AE_TEMPLATE_PATH = process.env.AE_TEMPLATE;
var AE_TEMPLATE_URL = `file://${path.resolve(__dirname, AE_TEMPLATE_PATH)}`;
var AE_AUTORENDER_SCRIPT_PATH = process.env.AE_AUTORENDER_SCRIPT_PATH ? process.env.AE_AUTORENDER_SCRIPT_PATH : DEFAULT_AE_AUTORENDER_SCRIPT_PATH;
var AE_AUTORENDER_SCRIPT_URL = `file://${path.resolve(__dirname, AE_AUTORENDER_SCRIPT_PATH)}`;
var OUTPUT_PATH = path.resolve(__dirname, process.env.OUTPUT_PATH ? process.env.OUTPUT_PATH : DEFAULT_OUTPUT_PATH);
const WORKDIR_PATH = path.resolve(__dirname, OUTPUT_PATH, `.nexrender`);
const jobTemplate = require(path.resolve(__dirname, `./nexrender_templates/nexrender_template_lossless_${_PLATFORM}.json`));
// Configure the template by replacing placeholders with the script and asset paths.
const configureJobTemplate = ({
jobTemplate,
projectScriptPath,
tempDir,
songDetails,
encodeOutputAsMP4 = true,
copyOutput = false,
renderProgressHandler
}) => {
var jobJson = { ...jobTemplate };
let {
projectName,
songFile,
backgroundFile,
artworkFile,
outputPath
} = songDetails;
let fileExtension = jobJson.template.outputExt;
if (!fileExtension) throw new Error("Could not determine file extension in job template.", jobJson);
jobJson.template.src = AE_TEMPLATE_URL;
// Here it's important that the paths are considered from the directory in which
// the process itself is ran, as the paths will be relative to this directory.
// TODO: Edit this to support songFiles.
if (songFile) jobJson.assets.push({
type: "audio",
src: copyFileAndReturnFileURI(songFile, tempDir),
// layerName: "Song",
// Use layer indeces for now as they are more stable. (Multiple renders seem
// to unreliably change the layerNames for subsequent renders)
layerIndex: 1,
composition: "Change Song"
});
if (backgroundFile) jobJson.assets.push({
type: "image",
src: copyFileAndReturnFileURI(backgroundFile, tempDir),
// layerName: "Background",
layerIndex: 2,
composition: "Change Background"
});
if (artworkFile) jobJson.assets.push({
type: "image",
src: copyFileAndReturnFileURI(artworkFile, tempDir),
// layerName: "Artwork",
layerIndex: 3,
composition: "Change Artwork"
});
jobJson.assets.push({
type: 'script',
src: `file://${path.resolve(projectScriptPath)}`
});
let outputNameWithoutExtension = `${OUTPUT_PATH}/${projectName}/${projectName}_render`;
let encodedOutputName = path.basename
// Add the action-copy postrender action.
// jobJson.actions.postrender[0].output = `${outputNameWithoutExtension}.${fileExtension}`;
if (copyOutput)
jobJson.actions.postrender.push(createCopyAction({
outputName: `${outputNameWithoutExtension}.${fileExtension}`
}));
// Log to console when the render progress changes. (TEMP) - Ensure that we attach this to the specific job in the future.
jobJson.onRenderProgress = function(progress){
log(projectName, `Render progress:`, progress.renderProgress);
}
jobJson.onRenderProgress = ({renderProgress}) => {
log(projectName, `Render progress:`, renderProgress);
if (renderProgressHandler) renderProgressHandler(renderProgress);
}
// Add the action-encode postrender action, if specified.
if (encodeOutputAsMP4)
jobJson.actions.postrender.push(createEncodeAction({
outputName: outputNameWithoutExtension
}));
return jobJson;
};
const configureScriptTemplate = (projectDetails, tempDir) => new Promise((resolve, reject) => {
console.log(`Fetching script from`, AE_AUTORENDER_SCRIPT_PATH);
fs.readFile(path.resolve(__dirname, AE_AUTORENDER_SCRIPT_PATH), (err, autorenderScriptTemplate) => {
autorenderScriptTemplate = autorenderScriptTemplate.toString('utf8');
// Replace placeholder contenet with project-specific details.
var projectScript = ejs.render(autorenderScriptTemplate, projectDetails.songDetails);
// log(`Reading autorenderScriptTemplate:`, autorenderScriptTemplate);
// Write the script template to the output dir.
const finalScriptLocation = path.resolve(tempDir, `${projectDetails.songDetails.projectName}_script.jsx`);
fs.writeFile(finalScriptLocation, projectScript, err => {
if (err) reject(err);
log(`Written autorenderScriptTemplate to`, finalScriptLocation)
return resolve(finalScriptLocation);
});
});
});
// Configures the directory structure by creating the project folder and temp folders.
const configureDirectoryStructure = ({outputPath, projectName}) => new Promise((resolve, reject) => {
// Set the new OUTPUT_PATH.
if (outputPath) OUTPUT_PATH = path.resolve(__dirname, outputPath);
let tempDir = path.resolve(__dirname, OUTPUT_PATH, projectName, '.temp');
log(`Creating temporary directory structure in`, tempDir);
mkdirp(tempDir, (err) => {
if (err) reject(err);
return resolve(tempDir);
});
});
const configureDirectoryStructureSync = (outputPath, projectName) => {
// Set the new OUTPUT_PATH.
if (outputPath) OUTPUT_PATH = path.resolve(__dirname, outputPath);
let tempDir = path.resolve(__dirname, OUTPUT_PATH, projectName, '.temp');
log(`Creating temporary directory structure in`, tempDir);
mkdirp.sync(tempDir);
return tempDir;
};
// Ensure that the workpath has been created, if it does not exist already.
log(`Ensuring that the output path`, WORKDIR_PATH, `exists.`);
mkdirp.sync(WORKDIR_PATH);
log(`Platform:`, _PLATFORM);
log(`Binary:`, process.env.BINARY || "unspecified.");
log(`Skip Cleanup:`, process.env.SKIP_CLEANUP);
// Configure settings.
const settings = nexrender.init({
logger: console,
workpath: WORKDIR_PATH,
binary: process.env.BINARY,
reuse: process.env.REUSE,
skipCleanup: process.env.SKIP_CLEANUP
});
module.exports = {
// TODO: Add support for a callback function whic is called everytime the render progress changes, so that the Job object progress property can be updated.
render: async function (params){
// Ensure that we do not receive any destructuring errors on the last line
// if no renderProgressHandler fuction has been passed.
if (!params.renderProgressHandler) params.renderProgressHandler = null;
var {
outputPath,
songDetails,
renderProgressHandler
} = params;
var { projectName, songName, artistName, genre, visualizerColour } = songDetails;
log(`Recieved request to render with params:`, params, `and details`, songDetails);
if (!projectName) return reject("Project name not supplied.");
if (!songName || !artistName || !genre || !visualizerColour)
return reject("Incomplete song details. Required: songName, artistName, genre, visualizerColour");
log(`Configuring directory structure.`);
let tempDir = await configureDirectoryStructure({outputPath, projectName});
log(`Configured directory structure:`, fs.readdirSync(path.resolve(OUTPUT_PATH, projectName)));
log(`Configuring script template.`);
const projectScriptPath = await configureScriptTemplate(params, tempDir);
log(`Saved + written script template.`);
log(`Configuring jobJson`);
const jobJson = configureJobTemplate({
jobTemplate,
projectScriptPath,
tempDir,
songDetails: params.songDetails,
renderProgressHandler
});
//const jobJson = configureJobTemplate(jobTemplate, projectScriptPath,tempDir, params.songDetails);
log(`Configured jobJson:`, jobJson);
fs.writeFileSync(path.resolve(__dirname, OUTPUT_PATH, projectName, '.temp', 'jobJson.json'), JSON.stringify(jobJson, null, 2));
log(`Attempting to render now.`);
const renderJob = await nexrender.render(jobJson, settings);
// TODO: Add cleanup operation.
log(`Finished rendering`, renderJob);
return renderJob;
},
configureDirectoryStructure,
configureDirectoryStructureSync,
OUTPUT_PATH
}
function log(...msg){
logger.info(`AUTORENDER | ${msg.map(obj => require('util').inspect(obj)).join(' ')}`);
}
function determinePlatform(){
let platform = require('os').platform();
switch (platform) {
case 'darwin':
return 'mac';
case 'win32':
return 'windows';
default:
throw new Error("Unsupported platform: " + platform);
}
}