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

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

Issue 2557513003: ShapeDetection: Eliminate DetectorType enum in ShapeDetector.cpp (Closed)
Patch Set: Add utility function: getSharedBufferOnData() 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 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 if (imageSource.isHTMLImageElement()) {
77 // TODO(mcasas): Implement more CanvasImageSources, https://crbug.com/659138 61 return detectShapesOnImageElement(scriptState, resolver,
mcasas 2016/12/06 22:50:12 Hmm after removing toImageSourceInternal() you ha
Reilly Grant (use Gerrit) 2016/12/06 23:03:42 How about: CanvasImageSource* canvasImageSource;
mcasas 2016/12/06 23:10:05 That looks nice, works for me!
78 NOTIMPLEMENTED() << "Unsupported CanvasImageSource"; 62 imageSource.getAsHTMLImageElement());
79 resolver->reject( 63 } else if (imageSource.isImageBitmap() &&
80 DOMException::create(NotFoundError, "Unsupported source.")); 64 !static_cast<ImageBitmap*>(imageSource.getAsImageBitmap())
Reilly Grant (use Gerrit) 2016/12/06 22:58:38 getAsImageBitmap() already returns an ImageBitmap*
81 return promise; 65 ->isNeutered()) {
66 return detectShapesOnImageBitmap(scriptState, resolver,
67 imageSource.getAsImageBitmap());
68 } else if (imageSource.isHTMLVideoElement()) {
69 return detectShapesOnVideoElement(scriptState, resolver,
70 imageSource.getAsHTMLVideoElement());
82 } 71 }
83 72
84 if (imageSourceInternal->wouldTaintOrigin( 73 // TODO(mcasas): Implement more CanvasImageSources, https://crbug.com/659138
74 NOTIMPLEMENTED() << "Unsupported CanvasImageSource";
75 resolver->reject(DOMException::create(NotFoundError, "Unsupported source."));
76 return promise;
77 }
78
79 ScriptPromise ShapeDetector::detectShapesOnImageElement(
80 ScriptState* scriptState,
81 ScriptPromiseResolver* resolver,
82 const HTMLImageElement* img) {
83 ScriptPromise promise = resolver->promise();
84
85 if (img->wouldTaintOrigin(
85 scriptState->getExecutionContext()->getSecurityOrigin())) { 86 scriptState->getExecutionContext()->getSecurityOrigin())) {
86 resolver->reject( 87 resolver->reject(
87 DOMException::create(SecurityError, "Source would taint origin.")); 88 DOMException::create(SecurityError, "Source would taint origin."));
88 return promise; 89 return promise;
89 } 90 }
90 91
91 if (imageSource.isHTMLImageElement()) {
92 return detectShapesOnImageElement(
93 detectorType, resolver,
94 static_cast<HTMLImageElement*>(imageSourceInternal));
95 }
96 if (imageSourceInternal->isImageBitmap()) {
97 return detectShapesOnImageBitmap(
98 detectorType, resolver, static_cast<ImageBitmap*>(imageSourceInternal));
99 }
100 if (imageSourceInternal->isVideoElement()) {
101 return detectShapesOnVideoElement(
102 detectorType, resolver,
103 static_cast<HTMLVideoElement*>(imageSourceInternal));
104 }
105
106 NOTREACHED();
107 return promise;
108 }
109
110 ScriptPromise ShapeDetector::detectShapesOnImageElement(
111 DetectorType detectorType,
112 ScriptPromiseResolver* resolver,
113 const HTMLImageElement* img) {
114 ScriptPromise promise = resolver->promise();
115 if (img->bitmapSourceSize().isZero()) { 92 if (img->bitmapSourceSize().isZero()) {
116 resolver->resolve(HeapVector<Member<DOMRect>>()); 93 resolver->resolve(HeapVector<Member<DOMRect>>());
117 return promise; 94 return promise;
118 } 95 }
119 96
120 ImageResource* const imageResource = img->cachedImage(); 97 ImageResource* const imageResource = img->cachedImage();
121 if (!imageResource || imageResource->errorOccurred()) { 98 if (!imageResource || imageResource->errorOccurred()) {
122 resolver->reject(DOMException::create( 99 resolver->reject(DOMException::create(
123 InvalidStateError, "Failed to load or decode HTMLImageElement.")); 100 InvalidStateError, "Failed to load or decode HTMLImageElement."));
124 return promise; 101 return promise;
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
163 sharedBufferHandle->Map(allocationSize); 140 sharedBufferHandle->Map(allocationSize);
164 141
165 const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes()); 142 const SkPixmap pixmap(skiaInfo, mappedBuffer.get(), skiaInfo.minRowBytes());
166 if (!image->readPixels(pixmap, 0, 0)) { 143 if (!image->readPixels(pixmap, 0, 0)) {
167 resolver->reject(DOMException::create( 144 resolver->reject(DOMException::create(
168 InvalidStateError, 145 InvalidStateError,
169 "Failed to read pixels: Unable to decompress or unsupported format.")); 146 "Failed to read pixels: Unable to decompress or unsupported format."));
170 return promise; 147 return promise;
171 } 148 }
172 149
173 if (detectorType == DetectorType::Face) { 150 return doDetect(resolver, std::move(sharedBufferHandle), img->naturalWidth(),
174 if (!m_faceService) { 151 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 } 152 }
204 153
205 ScriptPromise ShapeDetector::detectShapesOnImageBitmap( 154 ScriptPromise ShapeDetector::detectShapesOnImageBitmap(
206 DetectorType detectorType, 155 ScriptState* scriptState,
207 ScriptPromiseResolver* resolver, 156 ScriptPromiseResolver* resolver,
208 ImageBitmap* imageBitmap) { 157 ImageBitmap* imageBitmap) {
209 ScriptPromise promise = resolver->promise(); 158 ScriptPromise promise = resolver->promise();
210 if (!imageBitmap->originClean()) { 159
160 if (imageBitmap->wouldTaintOrigin(
161 scriptState->getExecutionContext()->getSecurityOrigin())) {
211 resolver->reject( 162 resolver->reject(
212 DOMException::create(SecurityError, "ImageBitmap is not origin clean")); 163 DOMException::create(SecurityError, "Source would taint origin."));
213 return promise; 164 return promise;
214 } 165 }
215 166
216 if (imageBitmap->size().area() == 0) { 167 if (imageBitmap->size().area() == 0) {
217 resolver->resolve(HeapVector<Member<DOMRect>>()); 168 resolver->resolve(HeapVector<Member<DOMRect>>());
218 return promise; 169 return promise;
219 } 170 }
220 171
221 SkPixmap pixmap; 172 SkPixmap pixmap;
222 RefPtr<Uint8Array> pixelData; 173 RefPtr<Uint8Array> pixelData;
223 uint8_t* pixelDataPtr = nullptr; 174 uint8_t* pixelDataPtr = nullptr;
224 WTF::CheckedNumeric<int> allocationSize = 0; 175 WTF::CheckedNumeric<int> allocationSize = 0;
225 // Use |skImage|'s pixels if it has direct access to them, otherwise retrieve 176 // Use |skImage|'s pixels if it has direct access to them, otherwise retrieve
226 // them from elsewhere via copyBitmapData(). 177 // them from elsewhere via copyBitmapData().
227 sk_sp<SkImage> skImage = imageBitmap->bitmapImage()->imageForCurrentFrame(); 178 sk_sp<SkImage> skImage = imageBitmap->bitmapImage()->imageForCurrentFrame();
228 if (skImage->peekPixels(&pixmap)) { 179 if (skImage->peekPixels(&pixmap)) {
229 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr()); 180 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr());
230 allocationSize = pixmap.getSafeSize(); 181 allocationSize = pixmap.getSafeSize();
231 } else { 182 } else {
232 pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied() 183 pixelData = imageBitmap->copyBitmapData(imageBitmap->isPremultiplied()
233 ? PremultiplyAlpha 184 ? PremultiplyAlpha
234 : DontPremultiplyAlpha, 185 : DontPremultiplyAlpha,
235 N32ColorType); 186 N32ColorType);
236 pixelDataPtr = pixelData->data(); 187 pixelDataPtr = pixelData->data();
237 allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */; 188 allocationSize = imageBitmap->size().area() * 4 /* bytes per pixel */;
238 } 189 }
239 190
240 return detectShapesOnData(detectorType, resolver, pixelDataPtr, 191 mojo::ScopedSharedBufferHandle sharedBufferHandle = getSharedBufferOnData(
241 allocationSize.ValueOrDefault(0), 192 resolver, pixelDataPtr, allocationSize.ValueOrDefault(0));
242 imageBitmap->width(), imageBitmap->height()); 193 if (!sharedBufferHandle->is_valid())
194 return promise;
195
196 return doDetect(resolver, std::move(sharedBufferHandle), imageBitmap->width(),
197 imageBitmap->height());
243 } 198 }
244 199
245 ScriptPromise ShapeDetector::detectShapesOnVideoElement( 200 ScriptPromise ShapeDetector::detectShapesOnVideoElement(
246 DetectorType detectorType, 201 ScriptState* scriptState,
247 ScriptPromiseResolver* resolver, 202 ScriptPromiseResolver* resolver,
248 const HTMLVideoElement* video) { 203 const HTMLVideoElement* video) {
249 ScriptPromise promise = resolver->promise(); 204 ScriptPromise promise = resolver->promise();
250 205
206 if (video->wouldTaintOrigin(
207 scriptState->getExecutionContext()->getSecurityOrigin())) {
208 resolver->reject(
209 DOMException::create(SecurityError, "Source would taint origin."));
210 return promise;
211 }
251 // TODO(mcasas): Check if |video| is actually playing a MediaStream by using 212 // TODO(mcasas): Check if |video| is actually playing a MediaStream by using
252 // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if 213 // HTMLMediaElement::isMediaStreamURL(video->currentSrc().getString()); if
253 // there is a local WebCam associated, there might be sophisticated ways to 214 // 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. 215 // detect faces on it. Until then, treat as a normal <video> element.
255 216
256 // !hasAvailableVideoFrame() is a bundle of invalid states. 217 // !hasAvailableVideoFrame() is a bundle of invalid states.
257 if (!video->hasAvailableVideoFrame()) { 218 if (!video->hasAvailableVideoFrame()) {
258 resolver->reject(DOMException::create( 219 resolver->reject(DOMException::create(
259 InvalidStateError, "Invalid HTMLVideoElement or state.")); 220 InvalidStateError, "Invalid HTMLVideoElement or state."));
260 return promise; 221 return promise;
(...skipping 17 matching lines...) Expand all
278 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr()); 239 pixelDataPtr = static_cast<uint8_t*>(pixmap.writable_addr());
279 allocationSize = pixmap.getSafeSize(); 240 allocationSize = pixmap.getSafeSize();
280 } else { 241 } else {
281 // TODO(mcasas): retrieve the pixels from elsewhere. 242 // TODO(mcasas): retrieve the pixels from elsewhere.
282 NOTREACHED(); 243 NOTREACHED();
283 resolver->reject(DOMException::create( 244 resolver->reject(DOMException::create(
284 InvalidStateError, "Failed to get pixels for current frame.")); 245 InvalidStateError, "Failed to get pixels for current frame."));
285 return promise; 246 return promise;
286 } 247 }
287 248
288 return detectShapesOnData(detectorType, resolver, pixelDataPtr, 249 mojo::ScopedSharedBufferHandle sharedBufferHandle = getSharedBufferOnData(
289 allocationSize.ValueOrDefault(0), image->width(), 250 resolver, pixelDataPtr, allocationSize.ValueOrDefault(0));
290 image->height()); 251 if (!sharedBufferHandle->is_valid())
291 } 252 return promise;
292 253
293 ScriptPromise ShapeDetector::detectShapesOnData(DetectorType detectorType, 254 return doDetect(resolver, std::move(sharedBufferHandle), image->width(),
294 ScriptPromiseResolver* resolver, 255 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 } 256 }
404 257
405 } // namespace blink 258 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698