Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(464)

Side by Side Diff: third_party/WebKit/Source/modules/shapedetection/ShapeDetector.cpp

Issue 2557513003: ShapeDetection: Eliminate DetectorType enum in ShapeDetector.cpp (Closed)
Patch Set: Move tainting logic into detect() Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « third_party/WebKit/Source/modules/shapedetection/ShapeDetector.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "modules/shapedetection/ShapeDetector.h" 5 #include "modules/shapedetection/ShapeDetector.h"
6 6
7 #include "core/dom/DOMException.h" 7 #include "core/dom/DOMException.h"
8 #include "core/dom/DOMRect.h" 8 #include "core/dom/DOMRect.h"
9 #include "core/dom/Document.h" 9 #include "core/dom/Document.h"
10 #include "core/fetch/ImageResource.h" 10 #include "core/fetch/ImageResource.h"
11 #include "core/frame/ImageBitmap.h" 11 #include "core/frame/ImageBitmap.h"
12 #include "core/frame/LocalDOMWindow.h"
13 #include "core/frame/LocalFrame.h" 12 #include "core/frame/LocalFrame.h"
14 #include "core/html/HTMLImageElement.h" 13 #include "core/html/HTMLImageElement.h"
15 #include "core/html/HTMLVideoElement.h" 14 #include "core/html/HTMLVideoElement.h"
16 #include "core/html/canvas/CanvasImageSource.h" 15 #include "core/html/canvas/CanvasImageSource.h"
17 #include "modules/shapedetection/DetectedBarcode.h"
18 #include "platform/graphics/Image.h" 16 #include "platform/graphics/Image.h"
19 #include "public/platform/InterfaceProvider.h"
20 #include "third_party/skia/include/core/SkImage.h" 17 #include "third_party/skia/include/core/SkImage.h"
21 #include "third_party/skia/include/core/SkImageInfo.h" 18 #include "third_party/skia/include/core/SkImageInfo.h"
22 #include "wtf/CheckedNumeric.h" 19 #include "wtf/CheckedNumeric.h"
23 20
24 namespace blink { 21 namespace blink {
25 22
26 namespace { 23 namespace {
27 24
28 static CanvasImageSource* toImageSourceInternal( 25 mojo::ScopedSharedBufferHandle getSharedBufferOnData(
29 const CanvasImageSourceUnion& value) { 26 ScriptPromiseResolver* resolver,
30 if (value.isHTMLImageElement()) 27 uint8_t* data,
31 return value.getAsHTMLImageElement(); 28 int size) {
29 DCHECK(data);
30 DCHECK(size);
31 ScriptPromise promise = resolver->promise();
32 32
33 if (value.isImageBitmap() && 33 mojo::ScopedSharedBufferHandle sharedBufferHandle =
34 !static_cast<ImageBitmap*>(value.getAsImageBitmap())->isNeutered()) { 34 mojo::SharedBufferHandle::Create(size);
35 return value.getAsImageBitmap(); 35 if (!sharedBufferHandle->is_valid()) {
36 resolver->reject(
37 DOMException::create(InvalidStateError, "Internal allocation error"));
38 return sharedBufferHandle;
36 } 39 }
37 40
38 if (value.isHTMLVideoElement()) 41 const mojo::ScopedSharedBufferMapping mappedBuffer =
39 return value.getAsHTMLVideoElement(); 42 sharedBufferHandle->Map(size);
43 DCHECK(mappedBuffer.get());
44 memcpy(mappedBuffer.get(), data, size);
40 45
41 return nullptr; 46 return sharedBufferHandle;
42 } 47 }
43 48
44 } // anonymous namespace 49 } // anonymous namespace
45 50
46 ShapeDetector::ShapeDetector(LocalFrame& frame) { 51 ShapeDetector::ShapeDetector(LocalFrame& frame) {
47 DCHECK(!m_faceService.is_bound());
48 DCHECK(!m_barcodeService.is_bound());
49 DCHECK(frame.interfaceProvider()); 52 DCHECK(frame.interfaceProvider());
50 frame.interfaceProvider()->getInterface(mojo::GetProxy(&m_faceService));
51 frame.interfaceProvider()->getInterface(mojo::GetProxy(&m_barcodeService));
52 m_faceService.set_connection_error_handler(convertToBaseCallback(WTF::bind(
53 &ShapeDetector::onFaceServiceConnectionError, wrapWeakPersistent(this))));
54 m_barcodeService.set_connection_error_handler(convertToBaseCallback(
55 WTF::bind(&ShapeDetector::onBarcodeServiceConnectionError,
56 wrapWeakPersistent(this))));
57 } 53 }
58 54
59 ShapeDetector::ShapeDetector(LocalFrame& frame, 55 ScriptPromise ShapeDetector::detect(ScriptState* scriptState,
60 const FaceDetectorOptions& options) 56 const CanvasImageSourceUnion& imageSource) {
61 : ShapeDetector(frame) {
62 m_faceDetectorOptions = mojom::blink::FaceDetectorOptions::New();
63 m_faceDetectorOptions->max_detected_faces = options.maxDetectedFaces();
64 m_faceDetectorOptions->fast_mode = options.fastMode();
65 }
66
67 ScriptPromise ShapeDetector::detectShapes(
68 ScriptState* scriptState,
69 DetectorType detectorType,
70 const CanvasImageSourceUnion& imageSource) {
71 CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource);
72
73 ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); 57 ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
74 ScriptPromise promise = resolver->promise(); 58 ScriptPromise promise = resolver->promise();
75 59
76 if (!imageSourceInternal) { 60 CanvasImageSource* canvasImageSource;
61 if (imageSource.isHTMLImageElement()) {
62 canvasImageSource = imageSource.getAsHTMLImageElement();
63 } else if (imageSource.isImageBitmap()) {
64 canvasImageSource = imageSource.getAsImageBitmap();
65 } else if (imageSource.isHTMLVideoElement()) {
66 canvasImageSource = imageSource.getAsHTMLVideoElement();
67 } else {
77 // TODO(mcasas): Implement more CanvasImageSources, https://crbug.com/659138 68 // TODO(mcasas): Implement more CanvasImageSources, https://crbug.com/659138
78 NOTIMPLEMENTED() << "Unsupported CanvasImageSource"; 69 NOTIMPLEMENTED() << "Unsupported CanvasImageSource";
79 resolver->reject( 70 resolver->reject(
80 DOMException::create(NotFoundError, "Unsupported source.")); 71 DOMException::create(NotFoundError, "Unsupported source."));
81 return promise; 72 return promise;
82 } 73 }
83 74
84 if (imageSourceInternal->wouldTaintOrigin( 75 if (canvasImageSource->wouldTaintOrigin(
85 scriptState->getExecutionContext()->getSecurityOrigin())) { 76 scriptState->getExecutionContext()->getSecurityOrigin())) {
86 resolver->reject( 77 resolver->reject(
87 DOMException::create(SecurityError, "Source would taint origin.")); 78 DOMException::create(SecurityError, "Source would taint origin."));
88 return promise; 79 return promise;
89 } 80 }
90 81
91 if (imageSource.isHTMLImageElement()) { 82 if (imageSource.isHTMLImageElement()) {
92 return detectShapesOnImageElement( 83 return detectShapesOnImageElement(resolver,
93 detectorType, resolver, 84 imageSource.getAsHTMLImageElement());
94 static_cast<HTMLImageElement*>(imageSourceInternal)); 85 } else if (imageSource.isImageBitmap()) {
95 } 86 return detectShapesOnImageBitmap(resolver, imageSource.getAsImageBitmap());
96 if (imageSourceInternal->isImageBitmap()) { 87 } else if (imageSource.isHTMLVideoElement()) {
97 return detectShapesOnImageBitmap( 88 return detectShapesOnVideoElement(resolver,
98 detectorType, resolver, static_cast<ImageBitmap*>(imageSourceInternal)); 89 imageSource.getAsHTMLVideoElement());
99 }
100 if (imageSourceInternal->isVideoElement()) {
101 return detectShapesOnVideoElement(
102 detectorType, resolver,
103 static_cast<HTMLVideoElement*>(imageSourceInternal));
104 } 90 }
105 91
106 NOTREACHED(); 92 NOTREACHED();
107 return promise; 93 return promise;
108 } 94 }
109 95
110 ScriptPromise ShapeDetector::detectShapesOnImageElement( 96 ScriptPromise ShapeDetector::detectShapesOnImageElement(
111 DetectorType detectorType,
112 ScriptPromiseResolver* resolver, 97 ScriptPromiseResolver* resolver,
113 const HTMLImageElement* img) { 98 const HTMLImageElement* img) {
114 ScriptPromise promise = resolver->promise(); 99 ScriptPromise promise = resolver->promise();
100
115 if (img->bitmapSourceSize().isZero()) { 101 if (img->bitmapSourceSize().isZero()) {
116 resolver->resolve(HeapVector<Member<DOMRect>>()); 102 resolver->resolve(HeapVector<Member<DOMRect>>());
117 return promise; 103 return promise;
118 } 104 }
119 105
120 ImageResource* const imageResource = img->cachedImage(); 106 ImageResource* const imageResource = img->cachedImage();
121 if (!imageResource || imageResource->errorOccurred()) { 107 if (!imageResource || imageResource->errorOccurred()) {
122 resolver->reject(DOMException::create( 108 resolver->reject(DOMException::create(
123 InvalidStateError, "Failed to load or decode HTMLImageElement.")); 109 InvalidStateError, "Failed to load or decode HTMLImageElement."));
124 return promise; 110 return promise;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
163 sharedBufferHandle->Map(allocationSize); 149 sharedBufferHandle->Map(allocationSize);
164 150
165 const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes()); 151 const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes());
166 if (!image->readPixels(pixmap, 0, 0)) { 152 if (!image->readPixels(pixmap, 0, 0)) {
167 resolver->reject(DOMException::create( 153 resolver->reject(DOMException::create(
168 InvalidStateError, 154 InvalidStateError,
169 "Failed to read pixels: Unable to decompress or unsupported format.")); 155 "Failed to read pixels: Unable to decompress or unsupported format."));
170 return promise; 156 return promise;
171 } 157 }
172 158
173 if (detectorType == DetectorType::Face) { 159 return doDetect(resolver, std::move(sharedBufferHandle), img->naturalWidth(),
174 if (!m_faceService) { 160 img->naturalHeight());
175 resolver->reject(DOMException::create(
176 NotSupportedError, "Face detection service unavailable."));
177 return promise;
178 }
179 m_faceServiceRequests.add(resolver);
180 m_faceService->Detect(std::move(sharedBufferHandle), img->naturalWidth(),
181 img->naturalHeight(), m_faceDetectorOptions.Clone(),
182 convertToBaseCallback(WTF::bind(
183 &ShapeDetector::onDetectFaces,
184 wrapPersistent(this), wrapPersistent(resolver))));
185 } else if (detectorType == DetectorType::Barcode) {
186 if (!m_barcodeService) {
187 resolver->reject(DOMException::create(
188 NotSupportedError, "Barcode detection service unavailable."));
189 return promise;
190 }
191 m_barcodeServiceRequests.add(resolver);
192 m_barcodeService->Detect(
193 std::move(sharedBufferHandle), img->naturalWidth(),
194 img->naturalHeight(),
195 convertToBaseCallback(WTF::bind(&ShapeDetector::onDetectBarcodes,
196 wrapPersistent(this),
197 wrapPersistent(resolver))));
198 } else {
199 NOTREACHED() << "Unsupported detector type";
200 }
201
202 return promise;
203 } 161 }
204 162
205 ScriptPromise ShapeDetector::detectShapesOnImageBitmap( 163 ScriptPromise ShapeDetector::detectShapesOnImageBitmap(
206 DetectorType detectorType,
207 ScriptPromiseResolver* resolver, 164 ScriptPromiseResolver* resolver,
208 ImageBitmap* imageBitmap) { 165 ImageBitmap* imageBitmap) {
209 ScriptPromise promise = resolver->promise(); 166 ScriptPromise promise = resolver->promise();
210 if (!imageBitmap->originClean()) { 167
168 if (imageBitmap->isNeutered()) {
211 resolver->reject( 169 resolver->reject(
212 DOMException::create(SecurityError, "ImageBitmap is not origin clean")); 170 DOMException::create(InvalidStateError, "Neutered ImageBitmap."));
213 return promise; 171 return promise;
214 } 172 }
215 173
216 if (imageBitmap->size().area() == 0) { 174 if (imageBitmap->size().area() == 0) {
217 resolver->resolve(HeapVector<Member<DOMRect>>()); 175 resolver->resolve(HeapVector<Member<DOMRect>>());
218 return promise; 176 return promise;
219 } 177 }
220 178
221 SkPixmap pixmap; 179 SkPixmap pixmap;
222 RefPtr<Uint8Array> pixelData; 180 RefPtr<Uint8Array> pixelData;
223 uint8_t* pixelDataPtr = nullptr; 181 uint8_t* pixelDataPtr = nullptr;
224 WTF::CheckedNumeric<int> allocationSize = 0; 182 WTF::CheckedNumeric<int> allocationSize = 0;
225 // Use |skImage|'s pixels if it has direct access to them, otherwise retrieve 183 // Use |skImage|'s pixels if it has direct access to them, otherwise retrieve
226 // them from elsewhere via copyBitmapData(). 184 // them from elsewhere via copyBitmapData().
227 sk_sp<SkImage> skImage = imageBitmap->bitmapImage()->imageForCurrentFrame(); 185 sk_sp<SkImage> skImage = imageBitmap->bitmapImage()->imageForCurrentFrame();
228 if (skImage->peekPixels(&pixmap)) { 186 if (skImage->peekPixels(&pixmap)) {
229 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr()); 187 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr());
230 allocationSize = pixmap.getSafeSize(); 188 allocationSize = pixmap.getSafeSize();
231 } else { 189 } else {
232 pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied() 190 pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied()
233 ? PremultiplyAlpha 191 ? PremultiplyAlpha
234 : DontPremultiplyAlpha, 192 : DontPremultiplyAlpha,
235 N32ColorType); 193 N32ColorType);
236 pixelDataPtr = pixelData->data(); 194 pixelDataPtr = pixelData->data();
237 allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */; 195 allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */;
238 } 196 }
239 197
240 return detectShapesOnData(detectorType, resolver, pixelDataPtr, 198 mojo::ScopedSharedBufferHandle sharedBufferHandle = getSharedBufferOnData(
241 allocationSize.ValueOrDefault(0), 199 resolver, pixelDataPtr, allocationSize.ValueOrDefault(0));
242 imageBitmap->width(), imageBitmap->height()); 200 if (!sharedBufferHandle->is_valid())
201 return promise;
202
203 return doDetect(resolver, std::move(sharedBufferHandle), imageBitmap->width(),
204 imageBitmap->height());
243 } 205 }
244 206
245 ScriptPromise ShapeDetector::detectShapesOnVideoElement( 207 ScriptPromise ShapeDetector::detectShapesOnVideoElement(
246 DetectorType detectorType,
247 ScriptPromiseResolver* resolver, 208 ScriptPromiseResolver* resolver,
248 const HTMLVideoElement* video) { 209 const HTMLVideoElement* video) {
249 ScriptPromise promise = resolver->promise(); 210 ScriptPromise promise = resolver->promise();
250
251 // TODO(mcasas): Check if |video| is actually playing a MediaStream by using 211 // TODO(mcasas): Check if |video| is actually playing a MediaStream by using
252 // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if 212 // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if
253 // there is a local WebCam associated, there might be sophisticated ways to 213 // there is a local WebCam associated, there might be sophisticated ways to
254 // detect faces on it. Until then, treat as a normal <video> element. 214 // detect faces on it. Until then, treat as a normal <video> element.
255 215
256 // !hasAvailableVideoFrame() is a bundle of invalid states. 216 // !hasAvailableVideoFrame() is a bundle of invalid states.
257 if (!video->hasAvailableVideoFrame()) { 217 if (!video->hasAvailableVideoFrame()) {
258 resolver->reject(DOMException::create( 218 resolver->reject(DOMException::create(
259 InvalidStateError, "Invalid HTMLVideoElement or state.")); 219 InvalidStateError, "Invalid HTMLVideoElement or state."));
260 return promise; 220 return promise;
(...skipping 17 matching lines...) Expand all
278 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr()); 238 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr());
279 allocationSize = pixmap.getSafeSize(); 239 allocationSize = pixmap.getSafeSize();
280 } else { 240 } else {
281 // TODO(mcasas): retrieve the pixels from elsewhere. 241 // TODO(mcasas): retrieve the pixels from elsewhere.
282 NOTREACHED(); 242 NOTREACHED();
283 resolver->reject(DOMException::create( 243 resolver->reject(DOMException::create(
284 InvalidStateError, "Failed to get pixels for current frame.")); 244 InvalidStateError, "Failed to get pixels for current frame."));
285 return promise; 245 return promise;
286 } 246 }
287 247
288 return detectShapesOnData(detectorType, resolver, pixelDataPtr, 248 mojo::ScopedSharedBufferHandle sharedBufferHandle = getSharedBufferOnData(
289 allocationSize.ValueOrDefault(0), image->width(), 249 resolver, pixelDataPtr, allocationSize.ValueOrDefault(0));
290 image->height()); 250 if (!sharedBufferHandle->is_valid())
291 } 251 return promise;
292 252
293 ScriptPromise ShapeDetector::detectShapesOnData(DetectorType detectorType, 253 return doDetect(resolver, std::move(sharedBufferHandle), image->width(),
294 ScriptPromiseResolver* resolver, 254 image->height());
295 uint8_t* data,
296 int size,
297 int width,
298 int height) {
299 DCHECK(data);
300 DCHECK(size);
301 ScriptPromise promise = resolver->promise();
302
303 mojo::ScopedSharedBufferHandle sharedBufferHandle =
304 mojo::SharedBufferHandle::Create(size);
305 if (!sharedBufferHandle->is_valid()) {
306 resolver->reject(
307 DOMException::create(InvalidStateError, "Internal allocation error"));
308 return promise;
309 }
310
311 const mojo::ScopedSharedBufferMapping mappedBuffer =
312 sharedBufferHandle->Map(size);
313 DCHECK(mappedBuffer.get());
314
315 memcpy(mappedBuffer.get(), data, size);
316
317 if (detectorType == DetectorType::Face) {
318 if (!m_faceService) {
319 resolver->reject(DOMException::create(
320 NotSupportedError, "Face detection service unavailable."));
321 return promise;
322 }
323 m_faceServiceRequests.add(resolver);
324 m_faceService->Detect(std::move(sharedBufferHandle), width, height,
325 m_faceDetectorOptions.Clone(),
326 convertToBaseCallback(WTF::bind(
327 &ShapeDetector::onDetectFaces,
328 wrapPersistent(this), wrapPersistent(resolver))));
329 } else if (detectorType == DetectorType::Barcode) {
330 if (!m_barcodeService) {
331 resolver->reject(DOMException::create(
332 NotSupportedError, "Barcode detection service unavailable."));
333 return promise;
334 }
335 m_barcodeServiceRequests.add(resolver);
336 m_barcodeService->Detect(
337 std::move(sharedBufferHandle), width, height,
338 convertToBaseCallback(WTF::bind(&ShapeDetector::onDetectBarcodes,
339 wrapPersistent(this),
340 wrapPersistent(resolver))));
341 } else {
342 NOTREACHED() << "Unsupported detector type";
343 }
344 sharedBufferHandle.reset();
345 return promise;
346 }
347
348 void ShapeDetector::onDetectFaces(
349 ScriptPromiseResolver* resolver,
350 mojom::blink::FaceDetectionResultPtr faceDetectionResult) {
351 DCHECK(m_faceServiceRequests.contains(resolver));
352 m_faceServiceRequests.remove(resolver);
353
354 HeapVector<Member<DOMRect>> detectedFaces;
355 for (const auto& boundingBox : faceDetectionResult->bounding_boxes) {
356 detectedFaces.append(DOMRect::create(boundingBox->x, boundingBox->y,
357 boundingBox->width,
358 boundingBox->height));
359 }
360
361 resolver->resolve(detectedFaces);
362 }
363
364 void ShapeDetector::onDetectBarcodes(
365 ScriptPromiseResolver* resolver,
366 Vector<mojom::blink::BarcodeDetectionResultPtr> barcodeDetectionResults) {
367 DCHECK(m_barcodeServiceRequests.contains(resolver));
368 m_barcodeServiceRequests.remove(resolver);
369
370 HeapVector<Member<DetectedBarcode>> detectedBarcodes;
371 for (const auto& barcode : barcodeDetectionResults) {
372 detectedBarcodes.append(DetectedBarcode::create(
373 barcode->raw_value,
374 DOMRect::create(barcode->bounding_box->x, barcode->bounding_box->y,
375 barcode->bounding_box->width,
376 barcode->bounding_box->height)));
377 }
378
379 resolver->resolve(detectedBarcodes);
380 }
381
382 void ShapeDetector::onFaceServiceConnectionError() {
383 for (const auto& request : m_faceServiceRequests) {
384 request->reject(DOMException::create(NotSupportedError,
385 "Face Detection not implemented."));
386 }
387 m_faceServiceRequests.clear();
388 m_faceService.reset();
389 }
390
391 void ShapeDetector::onBarcodeServiceConnectionError() {
392 for (const auto& request : m_barcodeServiceRequests) {
393 request->reject(DOMException::create(NotSupportedError,
394 "Barcode Detection not implemented."));
395 }
396 m_barcodeServiceRequests.clear();
397 m_barcodeService.reset();
398 }
399
400 DEFINE_TRACE(ShapeDetector) {
401 visitor->trace(m_faceServiceRequests);
402 visitor->trace(m_barcodeServiceRequests);
403 } 255 }
404 256
405 } // namespace blink 257 } // namespace blink
OLDNEW
« no previous file with comments | « third_party/WebKit/Source/modules/shapedetection/ShapeDetector.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698