summaryrefslogtreecommitdiffstats
path: root/remoting/client/plugin/pepper_view.cc
blob: d8a776c8b31f26d08462bb48d3375f5507527c94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/client/plugin/pepper_view.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/point.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/size.h"
#include "remoting/base/util.h"
#include "remoting/client/chromoting_stats.h"
#include "remoting/client/client_context.h"
#include "remoting/client/plugin/chromoting_instance.h"
#include "remoting/client/plugin/pepper_util.h"

namespace remoting {

namespace {

ChromotingScriptableObject::ConnectionError ConvertConnectionError(
    protocol::ConnectionToHost::Error error) {
  switch (error) {
    case protocol::ConnectionToHost::OK:
      return ChromotingScriptableObject::ERROR_NONE;
    case protocol::ConnectionToHost::HOST_IS_OFFLINE:
      return ChromotingScriptableObject::ERROR_HOST_IS_OFFLINE;
    case protocol::ConnectionToHost::SESSION_REJECTED:
      return ChromotingScriptableObject::ERROR_SESSION_REJECTED;
    case protocol::ConnectionToHost::INCOMPATIBLE_PROTOCOL:
      return ChromotingScriptableObject::ERROR_INCOMPATIBLE_PROTOCOL;
    case protocol::ConnectionToHost::NETWORK_FAILURE:
      return ChromotingScriptableObject::ERROR_NETWORK_FAILURE;
  }
  DLOG(FATAL) << "Unknown error code" << error;
  return  ChromotingScriptableObject::ERROR_NONE;
}

}  // namespace

PepperView::PepperView(ChromotingInstance* instance, ClientContext* context)
  : instance_(instance),
    context_(context),
    flush_blocked_(false),
    is_static_fill_(false),
    static_fill_color_(0),
    ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}

PepperView::~PepperView() {
}

bool PepperView::Initialize() {
  return true;
}

void PepperView::TearDown() {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  weak_factory_.InvalidateWeakPtrs();
}

void PepperView::Paint() {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  if (is_static_fill_) {
    VLOG(1) << "Static filling " << static_fill_color_;
    pp::ImageData image(instance_, pp::ImageData::GetNativeImageDataFormat(),
                        pp::Size(graphics2d_.size().width(),
                                 graphics2d_.size().height()),
                        false);
    if (image.is_null()) {
      LOG(ERROR) << "Unable to allocate image of size: "
                 << graphics2d_.size().width() << " x "
                 << graphics2d_.size().height();
      return;
    }

    for (int y = 0; y < image.size().height(); y++) {
      for (int x = 0; x < image.size().width(); x++) {
        *image.GetAddr32(pp::Point(x, y)) = static_fill_color_;
      }
    }

    // For ReplaceContents, make sure the image size matches the device context
    // size!  Otherwise, this will just silently do nothing.
    graphics2d_.ReplaceContents(&image);
    FlushGraphics(base::Time::Now());
  } else {
    // TODO(ajwong): We need to keep a backing store image of the host screen
    // that has the data here which can be redrawn.
    return;
  }
}

void PepperView::SetHostSize(const SkISize& host_size) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  if (host_size_ == host_size)
    return;

  host_size_ = host_size;

  // Submit an update of desktop size to Javascript.
  instance_->GetScriptableObject()->SetDesktopSize(
      host_size.width(), host_size.height());
}

void PepperView::PaintFrame(media::VideoFrame* frame, RectVector* rects) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  SetHostSize(SkISize::Make(frame->width(), frame->height()));

  if (!backing_store_.get() || backing_store_->is_null()) {
    LOG(ERROR) << "Backing store is not available.";
    return;
  }

  base::Time start_time = base::Time::Now();

  // Copy updated regions to the backing store and then paint the regions.
  bool changes_made = false;
  for (size_t i = 0; i < rects->size(); ++i)
    changes_made |= PaintRect(frame, (*rects)[i]);

  if (changes_made)
    FlushGraphics(start_time);
}

bool PepperView::PaintRect(media::VideoFrame* frame, const SkIRect& r) {
  const uint8* frame_data = frame->data(media::VideoFrame::kRGBPlane);
  const int kFrameStride = frame->stride(media::VideoFrame::kRGBPlane);
  const int kBytesPerPixel = GetBytesPerPixel(media::VideoFrame::RGB32);

  pp::Size backing_store_size = backing_store_->size();
  SkIRect rect(r);
  if (!rect.intersect(SkIRect::MakeWH(backing_store_size.width(),
                                      backing_store_size.height()))) {
    return false;
  }

  const uint8* in =
      frame_data +
      kFrameStride * rect.fTop +   // Y offset.
      kBytesPerPixel * rect.fLeft;  // X offset.
  uint8* out =
      reinterpret_cast<uint8*>(backing_store_->data()) +
      backing_store_->stride() * rect.fTop +  // Y offset.
      kBytesPerPixel * rect.fLeft;  // X offset.

  // TODO(hclam): We really should eliminate this memory copy.
  for (int j = 0; j < rect.height(); ++j) {
    memcpy(out, in, rect.width() * kBytesPerPixel);
    in += kFrameStride;
    out += backing_store_->stride();
  }

  // Pepper Graphics 2D has a strange and badly documented API that the
  // point here is the offset from the source rect. Why?
  graphics2d_.PaintImageData(
      *backing_store_.get(),
      pp::Point(0, 0),
      pp::Rect(rect.fLeft, rect.fTop, rect.width(), rect.height()));
  return true;
}

void PepperView::BlankRect(pp::ImageData& image_data, const pp::Rect& rect) {
  const int kBytesPerPixel = GetBytesPerPixel(media::VideoFrame::RGB32);
  for (int y = rect.y(); y < rect.bottom(); y++) {
    uint8* to = reinterpret_cast<uint8*>(image_data.data()) +
        (y * image_data.stride()) + (rect.x() * kBytesPerPixel);
    memset(to, 0xff, rect.width() * kBytesPerPixel);
  }
}

void PepperView::FlushGraphics(base::Time paint_start) {
  scoped_ptr<base::Closure> task(
      new base::Closure(
          base::Bind(&PepperView::OnPaintDone, weak_factory_.GetWeakPtr(),
                     paint_start)));

  // Flag needs to be set here in order to get a proper error code for Flush().
  // Otherwise Flush() will always return PP_OK_COMPLETIONPENDING and the error
  // would be hidden.
  //
  // Note that we can also handle this by providing an actual callback which
  // takes the result code. Right now everything goes to the task that doesn't
  // result value.
  pp::CompletionCallback pp_callback(&CompletionCallbackClosureAdapter,
                                     task.get(),
                                     PP_COMPLETIONCALLBACK_FLAG_OPTIONAL);
  int error = graphics2d_.Flush(pp_callback);

  // There is already a flush in progress so set this flag to true so that we
  // can flush again later.
  // |paint_start| is then discarded but this is fine because we're not aiming
  // for precise measurement of timing, otherwise we need to keep a list of
  // queued start time(s).
  if (error == PP_ERROR_INPROGRESS)
    flush_blocked_ = true;
  else
    flush_blocked_ = false;

  // If Flush() returns asynchronously then release the task.
  if (error == PP_OK_COMPLETIONPENDING)
    ignore_result(task.release());
}

void PepperView::SetSolidFill(uint32 color) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  is_static_fill_ = true;
  static_fill_color_ = color;

  Paint();
}

void PepperView::UnsetSolidFill() {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  is_static_fill_ = false;
}

void PepperView::SetConnectionState(protocol::ConnectionToHost::State state,
                                    protocol::ConnectionToHost::Error error) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  // TODO(hclam): Re-consider the way we communicate with Javascript.
  ChromotingScriptableObject* scriptable_obj = instance_->GetScriptableObject();
  switch (state) {
    case protocol::ConnectionToHost::CONNECTING:
      SetSolidFill(kCreatedColor);
      scriptable_obj->SetConnectionStatus(
          ChromotingScriptableObject::STATUS_CONNECTING,
          ConvertConnectionError(error));
      break;

    case protocol::ConnectionToHost::CONNECTED:
      UnsetSolidFill();
      scriptable_obj->SetConnectionStatus(
          ChromotingScriptableObject::STATUS_CONNECTED,
          ConvertConnectionError(error));
      break;

    case protocol::ConnectionToHost::CLOSED:
      SetSolidFill(kDisconnectedColor);
      scriptable_obj->SetConnectionStatus(
          ChromotingScriptableObject::STATUS_CLOSED,
          ConvertConnectionError(error));
      break;

    case protocol::ConnectionToHost::FAILED:
      SetSolidFill(kFailedColor);
      scriptable_obj->SetConnectionStatus(
          ChromotingScriptableObject::STATUS_FAILED,
          ConvertConnectionError(error));
      break;
  }
}

bool PepperView::SetViewSize(const SkISize& view_size) {
  if (view_size_ == view_size)
    return false;
  view_size_ = view_size;

  pp::Size pp_size = pp::Size(view_size.width(), view_size.height());

  graphics2d_ = pp::Graphics2D(instance_, pp_size, true);
  if (!instance_->BindGraphics(graphics2d_)) {
    LOG(ERROR) << "Couldn't bind the device context.";
    return false;
  }

  if (view_size.isEmpty())
    return false;

  // Allocate the backing store to save the desktop image.
  if ((backing_store_.get() == NULL) ||
      (backing_store_->size() != pp_size)) {
    VLOG(1) << "Allocate backing store: "
            << view_size.width() << " x " << view_size.height();
    backing_store_.reset(
        new pp::ImageData(instance_, pp::ImageData::GetNativeImageDataFormat(),
                          pp_size, false));
    DCHECK(backing_store_.get() && !backing_store_->is_null())
        << "Not enough memory for backing store.";
  }
  return true;
}

void PepperView::AllocateFrame(media::VideoFrame::Format format,
                               const SkISize& size,
                               scoped_refptr<media::VideoFrame>* frame_out,
                               const base::Closure& done) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  *frame_out = media::VideoFrame::CreateFrame(
      media::VideoFrame::RGB32, size.width(), size.height(),
      base::TimeDelta(), base::TimeDelta());
  (*frame_out)->AddRef();
  done.Run();
}

void PepperView::ReleaseFrame(media::VideoFrame* frame) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  if (frame)
    frame->Release();
}

void PepperView::OnPartialFrameOutput(media::VideoFrame* frame,
                                      RectVector* rects,
                                      const base::Closure& done) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());

  // TODO(ajwong): Clean up this API to be async so we don't need to use a
  // member variable as a hack.
  PaintFrame(frame, rects);
  done.Run();
}

void PepperView::OnPaintDone(base::Time paint_start) {
  DCHECK(context_->main_message_loop()->BelongsToCurrentThread());
  instance_->GetStats()->video_paint_ms()->Record(
      (base::Time::Now() - paint_start).InMilliseconds());

  // If the last flush failed because there was already another one in progress
  // then we perform the flush now.
  if (flush_blocked_)
    FlushGraphics(base::Time::Now());
  return;
}

}  // namespace remoting