pepper_view.cc revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "remoting/client/plugin/pepper_view.h"
6
7#include <functional>
8
9#include "base/message_loop/message_loop.h"
10#include "base/strings/string_util.h"
11#include "base/synchronization/waitable_event.h"
12#include "base/time/time.h"
13#include "ppapi/cpp/completion_callback.h"
14#include "ppapi/cpp/image_data.h"
15#include "ppapi/cpp/point.h"
16#include "ppapi/cpp/rect.h"
17#include "ppapi/cpp/size.h"
18#include "remoting/base/util.h"
19#include "remoting/client/chromoting_stats.h"
20#include "remoting/client/client_context.h"
21#include "remoting/client/frame_producer.h"
22#include "remoting/client/plugin/chromoting_instance.h"
23#include "third_party/webrtc/modules/desktop_capture/desktop_frame.h"
24
25using base::Passed;
26
27namespace {
28
29// DesktopFrame that wraps a supplied pp::ImageData
30class PepperDesktopFrame : public webrtc::DesktopFrame {
31 public:
32  // Wraps the supplied ImageData.
33  explicit PepperDesktopFrame(const pp::ImageData& buffer);
34
35  // Access to underlying pepper representation.
36  const pp::ImageData& buffer() const {
37    return buffer_;
38  }
39
40 private:
41  pp::ImageData buffer_;
42};
43
44PepperDesktopFrame::PepperDesktopFrame(const pp::ImageData& buffer)
45  : DesktopFrame(webrtc::DesktopSize(buffer.size().width(),
46                                     buffer.size().height()),
47                 buffer.stride(),
48                 reinterpret_cast<uint8_t*>(buffer.data()),
49                 NULL),
50    buffer_(buffer) {}
51
52}  // namespace
53
54namespace remoting {
55
56namespace {
57
58// The maximum number of image buffers to be allocated at any point of time.
59const size_t kMaxPendingBuffersCount = 2;
60
61}  // namespace
62
63PepperView::PepperView(ChromotingInstance* instance,
64                       ClientContext* context)
65  : instance_(instance),
66    context_(context),
67    producer_(NULL),
68    merge_buffer_(NULL),
69    dips_to_device_scale_(1.0f),
70    dips_to_view_scale_(1.0f),
71    flush_pending_(false),
72    is_initialized_(false),
73    frame_received_(false),
74    callback_factory_(this) {
75}
76
77PepperView::~PepperView() {
78  // The producer should now return any pending buffers. At this point, however,
79  // ReturnBuffer() tasks scheduled by the producer will not be delivered,
80  // so we free all the buffers once the producer's queue is empty.
81  base::WaitableEvent done_event(true, false);
82  producer_->RequestReturnBuffers(
83      base::Bind(&base::WaitableEvent::Signal, base::Unretained(&done_event)));
84  done_event.Wait();
85
86  merge_buffer_ = NULL;
87  while (!buffers_.empty()) {
88    FreeBuffer(buffers_.front());
89  }
90}
91
92void PepperView::Initialize(FrameProducer* producer) {
93  producer_ = producer;
94  webrtc::DesktopFrame* buffer = AllocateBuffer();
95  while (buffer) {
96    producer_->DrawBuffer(buffer);
97    buffer = AllocateBuffer();
98  }
99}
100
101void PepperView::SetView(const pp::View& view) {
102  bool view_changed = false;
103
104  pp::Rect pp_size = view.GetRect();
105  webrtc::DesktopSize new_dips_size(pp_size.width(), pp_size.height());
106  float new_dips_to_device_scale = view.GetDeviceScale();
107
108  if (!dips_size_.equals(new_dips_size) ||
109      dips_to_device_scale_ != new_dips_to_device_scale) {
110    view_changed = true;
111    dips_to_device_scale_ = new_dips_to_device_scale;
112    dips_size_ = new_dips_size;
113
114    // If |dips_to_device_scale_| is > 1.0 then the device is high-DPI, and
115    // there are actually |view_device_scale_| physical pixels for every one
116    // Density Independent Pixel (DIP).  If we specify a scale of 1.0 to
117    // Graphics2D then we can render at DIP resolution and let PPAPI up-scale
118    // for high-DPI devices.
119    dips_to_view_scale_ = 1.0f;
120    view_size_ = dips_size_;
121
122    // If the view's DIP dimensions don't match the source then let the frame
123    // producer do the scaling, and render at device resolution.
124    if (!dips_size_.equals(source_size_)) {
125      dips_to_view_scale_ = dips_to_device_scale_;
126      view_size_.set(ceilf(dips_size_.width() * dips_to_view_scale_),
127                     ceilf(dips_size_.height() * dips_to_view_scale_));
128    }
129
130    // Create a 2D rendering context at the chosen frame dimensions.
131    pp::Size pp_size = pp::Size(view_size_.width(), view_size_.height());
132    graphics2d_ = pp::Graphics2D(instance_, pp_size, false);
133
134    // Specify the scale from our coordinates to DIPs.
135    graphics2d_.SetScale(1.0f / dips_to_view_scale_);
136
137    bool result = instance_->BindGraphics(graphics2d_);
138
139    // There is no good way to handle this error currently.
140    DCHECK(result) << "Couldn't bind the device context.";
141  }
142
143  pp::Rect pp_clip = view.GetClipRect();
144  webrtc::DesktopRect new_clip = webrtc::DesktopRect::MakeLTRB(
145      floorf(pp_clip.x() * dips_to_view_scale_),
146      floorf(pp_clip.y() * dips_to_view_scale_),
147      ceilf(pp_clip.right() * dips_to_view_scale_),
148      ceilf(pp_clip.bottom() * dips_to_view_scale_));
149  if (!clip_area_.equals(new_clip)) {
150    view_changed = true;
151
152    // YUV to RGB conversion may require even X and Y coordinates for
153    // the top left corner of the clipping area.
154    clip_area_ = AlignRect(new_clip);
155    clip_area_.IntersectWith(webrtc::DesktopRect::MakeSize(view_size_));
156  }
157
158  if (view_changed) {
159    producer_->SetOutputSizeAndClip(view_size_, clip_area_);
160    Initialize(producer_);
161  }
162}
163
164void PepperView::ApplyBuffer(const webrtc::DesktopSize& view_size,
165                             const webrtc::DesktopRect& clip_area,
166                             webrtc::DesktopFrame* buffer,
167                             const webrtc::DesktopRegion& region,
168                             const webrtc::DesktopRegion& shape) {
169  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
170
171  if (!frame_received_) {
172    instance_->OnFirstFrameReceived();
173    frame_received_ = true;
174  }
175  // We cannot use the data in the buffer if its dimensions don't match the
176  // current view size.
177  // TODO(alexeypa): We could rescale and draw it (or even draw it without
178  // rescaling) to reduce the perceived lag while we are waiting for
179  // the properly scaled data.
180  if (!view_size_.equals(view_size)) {
181    FreeBuffer(buffer);
182    Initialize(producer_);
183  } else {
184    FlushBuffer(clip_area, buffer, region);
185    instance_->SetDesktopShape(shape);
186  }
187}
188
189void PepperView::ReturnBuffer(webrtc::DesktopFrame* buffer) {
190  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
191
192  // Reuse the buffer if it is large enough, otherwise drop it on the floor
193  // and allocate a new one.
194  if (buffer->size().width() >= clip_area_.width() &&
195      buffer->size().height() >= clip_area_.height()) {
196    producer_->DrawBuffer(buffer);
197  } else {
198    FreeBuffer(buffer);
199    Initialize(producer_);
200  }
201}
202
203void PepperView::SetSourceSize(const webrtc::DesktopSize& source_size,
204                               const webrtc::DesktopVector& source_dpi) {
205  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
206
207  if (source_size_.equals(source_size) && source_dpi_.equals(source_dpi))
208    return;
209
210  source_size_ = source_size;
211  source_dpi_ = source_dpi;
212
213  // Notify JavaScript of the change in source size.
214  instance_->SetDesktopSize(source_size, source_dpi);
215}
216
217FrameConsumer::PixelFormat PepperView::GetPixelFormat() {
218  return FORMAT_BGRA;
219}
220
221webrtc::DesktopFrame* PepperView::AllocateBuffer() {
222  if (buffers_.size() >= kMaxPendingBuffersCount)
223    return NULL;
224
225  if (clip_area_.width()==0 || clip_area_.height()==0)
226    return NULL;
227
228  // Create an image buffer of the required size, but don't zero it.
229  pp::ImageData buffer_data(instance_,
230                    PP_IMAGEDATAFORMAT_BGRA_PREMUL,
231                    pp::Size(clip_area_.width(),
232                             clip_area_.height()),
233                    false);
234  if (buffer_data.is_null()) {
235    LOG(WARNING) << "Not enough memory for frame buffers.";
236    return NULL;
237  }
238
239  webrtc::DesktopFrame* buffer = new PepperDesktopFrame(buffer_data);
240  buffers_.push_back(buffer);
241  return buffer;
242}
243
244void PepperView::FreeBuffer(webrtc::DesktopFrame* buffer) {
245  DCHECK(std::find(buffers_.begin(), buffers_.end(), buffer) != buffers_.end());
246
247  buffers_.remove(buffer);
248  delete buffer;
249}
250
251void PepperView::FlushBuffer(const webrtc::DesktopRect& clip_area,
252                             webrtc::DesktopFrame* buffer,
253                             const webrtc::DesktopRegion& region) {
254  // Defer drawing if the flush is already in progress.
255  if (flush_pending_) {
256    // |merge_buffer_| is guaranteed to be free here because we allocate only
257    // two buffers simultaneously. If more buffers are allowed this code should
258    // apply all pending changes to the screen.
259    DCHECK(merge_buffer_ == NULL);
260
261    merge_clip_area_ = clip_area;
262    merge_buffer_ = buffer;
263    merge_region_ = region;
264    return;
265  }
266
267  // Notify Pepper API about the updated areas and flush pixels to the screen.
268  base::Time start_time = base::Time::Now();
269
270  for (webrtc::DesktopRegion::Iterator i(region); !i.IsAtEnd(); i.Advance()) {
271    webrtc::DesktopRect rect = i.rect();
272
273    // Re-clip |region| with the current clipping area |clip_area_| because
274    // the latter could change from the time the buffer was drawn.
275    rect.IntersectWith(clip_area_);
276    if (rect.is_empty())
277      continue;
278
279    // Specify the rectangle coordinates relative to the clipping area.
280    rect.Translate(-clip_area.left(), -clip_area.top());
281
282    // Pepper Graphics 2D has a strange and badly documented API that the
283    // point here is the offset from the source rect. Why?
284    graphics2d_.PaintImageData(
285        static_cast<PepperDesktopFrame*>(buffer)->buffer(),
286        pp::Point(clip_area.left(), clip_area.top()),
287        pp::Rect(rect.left(), rect.top(), rect.width(), rect.height()));
288  }
289
290  // Notify the producer that some parts of the region weren't painted because
291  // the clipping area has changed already.
292  if (!clip_area.equals(clip_area_)) {
293    webrtc::DesktopRegion not_painted = region;
294    not_painted.Subtract(clip_area_);
295    if (!not_painted.is_empty()) {
296      producer_->InvalidateRegion(not_painted);
297    }
298  }
299
300  // Flush the updated areas to the screen.
301  pp::CompletionCallback callback =
302      callback_factory_.NewCallback(&PepperView::OnFlushDone,
303                                    start_time,
304                                    buffer);
305  int error = graphics2d_.Flush(callback);
306  CHECK(error == PP_OK_COMPLETIONPENDING);
307  flush_pending_ = true;
308}
309
310void PepperView::OnFlushDone(int result,
311                             const base::Time& paint_start,
312                             webrtc::DesktopFrame* buffer) {
313  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
314  DCHECK(flush_pending_);
315
316  instance_->GetStats()->video_paint_ms()->Record(
317      (base::Time::Now() - paint_start).InMilliseconds());
318
319  flush_pending_ = false;
320  ReturnBuffer(buffer);
321
322  // If there is a buffer queued for rendering then render it now.
323  if (merge_buffer_ != NULL) {
324    buffer = merge_buffer_;
325    merge_buffer_ = NULL;
326    FlushBuffer(merge_clip_area_, buffer, merge_region_);
327  }
328}
329
330}  // namespace remoting
331