1 /*
2 * Copyright 2012 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 "examples/peerconnection/client/linux/main_wnd.h"
12
13 #include <cairo.h>
14 #include <gdk/gdk.h>
15 #include <gdk/gdkkeysyms.h>
16 #include <glib-object.h>
17 #include <glib.h>
18 #include <gobject/gclosure.h>
19 #include <gtk/gtk.h>
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include <cstdint>
26 #include <map>
27 #include <utility>
28
29 #include "api/video/i420_buffer.h"
30 #include "api/video/video_frame_buffer.h"
31 #include "api/video/video_rotation.h"
32 #include "api/video/video_source_interface.h"
33 #include "rtc_base/checks.h"
34 #include "rtc_base/logging.h"
35 #include "third_party/libyuv/include/libyuv/convert_from.h"
36
37 namespace {
38
39 //
40 // Simple static functions that simply forward the callback to the
41 // GtkMainWnd instance.
42 //
43
OnDestroyedCallback(GtkWidget * widget,GdkEvent * event,gpointer data)44 gboolean OnDestroyedCallback(GtkWidget* widget,
45 GdkEvent* event,
46 gpointer data) {
47 reinterpret_cast<GtkMainWnd*>(data)->OnDestroyed(widget, event);
48 return FALSE;
49 }
50
OnClickedCallback(GtkWidget * widget,gpointer data)51 void OnClickedCallback(GtkWidget* widget, gpointer data) {
52 reinterpret_cast<GtkMainWnd*>(data)->OnClicked(widget);
53 }
54
SimulateButtonClick(gpointer button)55 gboolean SimulateButtonClick(gpointer button) {
56 g_signal_emit_by_name(button, "clicked");
57 return false;
58 }
59
OnKeyPressCallback(GtkWidget * widget,GdkEventKey * key,gpointer data)60 gboolean OnKeyPressCallback(GtkWidget* widget,
61 GdkEventKey* key,
62 gpointer data) {
63 reinterpret_cast<GtkMainWnd*>(data)->OnKeyPress(widget, key);
64 return false;
65 }
66
OnRowActivatedCallback(GtkTreeView * tree_view,GtkTreePath * path,GtkTreeViewColumn * column,gpointer data)67 void OnRowActivatedCallback(GtkTreeView* tree_view,
68 GtkTreePath* path,
69 GtkTreeViewColumn* column,
70 gpointer data) {
71 reinterpret_cast<GtkMainWnd*>(data)->OnRowActivated(tree_view, path, column);
72 }
73
SimulateLastRowActivated(gpointer data)74 gboolean SimulateLastRowActivated(gpointer data) {
75 GtkTreeView* tree_view = reinterpret_cast<GtkTreeView*>(data);
76 GtkTreeModel* model = gtk_tree_view_get_model(tree_view);
77
78 // "if iter is NULL, then the number of toplevel nodes is returned."
79 int rows = gtk_tree_model_iter_n_children(model, NULL);
80 GtkTreePath* lastpath = gtk_tree_path_new_from_indices(rows - 1, -1);
81
82 // Select the last item in the list
83 GtkTreeSelection* selection = gtk_tree_view_get_selection(tree_view);
84 gtk_tree_selection_select_path(selection, lastpath);
85
86 // Our TreeView only has one column, so it is column 0.
87 GtkTreeViewColumn* column = gtk_tree_view_get_column(tree_view, 0);
88
89 gtk_tree_view_row_activated(tree_view, lastpath, column);
90
91 gtk_tree_path_free(lastpath);
92 return false;
93 }
94
95 // Creates a tree view, that we use to display the list of peers.
InitializeList(GtkWidget * list)96 void InitializeList(GtkWidget* list) {
97 GtkCellRenderer* renderer = gtk_cell_renderer_text_new();
98 GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes(
99 "List Items", renderer, "text", 0, NULL);
100 gtk_tree_view_append_column(GTK_TREE_VIEW(list), column);
101 GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT);
102 gtk_tree_view_set_model(GTK_TREE_VIEW(list), GTK_TREE_MODEL(store));
103 g_object_unref(store);
104 }
105
106 // Adds an entry to a tree view.
AddToList(GtkWidget * list,const gchar * str,int value)107 void AddToList(GtkWidget* list, const gchar* str, int value) {
108 GtkListStore* store =
109 GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(list)));
110
111 GtkTreeIter iter;
112 gtk_list_store_append(store, &iter);
113 gtk_list_store_set(store, &iter, 0, str, 1, value, -1);
114 }
115
116 struct UIThreadCallbackData {
UIThreadCallbackData__anon2dd38e550111::UIThreadCallbackData117 explicit UIThreadCallbackData(MainWndCallback* cb, int id, void* d)
118 : callback(cb), msg_id(id), data(d) {}
119 MainWndCallback* callback;
120 int msg_id;
121 void* data;
122 };
123
HandleUIThreadCallback(gpointer data)124 gboolean HandleUIThreadCallback(gpointer data) {
125 UIThreadCallbackData* cb_data = reinterpret_cast<UIThreadCallbackData*>(data);
126 cb_data->callback->UIThreadCallback(cb_data->msg_id, cb_data->data);
127 delete cb_data;
128 return false;
129 }
130
Redraw(gpointer data)131 gboolean Redraw(gpointer data) {
132 GtkMainWnd* wnd = reinterpret_cast<GtkMainWnd*>(data);
133 wnd->OnRedraw();
134 return false;
135 }
136
Draw(GtkWidget * widget,cairo_t * cr,gpointer data)137 gboolean Draw(GtkWidget* widget, cairo_t* cr, gpointer data) {
138 GtkMainWnd* wnd = reinterpret_cast<GtkMainWnd*>(data);
139 wnd->Draw(widget, cr);
140 return false;
141 }
142
143 } // namespace
144
145 //
146 // GtkMainWnd implementation.
147 //
148
GtkMainWnd(const char * server,int port,bool autoconnect,bool autocall)149 GtkMainWnd::GtkMainWnd(const char* server,
150 int port,
151 bool autoconnect,
152 bool autocall)
153 : window_(NULL),
154 draw_area_(NULL),
155 vbox_(NULL),
156 server_edit_(NULL),
157 port_edit_(NULL),
158 peer_list_(NULL),
159 callback_(NULL),
160 server_(server),
161 autoconnect_(autoconnect),
162 autocall_(autocall) {
163 char buffer[10];
164 snprintf(buffer, sizeof(buffer), "%i", port);
165 port_ = buffer;
166 }
167
~GtkMainWnd()168 GtkMainWnd::~GtkMainWnd() {
169 RTC_DCHECK(!IsWindow());
170 }
171
RegisterObserver(MainWndCallback * callback)172 void GtkMainWnd::RegisterObserver(MainWndCallback* callback) {
173 callback_ = callback;
174 }
175
IsWindow()176 bool GtkMainWnd::IsWindow() {
177 return window_ != NULL && GTK_IS_WINDOW(window_);
178 }
179
MessageBox(const char * caption,const char * text,bool is_error)180 void GtkMainWnd::MessageBox(const char* caption,
181 const char* text,
182 bool is_error) {
183 GtkWidget* dialog = gtk_message_dialog_new(
184 GTK_WINDOW(window_), GTK_DIALOG_DESTROY_WITH_PARENT,
185 is_error ? GTK_MESSAGE_ERROR : GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s",
186 text);
187 gtk_window_set_title(GTK_WINDOW(dialog), caption);
188 gtk_dialog_run(GTK_DIALOG(dialog));
189 gtk_widget_destroy(dialog);
190 }
191
current_ui()192 MainWindow::UI GtkMainWnd::current_ui() {
193 if (vbox_)
194 return CONNECT_TO_SERVER;
195
196 if (peer_list_)
197 return LIST_PEERS;
198
199 return STREAMING;
200 }
201
StartLocalRenderer(webrtc::VideoTrackInterface * local_video)202 void GtkMainWnd::StartLocalRenderer(webrtc::VideoTrackInterface* local_video) {
203 local_renderer_.reset(new VideoRenderer(this, local_video));
204 }
205
StopLocalRenderer()206 void GtkMainWnd::StopLocalRenderer() {
207 local_renderer_.reset();
208 }
209
StartRemoteRenderer(webrtc::VideoTrackInterface * remote_video)210 void GtkMainWnd::StartRemoteRenderer(
211 webrtc::VideoTrackInterface* remote_video) {
212 remote_renderer_.reset(new VideoRenderer(this, remote_video));
213 }
214
StopRemoteRenderer()215 void GtkMainWnd::StopRemoteRenderer() {
216 remote_renderer_.reset();
217 }
218
QueueUIThreadCallback(int msg_id,void * data)219 void GtkMainWnd::QueueUIThreadCallback(int msg_id, void* data) {
220 g_idle_add(HandleUIThreadCallback,
221 new UIThreadCallbackData(callback_, msg_id, data));
222 }
223
Create()224 bool GtkMainWnd::Create() {
225 RTC_DCHECK(window_ == NULL);
226
227 window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
228 if (window_) {
229 gtk_window_set_position(GTK_WINDOW(window_), GTK_WIN_POS_CENTER);
230 gtk_window_set_default_size(GTK_WINDOW(window_), 640, 480);
231 gtk_window_set_title(GTK_WINDOW(window_), "PeerConnection client");
232 g_signal_connect(G_OBJECT(window_), "delete-event",
233 G_CALLBACK(&OnDestroyedCallback), this);
234 g_signal_connect(window_, "key-press-event", G_CALLBACK(OnKeyPressCallback),
235 this);
236
237 SwitchToConnectUI();
238 }
239
240 return window_ != NULL;
241 }
242
Destroy()243 bool GtkMainWnd::Destroy() {
244 if (!IsWindow())
245 return false;
246
247 gtk_widget_destroy(window_);
248 window_ = NULL;
249
250 return true;
251 }
252
SwitchToConnectUI()253 void GtkMainWnd::SwitchToConnectUI() {
254 RTC_LOG(INFO) << __FUNCTION__;
255
256 RTC_DCHECK(IsWindow());
257 RTC_DCHECK(vbox_ == NULL);
258
259 gtk_container_set_border_width(GTK_CONTAINER(window_), 10);
260
261 if (peer_list_) {
262 gtk_widget_destroy(peer_list_);
263 peer_list_ = NULL;
264 }
265
266 #if GTK_MAJOR_VERSION == 2
267 vbox_ = gtk_vbox_new(FALSE, 5);
268 #else
269 vbox_ = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
270 #endif
271 GtkWidget* valign = gtk_alignment_new(0, 1, 0, 0);
272 gtk_container_add(GTK_CONTAINER(vbox_), valign);
273 gtk_container_add(GTK_CONTAINER(window_), vbox_);
274
275 #if GTK_MAJOR_VERSION == 2
276 GtkWidget* hbox = gtk_hbox_new(FALSE, 5);
277 #else
278 GtkWidget* hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
279 #endif
280
281 GtkWidget* label = gtk_label_new("Server");
282 gtk_container_add(GTK_CONTAINER(hbox), label);
283
284 server_edit_ = gtk_entry_new();
285 gtk_entry_set_text(GTK_ENTRY(server_edit_), server_.c_str());
286 gtk_widget_set_size_request(server_edit_, 400, 30);
287 gtk_container_add(GTK_CONTAINER(hbox), server_edit_);
288
289 port_edit_ = gtk_entry_new();
290 gtk_entry_set_text(GTK_ENTRY(port_edit_), port_.c_str());
291 gtk_widget_set_size_request(port_edit_, 70, 30);
292 gtk_container_add(GTK_CONTAINER(hbox), port_edit_);
293
294 GtkWidget* button = gtk_button_new_with_label("Connect");
295 gtk_widget_set_size_request(button, 70, 30);
296 g_signal_connect(button, "clicked", G_CALLBACK(OnClickedCallback), this);
297 gtk_container_add(GTK_CONTAINER(hbox), button);
298
299 GtkWidget* halign = gtk_alignment_new(1, 0, 0, 0);
300 gtk_container_add(GTK_CONTAINER(halign), hbox);
301 gtk_box_pack_start(GTK_BOX(vbox_), halign, FALSE, FALSE, 0);
302
303 gtk_widget_show_all(window_);
304
305 if (autoconnect_)
306 g_idle_add(SimulateButtonClick, button);
307 }
308
SwitchToPeerList(const Peers & peers)309 void GtkMainWnd::SwitchToPeerList(const Peers& peers) {
310 RTC_LOG(INFO) << __FUNCTION__;
311
312 if (!peer_list_) {
313 gtk_container_set_border_width(GTK_CONTAINER(window_), 0);
314 if (vbox_) {
315 gtk_widget_destroy(vbox_);
316 vbox_ = NULL;
317 server_edit_ = NULL;
318 port_edit_ = NULL;
319 } else if (draw_area_) {
320 gtk_widget_destroy(draw_area_);
321 draw_area_ = NULL;
322 draw_buffer_.reset();
323 }
324
325 peer_list_ = gtk_tree_view_new();
326 g_signal_connect(peer_list_, "row-activated",
327 G_CALLBACK(OnRowActivatedCallback), this);
328 gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(peer_list_), FALSE);
329 InitializeList(peer_list_);
330 gtk_container_add(GTK_CONTAINER(window_), peer_list_);
331 gtk_widget_show_all(window_);
332 } else {
333 GtkListStore* store =
334 GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(peer_list_)));
335 gtk_list_store_clear(store);
336 }
337
338 AddToList(peer_list_, "List of currently connected peers:", -1);
339 for (Peers::const_iterator i = peers.begin(); i != peers.end(); ++i)
340 AddToList(peer_list_, i->second.c_str(), i->first);
341
342 if (autocall_ && peers.begin() != peers.end())
343 g_idle_add(SimulateLastRowActivated, peer_list_);
344 }
345
SwitchToStreamingUI()346 void GtkMainWnd::SwitchToStreamingUI() {
347 RTC_LOG(INFO) << __FUNCTION__;
348
349 RTC_DCHECK(draw_area_ == NULL);
350
351 gtk_container_set_border_width(GTK_CONTAINER(window_), 0);
352 if (peer_list_) {
353 gtk_widget_destroy(peer_list_);
354 peer_list_ = NULL;
355 }
356
357 draw_area_ = gtk_drawing_area_new();
358 gtk_container_add(GTK_CONTAINER(window_), draw_area_);
359 g_signal_connect(G_OBJECT(draw_area_), "draw", G_CALLBACK(&::Draw), this);
360
361 gtk_widget_show_all(window_);
362 }
363
OnDestroyed(GtkWidget * widget,GdkEvent * event)364 void GtkMainWnd::OnDestroyed(GtkWidget* widget, GdkEvent* event) {
365 callback_->Close();
366 window_ = NULL;
367 draw_area_ = NULL;
368 vbox_ = NULL;
369 server_edit_ = NULL;
370 port_edit_ = NULL;
371 peer_list_ = NULL;
372 }
373
OnClicked(GtkWidget * widget)374 void GtkMainWnd::OnClicked(GtkWidget* widget) {
375 // Make the connect button insensitive, so that it cannot be clicked more than
376 // once. Now that the connection includes auto-retry, it should not be
377 // necessary to click it more than once.
378 gtk_widget_set_sensitive(widget, false);
379 server_ = gtk_entry_get_text(GTK_ENTRY(server_edit_));
380 port_ = gtk_entry_get_text(GTK_ENTRY(port_edit_));
381 int port = port_.length() ? atoi(port_.c_str()) : 0;
382 callback_->StartLogin(server_, port);
383 }
384
OnKeyPress(GtkWidget * widget,GdkEventKey * key)385 void GtkMainWnd::OnKeyPress(GtkWidget* widget, GdkEventKey* key) {
386 if (key->type == GDK_KEY_PRESS) {
387 switch (key->keyval) {
388 #if GTK_MAJOR_VERSION == 2
389 case GDK_Escape:
390 #else
391 case GDK_KEY_Escape:
392 #endif
393 if (draw_area_) {
394 callback_->DisconnectFromCurrentPeer();
395 } else if (peer_list_) {
396 callback_->DisconnectFromServer();
397 }
398 break;
399
400 #if GTK_MAJOR_VERSION == 2
401 case GDK_KP_Enter:
402 case GDK_Return:
403 #else
404 case GDK_KEY_KP_Enter:
405 case GDK_KEY_Return:
406 #endif
407 if (vbox_) {
408 OnClicked(NULL);
409 } else if (peer_list_) {
410 // OnRowActivated will be called automatically when the user
411 // presses enter.
412 }
413 break;
414
415 default:
416 break;
417 }
418 }
419 }
420
OnRowActivated(GtkTreeView * tree_view,GtkTreePath * path,GtkTreeViewColumn * column)421 void GtkMainWnd::OnRowActivated(GtkTreeView* tree_view,
422 GtkTreePath* path,
423 GtkTreeViewColumn* column) {
424 RTC_DCHECK(peer_list_ != NULL);
425 GtkTreeIter iter;
426 GtkTreeModel* model;
427 GtkTreeSelection* selection =
428 gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_view));
429 if (gtk_tree_selection_get_selected(selection, &model, &iter)) {
430 char* text;
431 int id = -1;
432 gtk_tree_model_get(model, &iter, 0, &text, 1, &id, -1);
433 if (id != -1)
434 callback_->ConnectToPeer(id);
435 g_free(text);
436 }
437 }
438
OnRedraw()439 void GtkMainWnd::OnRedraw() {
440 gdk_threads_enter();
441
442 VideoRenderer* remote_renderer = remote_renderer_.get();
443 if (remote_renderer && remote_renderer->image() != NULL &&
444 draw_area_ != NULL) {
445 width_ = remote_renderer->width();
446 height_ = remote_renderer->height();
447
448 if (!draw_buffer_.get()) {
449 draw_buffer_size_ = (width_ * height_ * 4) * 4;
450 draw_buffer_.reset(new uint8_t[draw_buffer_size_]);
451 gtk_widget_set_size_request(draw_area_, width_ * 2, height_ * 2);
452 }
453
454 const uint32_t* image =
455 reinterpret_cast<const uint32_t*>(remote_renderer->image());
456 uint32_t* scaled = reinterpret_cast<uint32_t*>(draw_buffer_.get());
457 for (int r = 0; r < height_; ++r) {
458 for (int c = 0; c < width_; ++c) {
459 int x = c * 2;
460 scaled[x] = scaled[x + 1] = image[c];
461 }
462
463 uint32_t* prev_line = scaled;
464 scaled += width_ * 2;
465 memcpy(scaled, prev_line, (width_ * 2) * 4);
466
467 image += width_;
468 scaled += width_ * 2;
469 }
470
471 VideoRenderer* local_renderer = local_renderer_.get();
472 if (local_renderer && local_renderer->image()) {
473 image = reinterpret_cast<const uint32_t*>(local_renderer->image());
474 scaled = reinterpret_cast<uint32_t*>(draw_buffer_.get());
475 // Position the local preview on the right side.
476 scaled += (width_ * 2) - (local_renderer->width() / 2);
477 // right margin...
478 scaled -= 10;
479 // ... towards the bottom.
480 scaled += (height_ * width_ * 4) - ((local_renderer->height() / 2) *
481 (local_renderer->width() / 2) * 4);
482 // bottom margin...
483 scaled -= (width_ * 2) * 5;
484 for (int r = 0; r < local_renderer->height(); r += 2) {
485 for (int c = 0; c < local_renderer->width(); c += 2) {
486 scaled[c / 2] = image[c + r * local_renderer->width()];
487 }
488 scaled += width_ * 2;
489 }
490 }
491
492 #if GTK_MAJOR_VERSION == 2
493 gdk_draw_rgb_32_image(draw_area_->window,
494 draw_area_->style->fg_gc[GTK_STATE_NORMAL], 0, 0,
495 width_ * 2, height_ * 2, GDK_RGB_DITHER_MAX,
496 draw_buffer_.get(), (width_ * 2) * 4);
497 #else
498 gtk_widget_queue_draw(draw_area_);
499 #endif
500 }
501
502 gdk_threads_leave();
503 }
504
Draw(GtkWidget * widget,cairo_t * cr)505 void GtkMainWnd::Draw(GtkWidget* widget, cairo_t* cr) {
506 #if GTK_MAJOR_VERSION != 2
507 cairo_format_t format = CAIRO_FORMAT_ARGB32;
508 cairo_surface_t* surface = cairo_image_surface_create_for_data(
509 draw_buffer_.get(), format, width_ * 2, height_ * 2,
510 cairo_format_stride_for_width(format, width_ * 2));
511 cairo_set_source_surface(cr, surface, 0, 0);
512 cairo_rectangle(cr, 0, 0, width_ * 2, height_ * 2);
513 cairo_fill(cr);
514 cairo_surface_destroy(surface);
515 #else
516 RTC_NOTREACHED();
517 #endif
518 }
519
VideoRenderer(GtkMainWnd * main_wnd,webrtc::VideoTrackInterface * track_to_render)520 GtkMainWnd::VideoRenderer::VideoRenderer(
521 GtkMainWnd* main_wnd,
522 webrtc::VideoTrackInterface* track_to_render)
523 : width_(0),
524 height_(0),
525 main_wnd_(main_wnd),
526 rendered_track_(track_to_render) {
527 rendered_track_->AddOrUpdateSink(this, rtc::VideoSinkWants());
528 }
529
~VideoRenderer()530 GtkMainWnd::VideoRenderer::~VideoRenderer() {
531 rendered_track_->RemoveSink(this);
532 }
533
SetSize(int width,int height)534 void GtkMainWnd::VideoRenderer::SetSize(int width, int height) {
535 gdk_threads_enter();
536
537 if (width_ == width && height_ == height) {
538 return;
539 }
540
541 width_ = width;
542 height_ = height;
543 image_.reset(new uint8_t[width * height * 4]);
544 gdk_threads_leave();
545 }
546
OnFrame(const webrtc::VideoFrame & video_frame)547 void GtkMainWnd::VideoRenderer::OnFrame(const webrtc::VideoFrame& video_frame) {
548 gdk_threads_enter();
549
550 rtc::scoped_refptr<webrtc::I420BufferInterface> buffer(
551 video_frame.video_frame_buffer()->ToI420());
552 if (video_frame.rotation() != webrtc::kVideoRotation_0) {
553 buffer = webrtc::I420Buffer::Rotate(*buffer, video_frame.rotation());
554 }
555 SetSize(buffer->width(), buffer->height());
556
557 // TODO(bugs.webrtc.org/6857): This conversion is correct for little-endian
558 // only. Cairo ARGB32 treats pixels as 32-bit values in *native* byte order,
559 // with B in the least significant byte of the 32-bit value. Which on
560 // little-endian means that memory layout is BGRA, with the B byte stored at
561 // lowest address. Libyuv's ARGB format (surprisingly?) uses the same
562 // little-endian format, with B in the first byte in memory, regardless of
563 // native endianness.
564 libyuv::I420ToARGB(buffer->DataY(), buffer->StrideY(), buffer->DataU(),
565 buffer->StrideU(), buffer->DataV(), buffer->StrideV(),
566 image_.get(), width_ * 4, buffer->width(),
567 buffer->height());
568
569 gdk_threads_leave();
570
571 g_idle_add(Redraw, main_wnd_);
572 }
573