forked from GoogleChrome/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscreenshot-thumbnails.js
168 lines (144 loc) · 6.07 KB
/
screenshot-thumbnails.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
/**
* @license Copyright 2017 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import jpeg from 'jpeg-js';
import {Audit} from './audit.js';
import {LighthouseError} from '../lib/lh-error.js';
import {Speedline} from '../computed/speedline.js';
const NUMBER_OF_THUMBNAILS = 8;
/** @typedef {LH.Artifacts.Speedline['frames'][0]} SpeedlineFrame */
class ScreenshotThumbnails extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'screenshot-thumbnails',
scoreDisplayMode: Audit.SCORING_MODES.INFORMATIVE,
title: 'Screenshot Thumbnails',
description: 'This is what the load of your site looked like.',
requiredArtifacts: ['traces', 'GatherContext'],
};
}
/**
* Scales down an image to THUMBNAIL_WIDTH using nearest neighbor for speed, maintains aspect
* ratio of the original thumbnail.
*
* @param {ReturnType<SpeedlineFrame['getParsedImage']>} imageData
* @param {number} scaledWidth
* @return {{width: number, height: number, data: Uint8Array}}
*/
static scaleImageToThumbnail(imageData, scaledWidth) {
const scaleFactor = imageData.width / scaledWidth;
const scaledHeight = Math.floor(imageData.height / scaleFactor);
const outPixels = new Uint8Array(scaledWidth * scaledHeight * 4);
for (let i = 0; i < scaledWidth; i++) {
for (let j = 0; j < scaledHeight; j++) {
const origX = Math.floor(i * scaleFactor);
const origY = Math.floor(j * scaleFactor);
const origPos = (origY * imageData.width + origX) * 4;
const outPos = (j * scaledWidth + i) * 4;
outPixels[outPos] = imageData.data[origPos];
outPixels[outPos + 1] = imageData.data[origPos + 1];
outPixels[outPos + 2] = imageData.data[origPos + 2];
outPixels[outPos + 3] = imageData.data[origPos + 3];
}
}
return {
width: scaledWidth,
height: scaledHeight,
data: outPixels,
};
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async _audit(artifacts, context) {
const trace = artifacts.traces[Audit.DEFAULT_PASS];
/** @type {Map<SpeedlineFrame, string>} */
const cachedThumbnails = new Map();
const speedline = await Speedline.request(trace, context);
// Make the minimum time range 3s so sites that load super quickly don't get a single screenshot
const minimumTimelineDuration = context.options.minimumTimelineDuration || 3000;
const numberOfThumbnails = context.options.numberOfThumbnails || NUMBER_OF_THUMBNAILS;
const thumbnailWidth = context.options.thumbnailWidth || null;
const thumbnails = [];
const analyzedFrames = speedline.frames.filter(frame => !frame.isProgressInterpolated());
const maxFrameTime =
speedline.complete ||
Math.max(...speedline.frames.map(frame => frame.getTimeStamp() - speedline.beginning));
const timelineEnd = Math.max(maxFrameTime, minimumTimelineDuration);
if (!analyzedFrames.length || !Number.isFinite(timelineEnd)) {
throw new LighthouseError(LighthouseError.errors.INVALID_SPEEDLINE);
}
for (let i = 1; i <= numberOfThumbnails; i++) {
const targetTimestamp = speedline.beginning + timelineEnd * i / numberOfThumbnails;
/** @type {SpeedlineFrame} */
// @ts-expect-error - there will always be at least one frame by this point. TODO: use nonnullable assertion in TS2.9
let frameForTimestamp = null;
if (i === numberOfThumbnails) {
frameForTimestamp = analyzedFrames[analyzedFrames.length - 1];
} else {
analyzedFrames.forEach(frame => {
if (frame.getTimeStamp() <= targetTimestamp) {
frameForTimestamp = frame;
}
});
}
let base64Data;
const cachedThumbnail = cachedThumbnails.get(frameForTimestamp);
if (cachedThumbnail) {
base64Data = cachedThumbnail;
} else if (thumbnailWidth !== null) {
const imageData = frameForTimestamp.getParsedImage();
const thumbnailImageData =
ScreenshotThumbnails.scaleImageToThumbnail(imageData, thumbnailWidth);
base64Data = jpeg.encode(thumbnailImageData, 90).data.toString('base64');
cachedThumbnails.set(frameForTimestamp, base64Data);
} else {
base64Data = frameForTimestamp.getImage().toString('base64');
cachedThumbnails.set(frameForTimestamp, base64Data);
}
thumbnails.push({
timing: Math.round(targetTimestamp - speedline.beginning),
timestamp: targetTimestamp * 1000,
data: `data:image/jpeg;base64,${base64Data}`,
});
}
return {
score: 1,
details: {
type: 'filmstrip',
scale: timelineEnd,
items: thumbnails,
},
};
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
try {
return await this._audit(artifacts, context);
} catch (err) {
const noFramesErrors = new Set([
LighthouseError.errors.NO_SCREENSHOTS.code,
LighthouseError.errors.SPEEDINDEX_OF_ZERO.code,
LighthouseError.errors.NO_SPEEDLINE_FRAMES.code,
LighthouseError.errors.INVALID_SPEEDLINE.code,
]);
// If a timespan didn't happen to contain frames, that's fine. Just mark not applicable.
if (noFramesErrors.has(err.code) && artifacts.GatherContext.gatherMode === 'timespan') {
return {notApplicable: true, score: 1};
}
throw err;
}
}
}
export default ScreenshotThumbnails;