pepper_view.cc revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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                       FrameProducer* producer)
66  : instance_(instance),
67    context_(context),
68    producer_(producer),
69    merge_buffer_(NULL),
70    dips_to_device_scale_(1.0f),
71    dips_to_view_scale_(1.0f),
72    flush_pending_(false),
73    is_initialized_(false),
74    frame_received_(false),
75    callback_factory_(this) {
76  InitiateDrawing();
77}
78
79PepperView::~PepperView() {
80  // The producer should now return any pending buffers. At this point, however,
81  // ReturnBuffer() tasks scheduled by the producer will not be delivered,
82  // so we free all the buffers once the producer's queue is empty.
83  base::WaitableEvent done_event(true, false);
84  producer_->RequestReturnBuffers(
85      base::Bind(&base::WaitableEvent::Signal, base::Unretained(&done_event)));
86  done_event.Wait();
87
88  merge_buffer_ = NULL;
89  while (!buffers_.empty()) {
90    FreeBuffer(buffers_.front());
91  }
92}
93
94void PepperView::SetView(const pp::View& view) {
95  bool view_changed = false;
96
97  pp::Rect pp_size = view.GetRect();
98  webrtc::DesktopSize new_dips_size(pp_size.width(), pp_size.height());
99  float new_dips_to_device_scale = view.GetDeviceScale();
100
101  if (!dips_size_.equals(new_dips_size) ||
102      dips_to_device_scale_ != new_dips_to_device_scale) {
103    view_changed = true;
104    dips_to_device_scale_ = new_dips_to_device_scale;
105    dips_size_ = new_dips_size;
106
107    // If |dips_to_device_scale_| is > 1.0 then the device is high-DPI, and
108    // there are actually |view_device_scale_| physical pixels for every one
109    // Density Independent Pixel (DIP).  If we specify a scale of 1.0 to
110    // Graphics2D then we can render at DIP resolution and let PPAPI up-scale
111    // for high-DPI devices.
112    dips_to_view_scale_ = 1.0f;
113    view_size_ = dips_size_;
114
115    // If the view's DIP dimensions don't match the source then let the frame
116    // producer do the scaling, and render at device resolution.
117    if (!dips_size_.equals(source_size_)) {
118      dips_to_view_scale_ = dips_to_device_scale_;
119      view_size_.set(ceilf(dips_size_.width() * dips_to_view_scale_),
120                     ceilf(dips_size_.height() * dips_to_view_scale_));
121    }
122
123    // Create a 2D rendering context at the chosen frame dimensions.
124    pp::Size pp_size = pp::Size(view_size_.width(), view_size_.height());
125    graphics2d_ = pp::Graphics2D(instance_, pp_size, false);
126
127    // Specify the scale from our coordinates to DIPs.
128    graphics2d_.SetScale(1.0f / dips_to_view_scale_);
129
130    bool result = instance_->BindGraphics(graphics2d_);
131
132    // There is no good way to handle this error currently.
133    DCHECK(result) << "Couldn't bind the device context.";
134  }
135
136  pp::Rect pp_clip = view.GetClipRect();
137  webrtc::DesktopRect new_clip = webrtc::DesktopRect::MakeLTRB(
138      floorf(pp_clip.x() * dips_to_view_scale_),
139      floorf(pp_clip.y() * dips_to_view_scale_),
140      ceilf(pp_clip.right() * dips_to_view_scale_),
141      ceilf(pp_clip.bottom() * dips_to_view_scale_));
142  if (!clip_area_.equals(new_clip)) {
143    view_changed = true;
144
145    // YUV to RGB conversion may require even X and Y coordinates for
146    // the top left corner of the clipping area.
147    clip_area_ = AlignRect(new_clip);
148    clip_area_.IntersectWith(webrtc::DesktopRect::MakeSize(view_size_));
149  }
150
151  if (view_changed) {
152    producer_->SetOutputSizeAndClip(view_size_, clip_area_);
153    InitiateDrawing();
154  }
155}
156
157void PepperView::ApplyBuffer(const webrtc::DesktopSize& view_size,
158                             const webrtc::DesktopRect& clip_area,
159                             webrtc::DesktopFrame* buffer,
160                             const webrtc::DesktopRegion& region) {
161  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
162
163  if (!frame_received_) {
164    instance_->OnFirstFrameReceived();
165    frame_received_ = true;
166  }
167  // We cannot use the data in the buffer if its dimensions don't match the
168  // current view size.
169  // TODO(alexeypa): We could rescale and draw it (or even draw it without
170  // rescaling) to reduce the perceived lag while we are waiting for
171  // the properly scaled data.
172  if (!view_size_.equals(view_size)) {
173    FreeBuffer(buffer);
174    InitiateDrawing();
175  } else {
176    FlushBuffer(clip_area, buffer, region);
177  }
178}
179
180void PepperView::ReturnBuffer(webrtc::DesktopFrame* buffer) {
181  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
182
183  // Reuse the buffer if it is large enough, otherwise drop it on the floor
184  // and allocate a new one.
185  if (buffer->size().width() >= clip_area_.width() &&
186      buffer->size().height() >= clip_area_.height()) {
187    producer_->DrawBuffer(buffer);
188  } else {
189    FreeBuffer(buffer);
190    InitiateDrawing();
191  }
192}
193
194void PepperView::SetSourceSize(const webrtc::DesktopSize& source_size,
195                               const webrtc::DesktopVector& source_dpi) {
196  DCHECK(context_->main_task_runner()->BelongsToCurrentThread());
197
198  if (source_size_.equals(source_size) && source_dpi_.equals(source_dpi))
199    return;
200
201  source_size_ = source_size;
202  source_dpi_ = source_dpi;
203
204  // Notify JavaScript of the change in source size.
205  instance_->SetDesktopSize(source_size, source_dpi);
206}
207
208webrtc::DesktopFrame* PepperView::AllocateBuffer() {
209  if (buffers_.size() >= kMaxPendingBuffersCount)
210    return NULL;
211
212  if (clip_area_.width()==0 || clip_area_.height()==0)
213    return NULL;
214
215  // Create an image buffer of the required size, but don't zero it.
216  pp::ImageData buffer_data(instance_,
217                    PP_IMAGEDATAFORMAT_BGRA_PREMUL,
218                    pp::Size(clip_area_.width(),
219                             clip_area_.height()),
220                    false);
221  if (buffer_data.is_null()) {
222    LOG(WARNING) << "Not enough memory for frame buffers.";
223    return NULL;
224  }
225
226  webrtc::DesktopFrame* buffer = new PepperDesktopFrame(buffer_data);
227  buffers_.push_back(buffer);
228  return buffer;
229}
230
231void PepperView::FreeBuffer(webrtc::DesktopFrame* buffer) {
232  DCHECK(std::find(buffers_.begin(), buffers_.end(), buffer) != buffers_.end());
233
234  buffers_.remove(buffer);
235  delete buffer;
236}
237
238void PepperView::InitiateDrawing() {
239  webrtc::DesktopFrame* buffer = AllocateBuffer();
240  while (buffer) {
241    producer_->DrawBuffer(buffer);
242    buffer = AllocateBuffer();
243  }
244}
245
246void PepperView::FlushBuffer(const webrtc::DesktopRect& clip_area,
247                             webrtc::DesktopFrame* buffer,
248                             const webrtc::DesktopRegion& region) {
249  // Defer drawing if the flush is already in progress.
250  if (flush_pending_) {
251    // |merge_buffer_| is guaranteed to be free here because we allocate only
252    // two buffers simultaneously. If more buffers are allowed this code should
253    // apply all pending changes to the screen.
254    DCHECK(merge_buffer_ == NULL);
255
256    merge_clip_area_ = clip_area;
257    merge_buffer_ = buffer;
258    merge_region_ = region;
259    return;
260  }
261
262  // Notify Pepper API about the updated areas and flush pixels to the screen.
263  base::Time start_time = base::Time::Now();
264
265  for (webrtc::DesktopRegion::Iterator i(region); !i.IsAtEnd(); i.Advance()) {
266    webrtc::DesktopRect rect = i.rect();
267
268    // Re-clip |region| with the current clipping area |clip_area_| because
269    // the latter could change from the time the buffer was drawn.
270    rect.IntersectWith(clip_area_);
271    if (rect.is_empty())
272      continue;
273
274    // Specify the rectangle coordinates relative to the clipping area.
275    rect.Translate(-clip_area.left(), -clip_area.top());
276
277    // Pepper Graphics 2D has a strange and badly documented API that the
278    // point here is the offset from the source rect. Why?
279    graphics2d_.PaintImageData(
280        static_cast<PepperDesktopFrame*>(buffer)->buffer(),
281        pp::Point(clip_area.left(), clip_area.top()),
282        pp::Rect(rect.left(), rect.top(), rect.width(), rect.height()));
283  }
284
285  // Notify the producer that some parts of the region weren't painted because
286  // the clipping area has changed already.
287  if (!clip_area.equals(clip_area_)) {
288    webrtc::DesktopRegion not_painted = region;
289    not_painted.Subtract(clip_area_);
290    if (!not_painted.is_empty()) {
291      producer_->InvalidateRegion(not_painted);
292    }
293  }
294
295  // Flush the updated areas to the screen.
296  pp::CompletionCallback callback =
297      callback_factory_.NewCallback(&PepperView::OnFlushDone,
298                                    start_time,
299                                    buffer);
300  int error = graphics2d_.Flush(callback);
301  CHECK(error == PP_OK_COMPLETIONPENDING);
302  flush_pending_ = true;
303
304  // If the buffer we just rendered has a shape then pass that to JavaScript.
305  const webrtc::DesktopRegion* buffer_shape = producer_->GetBufferShape();
306  if (buffer_shape)
307    instance_->SetDesktopShape(*buffer_shape);
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