-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert-image.ts
353 lines (300 loc) · 9.15 KB
/
convert-image.ts
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import { Logger, Task } from 'graphile-worker';
import { PromisePool } from '@supercharge/promise-pool';
import { GetObjectCommand, PutObjectAclCommand } from '@aws-sdk/client-s3';
import { Upload } from '@aws-sdk/lib-storage';
import exifr from 'exifr';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import * as path from 'node:path';
import { spawn } from 'node:child_process';
import * as os from 'os';
import { env } from '@app/config/env.js';
import { s3 } from '../s3.js';
import { TempFile } from '../fs.js';
export const convertTypes = ['image/avif', 'image/webp', 'image/jpeg'] as const;
export const convertSizes = [2560, 960, 3840, 480, 1440] as const;
const flatten = <T>(arr: T[][]): T[] => ([] as T[]).concat(...arr);
export const spawnAsync = async (command: string, args: string[]): Promise<void> => {
// using declaration https://github.com/tc39/proposal-explicit-resource-management
using process = spawn(command, args);
await new Promise((resolve, reject) => {
let stdout = '';
let stderr = '';
process.stdout.on('data', (data) => {
stdout += data;
});
process.stderr.on('data', (data) => {
stderr += data;
});
process.on('close', (code) => {
if (code !== 0) {
reject(new Error(`FFmpeg exited with code ${code}: ${stdout} ${stderr}`));
} else {
resolve(stdout);
}
});
});
};
interface ConvertSource {
filePath: string;
hdr: boolean;
type: (typeof convertTypes)[number] | string;
}
interface ConvertTarget {
filePath: string;
size: (typeof convertSizes)[number];
type: (typeof convertTypes)[number];
}
interface ConvertResult {
filePath: string;
type: (typeof convertTypes)[number];
size: (typeof convertSizes)[number];
}
export interface ImageSource {
s3_key: string;
size: number;
type: string;
}
export const convertImage = async (
source: ConvertSource,
target: ConvertTarget,
logger: Logger,
): Promise<ConvertResult> => {
const lossless = target.size === 3840;
const scaleArg = `w='if(gt(iw,ih),${target.size},-2)':h='if(gt(iw,ih),-2,${target.size})'`;
let commandArgs = [
['-vf', `scale=${scaleArg},format=yuv420p`],
['-c:v', 'libwebp'],
['-lossless', lossless ? '1' : '0'],
];
// simple jpeg conversion
if (target.type === 'image/jpeg') {
commandArgs = [
['-vf', `scale=${scaleArg}`],
['-qscale:v', '80'],
];
}
if (target.type === 'image/avif') {
commandArgs = [
['-vf', `scale=${scaleArg}`],
['-c:v', 'libaom-av1'],
['-crf', '6'],
['-still-picture', '1'],
];
}
// convert to avif with hdr settings
if (source.hdr && target.type === 'image/avif') {
commandArgs = [
['-colorspace', 'bt2020nc'],
['-color_trc', 'smpte2084'],
['-color_primaries', 'bt2020'],
['-c:v', 'libaom-av1'],
['-crf', '6'],
['-still-picture', '1'],
['-vf', `scale=${scaleArg}`],
];
}
// fallback to web with sdr tonemapping
if (source.hdr && target.type === 'image/webp') {
commandArgs = [
[
'-vf',
`scale=${scaleArg},format=yuv420p,zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p`,
],
['-c:v', 'libwebp'],
['-lossless', lossless ? '1' : '0'],
];
}
const args = ['-y', '-i', source.filePath, ...commandArgs.flat(), target.filePath];
logger.debug(`🤓 Converting image: ffmpeg ${args.join(' ')}`);
await spawnAsync('ffmpeg', args);
logger.debug(`😎 Image converted => ${target.filePath}`);
return {
filePath: target.filePath,
type: target.type,
size: target.size,
};
};
export interface ConvertImagePayload {
image_id: number;
}
type ExifData = Record<string, string | number | number[]> & { errors: [[string]] };
type DbImage = {
id: number;
s3_key: string;
s3_bucket: string;
exif_data: ExifData;
};
// @see https://github.com/MikeKovarik/exifr/issues/115
export const detectHdr = (contentType: string, exifData: ExifData) =>
contentType === 'image/avif' && typeof exifData.Software === 'string';
// exifData.Software.startsWith('Adobe Photoshop Camera Raw 15');
export const getExifData = (filePath: string) =>
exifr.parse(filePath, {
tiff: true,
xmp: true,
icc: true,
iptc: true,
jfif: true,
exif: true,
gps: true,
interop: true,
translateKeys: true,
translateValues: true,
reviveValues: true,
sanitize: true,
mergeOutput: true,
});
export const convertImageTask: Task = async (inPayload, { logger, query }) => {
try {
const payload = inPayload as ConvertImagePayload;
const imageId = payload.image_id;
logger.info(`Converting image: ${imageId}`);
const {
rows: [image],
} = await query<DbImage>(
`
select
id,
s3_key,
s3_bucket,
exif_data
from
app_public.images
where
id = $1
`,
[imageId],
);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (image == null) {
throw new Error(`Image not found: ${imageId}`);
}
const command = new GetObjectCommand({
Bucket: image.s3_bucket,
Key: image.s3_key,
});
const obj = await s3.send(command);
if (!(obj.Body instanceof Readable)) {
throw new Error('Body is not a readable stream');
}
if (obj.ContentType == null) {
throw new Error('Content type is null');
}
await using sourceTmpFile = await TempFile.createWrite();
const writeStream = sourceTmpFile.handle.createWriteStream();
await pipeline(obj.Body, writeStream);
await sourceTmpFile.handle.close();
const exifData = await getExifData(sourceTmpFile.path);
const isHdr = detectHdr(obj.ContentType, exifData);
const source = {
filePath: sourceTmpFile.path,
hdr: isHdr,
type: obj.ContentType as string,
};
const sourcesToConvert: [ConvertSource, ConvertTarget][] = flatten(
convertSizes.map((size) => {
const targetAvif = {
type: 'image/avif' as const,
size,
filePath: path.join(
os.tmpdir(),
`${path.basename(image.s3_key, path.extname(image.s3_key))}__${size}px.avif`,
),
};
const targetWebp = {
type: 'image/webp' as const,
size,
filePath: path.join(
os.tmpdir(),
`${path.basename(image.s3_key, path.extname(image.s3_key))}__${size}px.webp`,
),
};
return [
[source, targetWebp],
[source, targetAvif],
];
}),
);
// convert 480px webp to jpeg, we need 480 for emails only
const [, target480Webp] = sourcesToConvert.find(
([, target]) => target.type === 'image/webp' && target.size === 480,
) as [ConvertSource, ConvertTarget];
const target480Jpeg = {
type: 'image/jpeg' as const,
size: 480 as const,
filePath: path.join(
os.tmpdir(),
`${path.basename(image.s3_key, path.extname(image.s3_key))}__${480}px.jpeg`,
),
};
const source480Webp = {
filePath: target480Webp.filePath,
hdr: false,
type: 'image/webp' as const,
};
sourcesToConvert.push([source480Webp, target480Jpeg]);
const convertAndUpload = async ([, target]: [
ConvertSource,
ConvertTarget,
]): Promise<ImageSource> => {
const { filePath, type, size } = await convertImage(source, target, logger);
await using tempFile = await TempFile.createRead(filePath);
const fileStream = tempFile.handle.createReadStream();
const destKey = path.join(path.dirname(image.s3_key), path.basename(filePath));
const upload = new Upload({
client: s3,
params: {
Bucket: env.S3_BUCKET_NAME,
Key: destKey,
Body: fileStream,
ContentType: type,
ACL: 'public-read',
},
});
await upload.done();
logger.debug(`📤 Image uploaded to s3 => ${destKey}`);
return {
size,
s3_key: destKey,
type,
};
};
const { results: uploadedImages } = await PromisePool.withConcurrency(2)
.for(sourcesToConvert)
.handleError((err) => {
throw err;
})
.process(convertAndUpload);
await query(
`
update
app_public.images
set
sources = array (
select
array_agg(rows)
from
json_populate_recordset(null::app_public.image_source, $1) as rows),
exif_data = $2,
is_hdr = $3
where
id = $4
returning
id
`,
[JSON.stringify(uploadedImages), exifData, isHdr, imageId],
);
// set ACL to authenticated_read to source image
const updateAclCommand = new PutObjectAclCommand({
Bucket: image.s3_bucket,
Key: image.s3_key,
ACL: 'authenticated-read',
});
await s3.send(updateAclCommand);
logger.info(`🤌 Image with id ${imageId} converted`);
} catch (err) {
logger.error(`🫡 Error resizing image ${err}`);
throw err;
}
};