1/*
2 *  Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 *  Use of this source code is governed by a BSD-style license
5 *  that can be found in the LICENSE file in the root of the source
6 *  tree. An additional intellectual property rights grant can be found
7 *  in the file PATENTS.  All contributing project authors may
8 *  be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "modules/desktop_capture/mac/desktop_frame_iosurface.h"
12
13#include "rtc_base/checks.h"
14#include "rtc_base/logging.h"
15
16namespace webrtc {
17
18// static
19std::unique_ptr<DesktopFrameIOSurface> DesktopFrameIOSurface::Wrap(
20    rtc::ScopedCFTypeRef<IOSurfaceRef> io_surface) {
21  if (!io_surface) {
22    return nullptr;
23  }
24
25  IOSurfaceIncrementUseCount(io_surface.get());
26  IOReturn status = IOSurfaceLock(io_surface.get(), kIOSurfaceLockReadOnly, nullptr);
27  if (status != kIOReturnSuccess) {
28    RTC_LOG(LS_ERROR) << "Failed to lock the IOSurface with status " << status;
29    IOSurfaceDecrementUseCount(io_surface.get());
30    return nullptr;
31  }
32
33  // Verify that the image has 32-bit depth.
34  int bytes_per_pixel = IOSurfaceGetBytesPerElement(io_surface.get());
35  if (bytes_per_pixel != DesktopFrame::kBytesPerPixel) {
36    RTC_LOG(LS_ERROR) << "CGDisplayStream handler returned IOSurface with " << (8 * bytes_per_pixel)
37                      << " bits per pixel. Only 32-bit depth is supported.";
38    IOSurfaceUnlock(io_surface.get(), kIOSurfaceLockReadOnly, nullptr);
39    IOSurfaceDecrementUseCount(io_surface.get());
40    return nullptr;
41  }
42
43  return std::unique_ptr<DesktopFrameIOSurface>(new DesktopFrameIOSurface(io_surface));
44}
45
46DesktopFrameIOSurface::DesktopFrameIOSurface(rtc::ScopedCFTypeRef<IOSurfaceRef> io_surface)
47    : DesktopFrame(
48          DesktopSize(IOSurfaceGetWidth(io_surface.get()), IOSurfaceGetHeight(io_surface.get())),
49          IOSurfaceGetBytesPerRow(io_surface.get()),
50          static_cast<uint8_t*>(IOSurfaceGetBaseAddress(io_surface.get())),
51          nullptr),
52      io_surface_(io_surface) {
53  RTC_DCHECK(io_surface_);
54}
55
56DesktopFrameIOSurface::~DesktopFrameIOSurface() {
57  IOSurfaceUnlock(io_surface_.get(), kIOSurfaceLockReadOnly, nullptr);
58  IOSurfaceDecrementUseCount(io_surface_.get());
59}
60
61}  // namespace webrtc
62