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

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

Issue 2557513003: ShapeDetection: Eliminate DetectorType enum in ShapeDetector.cpp (Closed)
Patch Set: Remove state info from parent class, add doDetect() pure virtual method. 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
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 static CanvasImageSource* toImageSourceInternal(
29 const CanvasImageSourceUnion& value) { 26 const CanvasImageSourceUnion& value) {
30 if (value.isHTMLImageElement()) 27 if (value.isHTMLImageElement())
31 return value.getAsHTMLImageElement(); 28 return value.getAsHTMLImageElement();
32 29
33 if (value.isImageBitmap() && 30 if (value.isImageBitmap() &&
34 !static_cast<ImageBitmap*>(value.getAsImageBitmap())->isNeutered()) { 31 !static_cast<ImageBitmap*>(value.getAsImageBitmap())->isNeutered()) {
35 return value.getAsImageBitmap(); 32 return value.getAsImageBitmap();
36 } 33 }
37 34
38 if (value.isHTMLVideoElement()) 35 if (value.isHTMLVideoElement())
39 return value.getAsHTMLVideoElement(); 36 return value.getAsHTMLVideoElement();
40 37
41 return nullptr; 38 return nullptr;
42 } 39 }
43 40
44 } // anonymous namespace 41 } // anonymous namespace
45 42
46 ShapeDetector::ShapeDetector(LocalFrame& frame) { 43 ShapeDetector::ShapeDetector(LocalFrame& frame) {
47 DCHECK(!m_faceService.is_bound());
48 DCHECK(!m_barcodeService.is_bound());
49 DCHECK(frame.interfaceProvider()); 44 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 } 45 }
58 46
59 ShapeDetector::ShapeDetector(LocalFrame& frame, 47 ScriptPromise ShapeDetector::detect(ScriptState* scriptState,
60 const FaceDetectorOptions& options) 48 const CanvasImageSourceUnion& imageSource) {
61 : ShapeDetector(frame) { 49 ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
62 m_faceDetectorOptions = mojom::blink::FaceDetectorOptions::New(); 50 return detectShapes(scriptState, resolver, imageSource);
63 m_faceDetectorOptions->max_detected_faces = options.maxDetectedFaces();
64 m_faceDetectorOptions->fast_mode = options.fastMode();
65 } 51 }
66 52
67 ScriptPromise ShapeDetector::detectShapes( 53 ScriptPromise ShapeDetector::detectShapes(
68 ScriptState* scriptState, 54 ScriptState* scriptState,
69 DetectorType detectorType, 55 ScriptPromiseResolver* resolver,
70 const CanvasImageSourceUnion& imageSource) { 56 const CanvasImageSourceUnion& imageSource) {
57 ScriptPromise promise = resolver->promise();
71 CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource); 58 CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource);
72 59
73 ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
74 ScriptPromise promise = resolver->promise();
75
76 if (!imageSourceInternal) { 60 if (!imageSourceInternal) {
77 // TODO(mcasas): Implement more CanvasImageSources, https://crbug.com/659138 61 // TODO(mcasas): Implement more CanvasImageSources, https://crbug.com/659138
78 NOTIMPLEMENTED() << "Unsupported CanvasImageSource"; 62 NOTIMPLEMENTED() << "Unsupported CanvasImageSource";
79 resolver->reject( 63 resolver->reject(
80 DOMException::create(NotFoundError, "Unsupported source.")); 64 DOMException::create(NotFoundError, "Unsupported source."));
81 return promise; 65 return promise;
82 } 66 }
83 67
84 if (imageSourceInternal->wouldTaintOrigin( 68 if (imageSourceInternal->wouldTaintOrigin(
85 scriptState->getExecutionContext()->getSecurityOrigin())) { 69 scriptState->getExecutionContext()->getSecurityOrigin())) {
86 resolver->reject( 70 resolver->reject(
87 DOMException::create(SecurityError, "Source would taint origin.")); 71 DOMException::create(SecurityError, "Source would taint origin."));
88 return promise; 72 return promise;
89 } 73 }
90 74
91 if (imageSource.isHTMLImageElement()) { 75 if (imageSource.isHTMLImageElement()) {
92 return detectShapesOnImageElement( 76 return detectShapesOnImageElement(
93 detectorType, resolver, 77 resolver, static_cast<HTMLImageElement*>(imageSourceInternal));
Reilly Grant (use Gerrit) 2016/12/06 20:40:13 It seems to me that since this set of if statement
xianglu 2016/12/06 22:31:56 Removed duplicated logic. I think the only trade-o
94 static_cast<HTMLImageElement*>(imageSourceInternal));
95 } 78 }
96 if (imageSourceInternal->isImageBitmap()) { 79 if (imageSourceInternal->isImageBitmap()) {
97 return detectShapesOnImageBitmap( 80 return detectShapesOnImageBitmap(
98 detectorType, resolver, static_cast<ImageBitmap*>(imageSourceInternal)); 81 resolver, static_cast<ImageBitmap*>(imageSourceInternal));
99 } 82 }
100 if (imageSourceInternal->isVideoElement()) { 83 if (imageSourceInternal->isVideoElement()) {
101 return detectShapesOnVideoElement( 84 return detectShapesOnVideoElement(
102 detectorType, resolver, 85 resolver, static_cast<HTMLVideoElement*>(imageSourceInternal));
103 static_cast<HTMLVideoElement*>(imageSourceInternal));
104 } 86 }
105 87
106 NOTREACHED(); 88 NOTREACHED();
107 return promise; 89 return promise;
108 } 90 }
109 91
110 ScriptPromise ShapeDetector::detectShapesOnImageElement( 92 ScriptPromise ShapeDetector::detectShapesOnImageElement(
111 DetectorType detectorType,
112 ScriptPromiseResolver* resolver, 93 ScriptPromiseResolver* resolver,
113 const HTMLImageElement* img) { 94 const HTMLImageElement* img) {
114 ScriptPromise promise = resolver->promise(); 95 ScriptPromise promise = resolver->promise();
115 if (img->bitmapSourceSize().isZero()) { 96 if (img->bitmapSourceSize().isZero()) {
116 resolver->resolve(HeapVector<Member<DOMRect>>()); 97 resolver->resolve(HeapVector<Member<DOMRect>>());
117 return promise; 98 return promise;
118 } 99 }
119 100
120 ImageResource* const imageResource = img->cachedImage(); 101 ImageResource* const imageResource = img->cachedImage();
121 if (!imageResource || imageResource->errorOccurred()) { 102 if (!imageResource || imageResource->errorOccurred()) {
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
163 sharedBufferHandle->Map(allocationSize); 144 sharedBufferHandle->Map(allocationSize);
164 145
165 const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes()); 146 const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes());
166 if (!image->readPixels(pixmap, 0, 0)) { 147 if (!image->readPixels(pixmap, 0, 0)) {
167 resolver->reject(DOMException::create( 148 resolver->reject(DOMException::create(
168 InvalidStateError, 149 InvalidStateError,
169 "Failed to read pixels: Unable to decompress or unsupported format.")); 150 "Failed to read pixels: Unable to decompress or unsupported format."));
170 return promise; 151 return promise;
171 } 152 }
172 153
173 if (detectorType == DetectorType::Face) { 154 return doDetect(resolver, std::move(sharedBufferHandle), img->naturalWidth(),
174 if (!m_faceService) { 155 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 } 156 }
204 157
205 ScriptPromise ShapeDetector::detectShapesOnImageBitmap( 158 ScriptPromise ShapeDetector::detectShapesOnImageBitmap(
206 DetectorType detectorType,
207 ScriptPromiseResolver* resolver, 159 ScriptPromiseResolver* resolver,
208 ImageBitmap* imageBitmap) { 160 ImageBitmap* imageBitmap) {
209 ScriptPromise promise = resolver->promise(); 161 ScriptPromise promise = resolver->promise();
210 if (!imageBitmap->originClean()) { 162 if (!imageBitmap->originClean()) {
211 resolver->reject( 163 resolver->reject(
212 DOMException::create(SecurityError, "ImageBitmap is not origin clean")); 164 DOMException::create(SecurityError, "ImageBitmap is not origin clean"));
213 return promise; 165 return promise;
214 } 166 }
215 167
216 if (imageBitmap->size().area() == 0) { 168 if (imageBitmap->size().area() == 0) {
(...skipping 13 matching lines...) Expand all
230 allocationSize = pixmap.getSafeSize(); 182 allocationSize = pixmap.getSafeSize();
231 } else { 183 } else {
232 pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied() 184 pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied()
233 ? PremultiplyAlpha 185 ? PremultiplyAlpha
234 : DontPremultiplyAlpha, 186 : DontPremultiplyAlpha,
235 N32ColorType); 187 N32ColorType);
236 pixelDataPtr = pixelData->data(); 188 pixelDataPtr = pixelData->data();
237 allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */; 189 allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */;
238 } 190 }
239 191
240 return detectShapesOnData(detectorType, resolver, pixelDataPtr, 192 int size = allocationSize.ValueOrDefault(0);
241 allocationSize.ValueOrDefault(0), 193 mojo::ScopedSharedBufferHandle sharedBufferHandle =
242 imageBitmap->width(), imageBitmap->height()); 194 mojo::SharedBufferHandle::Create(size);
195 if (!sharedBufferHandle->is_valid()) {
196 resolver->reject(
197 DOMException::create(InvalidStateError, "Internal allocation error"));
198 return promise;
199 }
200
201 const mojo::ScopedSharedBufferMapping mappedBuffer =
202 sharedBufferHandle->Map(size);
203 DCHECK(mappedBuffer.get());
204 memcpy(mappedBuffer.get(), pixelDataPtr, size);
205
206 return doDetect(resolver, std::move(sharedBufferHandle), imageBitmap->width(),
207 imageBitmap->height());
243 } 208 }
244 209
245 ScriptPromise ShapeDetector::detectShapesOnVideoElement( 210 ScriptPromise ShapeDetector::detectShapesOnVideoElement(
246 DetectorType detectorType,
247 ScriptPromiseResolver* resolver, 211 ScriptPromiseResolver* resolver,
248 const HTMLVideoElement* video) { 212 const HTMLVideoElement* video) {
249 ScriptPromise promise = resolver->promise(); 213 ScriptPromise promise = resolver->promise();
250
251 // TODO(mcasas): Check if |video| is actually playing a MediaStream by using 214 // TODO(mcasas): Check if |video| is actually playing a MediaStream by using
252 // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if 215 // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if
253 // there is a local WebCam associated, there might be sophisticated ways to 216 // 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. 217 // detect faces on it. Until then, treat as a normal <video> element.
255 218
256 // !hasAvailableVideoFrame() is a bundle of invalid states. 219 // !hasAvailableVideoFrame() is a bundle of invalid states.
257 if (!video->hasAvailableVideoFrame()) { 220 if (!video->hasAvailableVideoFrame()) {
258 resolver->reject(DOMException::create( 221 resolver->reject(DOMException::create(
259 InvalidStateError, "Invalid HTMLVideoElement or state.")); 222 InvalidStateError, "Invalid HTMLVideoElement or state."));
260 return promise; 223 return promise;
(...skipping 17 matching lines...) Expand all
278 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr()); 241 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr());
279 allocationSize = pixmap.getSafeSize(); 242 allocationSize = pixmap.getSafeSize();
280 } else { 243 } else {
281 // TODO(mcasas): retrieve the pixels from elsewhere. 244 // TODO(mcasas): retrieve the pixels from elsewhere.
282 NOTREACHED(); 245 NOTREACHED();
283 resolver->reject(DOMException::create( 246 resolver->reject(DOMException::create(
284 InvalidStateError, "Failed to get pixels for current frame.")); 247 InvalidStateError, "Failed to get pixels for current frame."));
285 return promise; 248 return promise;
286 } 249 }
287 250
288 return detectShapesOnData(detectorType, resolver, pixelDataPtr, 251 int size = allocationSize.ValueOrDefault(0);
289 allocationSize.ValueOrDefault(0), image->width(),
290 image->height());
291 }
292
293 ScriptPromise ShapeDetector::detectShapesOnData(DetectorType detectorType,
294 ScriptPromiseResolver* resolver,
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 = 252 mojo::ScopedSharedBufferHandle sharedBufferHandle =
304 mojo::SharedBufferHandle::Create(size); 253 mojo::SharedBufferHandle::Create(size);
305 if (!sharedBufferHandle->is_valid()) { 254 if (!sharedBufferHandle->is_valid()) {
306 resolver->reject( 255 resolver->reject(
307 DOMException::create(InvalidStateError, "Internal allocation error")); 256 DOMException::create(InvalidStateError, "Internal allocation error"));
308 return promise; 257 return promise;
309 } 258 }
310 259
311 const mojo::ScopedSharedBufferMapping mappedBuffer = 260 const mojo::ScopedSharedBufferMapping mappedBuffer =
312 sharedBufferHandle->Map(size); 261 sharedBufferHandle->Map(size);
313 DCHECK(mappedBuffer.get()); 262 DCHECK(mappedBuffer.get());
263 memcpy(mappedBuffer.get(), pixelDataPtr, size);
314 264
315 memcpy(mappedBuffer.get(), data, size); 265 return doDetect(resolver, std::move(sharedBufferHandle), image->width(),
316 266 image->height());
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 } 267 }
404 268
405 } // namespace blink 269 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698