You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1585 lines
54 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/examples/call/callclient.h"
  28. #include <string>
  29. #include "talk/base/helpers.h"
  30. #include "talk/base/logging.h"
  31. #include "talk/base/network.h"
  32. #include "talk/base/socketaddress.h"
  33. #include "talk/base/stringencode.h"
  34. #include "talk/base/stringutils.h"
  35. #include "talk/base/thread.h"
  36. #include "talk/base/windowpickerfactory.h"
  37. #include "talk/examples/call/console.h"
  38. #include "talk/examples/call/friendinvitesendtask.h"
  39. #include "talk/examples/call/muc.h"
  40. #include "talk/examples/call/mucinviterecvtask.h"
  41. #include "talk/examples/call/mucinvitesendtask.h"
  42. #include "talk/examples/call/presencepushtask.h"
  43. #include "talk/media/base/mediacommon.h"
  44. #include "talk/media/base/mediaengine.h"
  45. #include "talk/media/base/rtpdataengine.h"
  46. #include "talk/media/base/screencastid.h"
  47. #include "talk/media/devices/devicemanager.h"
  48. #include "talk/media/devices/videorendererfactory.h"
  49. #include "talk/p2p/base/sessionmanager.h"
  50. #include "talk/p2p/client/basicportallocator.h"
  51. #include "talk/p2p/client/sessionmanagertask.h"
  52. #include "talk/session/media/mediamessages.h"
  53. #include "talk/session/media/mediasessionclient.h"
  54. #include "talk/xmpp/constants.h"
  55. #include "talk/xmpp/hangoutpubsubclient.h"
  56. #include "talk/xmpp/mucroomconfigtask.h"
  57. #include "talk/xmpp/mucroomlookuptask.h"
  58. #include "talk/xmpp/presenceouttask.h"
  59. #include "talk/xmpp/pingtask.h"
  60. namespace {
  61. // Must be period >= timeout.
  62. const uint32 kPingPeriodMillis = 10000;
  63. const uint32 kPingTimeoutMillis = 10000;
  64. const char* DescribeStatus(buzz::PresenceStatus::Show show,
  65. const std::string& desc) {
  66. switch (show) {
  67. case buzz::PresenceStatus::SHOW_XA: return desc.c_str();
  68. case buzz::PresenceStatus::SHOW_ONLINE: return "online";
  69. case buzz::PresenceStatus::SHOW_AWAY: return "away";
  70. case buzz::PresenceStatus::SHOW_DND: return "do not disturb";
  71. case buzz::PresenceStatus::SHOW_CHAT: return "ready to chat";
  72. default: return "offline";
  73. }
  74. }
  75. std::string GetWord(const std::vector<std::string>& words,
  76. size_t index, const std::string& def) {
  77. if (words.size() > index) {
  78. return words[index];
  79. } else {
  80. return def;
  81. }
  82. }
  83. int GetInt(const std::vector<std::string>& words, size_t index, int def) {
  84. int val;
  85. if (words.size() > index && talk_base::FromString(words[index], &val)) {
  86. return val;
  87. } else {
  88. return def;
  89. }
  90. }
  91. } // namespace
  92. const char* CALL_COMMANDS =
  93. "Available commands:\n"
  94. "\n"
  95. " hangup Ends the call.\n"
  96. " hold Puts the current call on hold\n"
  97. " calls Lists the current calls and their sessions\n"
  98. " switch [call_id] Switch to the specified call\n"
  99. " addsession [jid] Add a new session to the current call.\n"
  100. " rmsession [sid] Remove specified session.\n"
  101. " mute Stops sending voice.\n"
  102. " unmute Re-starts sending voice.\n"
  103. " vmute Stops sending video.\n"
  104. " vunmute Re-starts sending video.\n"
  105. " dtmf Sends a DTMF tone.\n"
  106. " stats Print voice stats for the current call.\n"
  107. " quit Quits the application.\n"
  108. "";
  109. // TODO: Make present and record really work.
  110. const char* HANGOUT_COMMANDS =
  111. "Available MUC commands:\n"
  112. "\n"
  113. " present Starts presenting (just signalling; not actually presenting.)\n"
  114. " unpresent Stops presenting (just signalling; not actually presenting.)\n"
  115. " record Starts recording (just signalling; not actually recording.)\n"
  116. " unrecord Stops recording (just signalling; not actually recording.)\n"
  117. " rmute [nick] Remote mute another participant.\n"
  118. " block [nick] Block another participant.\n"
  119. " screencast [fps] Starts screencast. \n"
  120. " unscreencast Stops screencast. \n"
  121. " quit Quits the application.\n"
  122. "";
  123. const char* RECEIVE_COMMANDS =
  124. "Available commands:\n"
  125. "\n"
  126. " accept [bw] Accepts the incoming call and switches to it.\n"
  127. " reject Rejects the incoming call and stays with the current call.\n"
  128. " quit Quits the application.\n"
  129. "";
  130. const char* CONSOLE_COMMANDS =
  131. "Available commands:\n"
  132. "\n"
  133. " roster Prints the online friends from your roster.\n"
  134. " friend user Request to add a user to your roster.\n"
  135. " call [jid] [bw] Initiates a call to the user[/room] with the\n"
  136. " given JID and with optional bandwidth.\n"
  137. " vcall [jid] [bw] Initiates a video call to the user[/room] with\n"
  138. " the given JID and with optional bandwidth.\n"
  139. " calls Lists the current calls\n"
  140. " switch [call_id] Switch to the specified call\n"
  141. " join [room_jid] Joins a multi-user-chat with room JID.\n"
  142. " ljoin [room_name] Joins a MUC by looking up JID from room name.\n"
  143. " invite user [room] Invites a friend to a multi-user-chat.\n"
  144. " leave [room] Leaves a multi-user-chat.\n"
  145. " nick [nick] Sets the nick.\n"
  146. " priority [int] Sets the priority.\n"
  147. " getdevs Prints the available media devices.\n"
  148. " quit Quits the application.\n"
  149. "";
  150. void CallClient::ParseLine(const std::string& line) {
  151. std::vector<std::string> words;
  152. int start = -1;
  153. int state = 0;
  154. for (int index = 0; index <= static_cast<int>(line.size()); ++index) {
  155. if (state == 0) {
  156. if (!isspace(line[index])) {
  157. start = index;
  158. state = 1;
  159. }
  160. } else {
  161. ASSERT(state == 1);
  162. ASSERT(start >= 0);
  163. if (isspace(line[index])) {
  164. std::string word(line, start, index - start);
  165. words.push_back(word);
  166. start = -1;
  167. state = 0;
  168. }
  169. }
  170. }
  171. // Global commands
  172. const std::string& command = GetWord(words, 0, "");
  173. if (command == "quit") {
  174. Quit();
  175. } else if (call_ && incoming_call_) {
  176. if (command == "accept") {
  177. cricket::CallOptions options;
  178. options.video_bandwidth = GetInt(words, 1, cricket::kAutoBandwidth);
  179. options.has_video = true;
  180. options.has_data = data_channel_enabled_;
  181. Accept(options);
  182. } else if (command == "reject") {
  183. Reject();
  184. } else {
  185. console_->PrintLine(RECEIVE_COMMANDS);
  186. }
  187. } else if (call_) {
  188. if (command == "hangup") {
  189. call_->Terminate();
  190. } else if (command == "hold") {
  191. media_client_->SetFocus(NULL);
  192. call_ = NULL;
  193. } else if (command == "addsession") {
  194. std::string to = GetWord(words, 1, "");
  195. cricket::CallOptions options;
  196. options.has_video = call_->has_video();
  197. options.video_bandwidth = cricket::kAutoBandwidth;
  198. options.has_data = data_channel_enabled_;
  199. options.AddStream(cricket::MEDIA_TYPE_VIDEO, "", "");
  200. if (!InitiateAdditionalSession(to, options)) {
  201. console_->PrintLine("Failed to initiate additional session.");
  202. }
  203. } else if (command == "rmsession") {
  204. std::string id = GetWord(words, 1, "");
  205. TerminateAndRemoveSession(call_, id);
  206. } else if (command == "calls") {
  207. PrintCalls();
  208. } else if ((words.size() == 2) && (command == "switch")) {
  209. SwitchToCall(GetInt(words, 1, -1));
  210. } else if (command == "mute") {
  211. call_->Mute(true);
  212. if (InMuc()) {
  213. hangout_pubsub_client_->PublishAudioMuteState(true);
  214. }
  215. } else if (command == "unmute") {
  216. call_->Mute(false);
  217. if (InMuc()) {
  218. hangout_pubsub_client_->PublishAudioMuteState(false);
  219. }
  220. } else if (command == "vmute") {
  221. call_->MuteVideo(true);
  222. if (InMuc()) {
  223. hangout_pubsub_client_->PublishVideoMuteState(true);
  224. }
  225. } else if (command == "vunmute") {
  226. call_->MuteVideo(false);
  227. if (InMuc()) {
  228. hangout_pubsub_client_->PublishVideoMuteState(false);
  229. }
  230. } else if (command == "screencast") {
  231. if (screencast_ssrc_ != 0) {
  232. console_->PrintLine("Can't screencast twice. Unscreencast first.");
  233. } else {
  234. std::string stream_name = "screencast";
  235. screencast_ssrc_ = talk_base::CreateRandomId();
  236. int fps = GetInt(words, 1, 5); // Default to 5 fps.
  237. cricket::ScreencastId screencastid;
  238. cricket::Session* session = GetFirstSession();
  239. if (session && SelectFirstDesktopScreencastId(&screencastid)) {
  240. call_->StartScreencast(
  241. session, stream_name, screencast_ssrc_, screencastid, fps);
  242. }
  243. }
  244. } else if (command == "unscreencast") {
  245. // TODO: Use a random ssrc
  246. std::string stream_name = "screencast";
  247. cricket::Session* session = GetFirstSession();
  248. if (session) {
  249. call_->StopScreencast(session, stream_name, screencast_ssrc_);
  250. screencast_ssrc_ = 0;
  251. }
  252. } else if (command == "present") {
  253. if (InMuc()) {
  254. hangout_pubsub_client_->PublishPresenterState(true);
  255. }
  256. } else if (command == "unpresent") {
  257. if (InMuc()) {
  258. hangout_pubsub_client_->PublishPresenterState(false);
  259. }
  260. } else if (command == "record") {
  261. if (InMuc()) {
  262. hangout_pubsub_client_->PublishRecordingState(true);
  263. }
  264. } else if (command == "unrecord") {
  265. if (InMuc()) {
  266. hangout_pubsub_client_->PublishRecordingState(false);
  267. }
  268. } else if ((command == "rmute") && (words.size() == 2)) {
  269. if (InMuc()) {
  270. const std::string& nick = words[1];
  271. hangout_pubsub_client_->RemoteMute(nick);
  272. }
  273. } else if ((command == "block") && (words.size() == 2)) {
  274. if (InMuc()) {
  275. const std::string& nick = words[1];
  276. hangout_pubsub_client_->BlockMedia(nick);
  277. }
  278. } else if (command == "senddata") {
  279. // "" is the default stream name.
  280. SendData("", words[1]);
  281. } else if ((command == "dtmf") && (words.size() == 2)) {
  282. int ev = std::string("0123456789*#").find(words[1][0]);
  283. call_->PressDTMF(ev);
  284. } else if (command == "stats") {
  285. PrintStats();
  286. } else {
  287. console_->PrintLine(CALL_COMMANDS);
  288. if (InMuc()) {
  289. console_->PrintLine(HANGOUT_COMMANDS);
  290. }
  291. }
  292. } else {
  293. if (command == "roster") {
  294. PrintRoster();
  295. } else if (command == "send") {
  296. buzz::Jid jid(words[1]);
  297. if (jid.IsValid()) {
  298. last_sent_to_ = words[1];
  299. SendChat(words[1], words[2]);
  300. } else if (!last_sent_to_.empty()) {
  301. SendChat(last_sent_to_, words[1]);
  302. } else {
  303. console_->PrintLine(
  304. "Invalid JID. JIDs should be in the form user@domain");
  305. }
  306. } else if ((words.size() == 2) && (command == "friend")) {
  307. InviteFriend(words[1]);
  308. } else if (command == "call") {
  309. std::string to = GetWord(words, 1, "");
  310. cricket::CallOptions options;
  311. options.has_data = data_channel_enabled_;
  312. if (!PlaceCall(to, options)) {
  313. console_->PrintLine("Failed to initiate call.");
  314. }
  315. } else if (command == "vcall") {
  316. std::string to = GetWord(words, 1, "");
  317. int bandwidth = GetInt(words, 2, cricket::kAutoBandwidth);
  318. cricket::CallOptions options;
  319. options.has_video = true;
  320. options.video_bandwidth = bandwidth;
  321. options.has_data = data_channel_enabled_;
  322. if (!PlaceCall(to, options)) {
  323. console_->PrintLine("Failed to initiate call.");
  324. }
  325. } else if (command == "calls") {
  326. PrintCalls();
  327. } else if ((words.size() == 2) && (command == "switch")) {
  328. SwitchToCall(GetInt(words, 1, -1));
  329. } else if (command == "join") {
  330. JoinMuc(GetWord(words, 1, ""));
  331. } else if (command == "ljoin") {
  332. LookupAndJoinMuc(GetWord(words, 1, ""));
  333. } else if ((words.size() >= 2) && (command == "invite")) {
  334. InviteToMuc(words[1], GetWord(words, 2, ""));
  335. } else if (command == "leave") {
  336. LeaveMuc(GetWord(words, 1, ""));
  337. } else if (command == "nick") {
  338. SetNick(GetWord(words, 1, ""));
  339. } else if (command == "priority") {
  340. int priority = GetInt(words, 1, 0);
  341. SetPriority(priority);
  342. SendStatus();
  343. } else if (command == "getdevs") {
  344. GetDevices();
  345. } else if ((words.size() == 2) && (command == "setvol")) {
  346. SetVolume(words[1]);
  347. } else {
  348. console_->PrintLine(CONSOLE_COMMANDS);
  349. }
  350. }
  351. }
  352. CallClient::CallClient(buzz::XmppClient* xmpp_client,
  353. const std::string& caps_node, const std::string& version)
  354. : xmpp_client_(xmpp_client),
  355. worker_thread_(NULL),
  356. media_engine_(NULL),
  357. data_engine_(NULL),
  358. media_client_(NULL),
  359. call_(NULL),
  360. hangout_pubsub_client_(NULL),
  361. incoming_call_(false),
  362. auto_accept_(false),
  363. pmuc_domain_("groupchat.google.com"),
  364. render_(true),
  365. data_channel_enabled_(false),
  366. multisession_enabled_(false),
  367. local_renderer_(NULL),
  368. static_views_accumulated_count_(0),
  369. screencast_ssrc_(0),
  370. roster_(new RosterMap),
  371. portallocator_flags_(0),
  372. allow_local_ips_(false),
  373. signaling_protocol_(cricket::PROTOCOL_HYBRID),
  374. transport_protocol_(cricket::ICEPROTO_HYBRID),
  375. sdes_policy_(cricket::SEC_DISABLED),
  376. dtls_policy_(cricket::SEC_DISABLED),
  377. ssl_identity_(NULL) {
  378. xmpp_client_->SignalStateChange.connect(this, &CallClient::OnStateChange);
  379. my_status_.set_caps_node(caps_node);
  380. my_status_.set_version(version);
  381. }
  382. CallClient::~CallClient() {
  383. delete media_client_;
  384. delete roster_;
  385. delete worker_thread_;
  386. }
  387. const std::string CallClient::strerror(buzz::XmppEngine::Error err) {
  388. switch (err) {
  389. case buzz::XmppEngine::ERROR_NONE:
  390. return "";
  391. case buzz::XmppEngine::ERROR_XML:
  392. return "Malformed XML or encoding error";
  393. case buzz::XmppEngine::ERROR_STREAM:
  394. return "XMPP stream error";
  395. case buzz::XmppEngine::ERROR_VERSION:
  396. return "XMPP version error";
  397. case buzz::XmppEngine::ERROR_UNAUTHORIZED:
  398. return "User is not authorized (Check your username and password)";
  399. case buzz::XmppEngine::ERROR_TLS:
  400. return "TLS could not be negotiated";
  401. case buzz::XmppEngine::ERROR_AUTH:
  402. return "Authentication could not be negotiated";
  403. case buzz::XmppEngine::ERROR_BIND:
  404. return "Resource or session binding could not be negotiated";
  405. case buzz::XmppEngine::ERROR_CONNECTION_CLOSED:
  406. return "Connection closed by output handler.";
  407. case buzz::XmppEngine::ERROR_DOCUMENT_CLOSED:
  408. return "Closed by </stream:stream>";
  409. case buzz::XmppEngine::ERROR_SOCKET:
  410. return "Socket error";
  411. default:
  412. return "Unknown error";
  413. }
  414. }
  415. void CallClient::OnCallDestroy(cricket::Call* call) {
  416. RemoveCallsStaticRenderedViews(call);
  417. if (call == call_) {
  418. if (local_renderer_) {
  419. delete local_renderer_;
  420. local_renderer_ = NULL;
  421. }
  422. console_->PrintLine("call destroyed");
  423. call_ = NULL;
  424. delete hangout_pubsub_client_;
  425. hangout_pubsub_client_ = NULL;
  426. }
  427. }
  428. void CallClient::OnStateChange(buzz::XmppEngine::State state) {
  429. switch (state) {
  430. case buzz::XmppEngine::STATE_START:
  431. console_->PrintLine("connecting...");
  432. break;
  433. case buzz::XmppEngine::STATE_OPENING:
  434. console_->PrintLine("logging in...");
  435. break;
  436. case buzz::XmppEngine::STATE_OPEN:
  437. console_->PrintLine("logged in...");
  438. InitMedia();
  439. InitPresence();
  440. break;
  441. case buzz::XmppEngine::STATE_CLOSED:
  442. {
  443. buzz::XmppEngine::Error error = xmpp_client_->GetError(NULL);
  444. console_->PrintLine("logged out... %s", strerror(error).c_str());
  445. Quit();
  446. }
  447. break;
  448. default:
  449. break;
  450. }
  451. }
  452. void CallClient::InitMedia() {
  453. worker_thread_ = new talk_base::Thread();
  454. // The worker thread must be started here since initialization of
  455. // the ChannelManager will generate messages that need to be
  456. // dispatched by it.
  457. worker_thread_->Start();
  458. // TODO: It looks like we are leaking many objects. E.g.
  459. // |network_manager_| is never deleted.
  460. network_manager_ = new talk_base::BasicNetworkManager();
  461. // TODO: Decide if the relay address should be specified here.
  462. talk_base::SocketAddress stun_addr("stun.l.google.com", 19302);
  463. port_allocator_ = new cricket::BasicPortAllocator(
  464. network_manager_, stun_addr, talk_base::SocketAddress(),
  465. talk_base::SocketAddress(), talk_base::SocketAddress());
  466. if (portallocator_flags_ != 0) {
  467. port_allocator_->set_flags(portallocator_flags_);
  468. }
  469. session_manager_ = new cricket::SessionManager(
  470. port_allocator_, worker_thread_);
  471. session_manager_->set_secure(dtls_policy_);
  472. session_manager_->set_identity(ssl_identity_.get());
  473. session_manager_->set_transport_protocol(transport_protocol_);
  474. session_manager_->SignalRequestSignaling.connect(
  475. this, &CallClient::OnRequestSignaling);
  476. session_manager_->SignalSessionCreate.connect(
  477. this, &CallClient::OnSessionCreate);
  478. session_manager_->OnSignalingReady();
  479. session_manager_task_ =
  480. new cricket::SessionManagerTask(xmpp_client_, session_manager_);
  481. session_manager_task_->EnableOutgoingMessages();
  482. session_manager_task_->Start();
  483. if (!media_engine_) {
  484. media_engine_ = cricket::MediaEngineFactory::Create();
  485. }
  486. if (!data_engine_) {
  487. // TODO(pthatcher): Make it easy to make other types of data
  488. // engines.
  489. data_engine_ = new cricket::RtpDataEngine();
  490. }
  491. media_client_ = new cricket::MediaSessionClient(
  492. xmpp_client_->jid(),
  493. session_manager_,
  494. media_engine_,
  495. data_engine_,
  496. cricket::DeviceManagerFactory::Create());
  497. media_client_->SignalCallCreate.connect(this, &CallClient::OnCallCreate);
  498. media_client_->SignalCallDestroy.connect(this, &CallClient::OnCallDestroy);
  499. media_client_->SignalDevicesChange.connect(this,
  500. &CallClient::OnDevicesChange);
  501. media_client_->set_secure(sdes_policy_);
  502. media_client_->set_multisession_enabled(multisession_enabled_);
  503. }
  504. void CallClient::OnRequestSignaling() {
  505. session_manager_->OnSignalingReady();
  506. }
  507. void CallClient::OnSessionCreate(cricket::Session* session, bool initiate) {
  508. session->set_current_protocol(signaling_protocol_);
  509. }
  510. void CallClient::OnCallCreate(cricket::Call* call) {
  511. call->SignalSessionState.connect(this, &CallClient::OnSessionState);
  512. call->SignalMediaStreamsUpdate.connect(
  513. this, &CallClient::OnMediaStreamsUpdate);
  514. }
  515. void CallClient::OnSessionState(cricket::Call* call,
  516. cricket::Session* session,
  517. cricket::Session::State state) {
  518. if (state == cricket::Session::STATE_RECEIVEDINITIATE) {
  519. buzz::Jid jid(session->remote_name());
  520. if (call_ == call && multisession_enabled_) {
  521. // We've received an initiate for an existing call. This is actually a
  522. // new session for that call.
  523. console_->PrintLine("Incoming session from '%s'", jid.Str().c_str());
  524. AddSession(session);
  525. cricket::CallOptions options;
  526. options.has_video = call_->has_video();
  527. options.has_data = data_channel_enabled_;
  528. call_->AcceptSession(session, options);
  529. if (call_->has_video() && render_) {
  530. RenderAllStreams(call, session, true);
  531. }
  532. } else {
  533. console_->PrintLine("Incoming call from '%s'", jid.Str().c_str());
  534. call_ = call;
  535. AddSession(session);
  536. incoming_call_ = true;
  537. if (call->has_video() && render_) {
  538. local_renderer_ =
  539. cricket::VideoRendererFactory::CreateGuiVideoRenderer(160, 100);
  540. }
  541. if (auto_accept_) {
  542. cricket::CallOptions options;
  543. options.has_video = true;
  544. options.has_data = data_channel_enabled_;
  545. Accept(options);
  546. }
  547. }
  548. } else if (state == cricket::Session::STATE_SENTINITIATE) {
  549. if (call->has_video() && render_) {
  550. local_renderer_ =
  551. cricket::VideoRendererFactory::CreateGuiVideoRenderer(160, 100);
  552. }
  553. console_->PrintLine("calling...");
  554. } else if (state == cricket::Session::STATE_RECEIVEDACCEPT) {
  555. console_->PrintLine("call answered");
  556. SetupAcceptedCall();
  557. } else if (state == cricket::Session::STATE_RECEIVEDREJECT) {
  558. console_->PrintLine("call not answered");
  559. } else if (state == cricket::Session::STATE_INPROGRESS) {
  560. console_->PrintLine("call in progress");
  561. call->SignalSpeakerMonitor.connect(this, &CallClient::OnSpeakerChanged);
  562. call->StartSpeakerMonitor(session);
  563. } else if (state == cricket::Session::STATE_RECEIVEDTERMINATE) {
  564. console_->PrintLine("other side terminated");
  565. TerminateAndRemoveSession(call, session->id());
  566. }
  567. }
  568. void CallClient::OnSpeakerChanged(cricket::Call* call,
  569. cricket::Session* session,
  570. const cricket::StreamParams& speaker) {
  571. if (!speaker.has_ssrcs()) {
  572. console_->PrintLine("Session %s has no current speaker.",
  573. session->id().c_str());
  574. } else if (speaker.nick.empty()) {
  575. console_->PrintLine("Session %s speaker change to unknown (%u).",
  576. session->id().c_str(), speaker.first_ssrc());
  577. } else {
  578. console_->PrintLine("Session %s speaker changed to %s (%u).",
  579. session->id().c_str(), speaker.nick.c_str(),
  580. speaker.first_ssrc());
  581. }
  582. }
  583. void SetMediaCaps(int media_caps, buzz::PresenceStatus* status) {
  584. status->set_voice_capability((media_caps & cricket::AUDIO_RECV) != 0);
  585. status->set_video_capability((media_caps & cricket::VIDEO_RECV) != 0);
  586. status->set_camera_capability((media_caps & cricket::VIDEO_SEND) != 0);
  587. }
  588. void SetCaps(int media_caps, buzz::PresenceStatus* status) {
  589. status->set_know_capabilities(true);
  590. status->set_pmuc_capability(true);
  591. SetMediaCaps(media_caps, status);
  592. }
  593. void SetAvailable(const buzz::Jid& jid, buzz::PresenceStatus* status) {
  594. status->set_jid(jid);
  595. status->set_available(true);
  596. status->set_show(buzz::PresenceStatus::SHOW_ONLINE);
  597. }
  598. void CallClient::InitPresence() {
  599. presence_push_ = new buzz::PresencePushTask(xmpp_client_, this);
  600. presence_push_->SignalStatusUpdate.connect(
  601. this, &CallClient::OnStatusUpdate);
  602. presence_push_->SignalMucJoined.connect(this, &CallClient::OnMucJoined);
  603. presence_push_->SignalMucLeft.connect(this, &CallClient::OnMucLeft);
  604. presence_push_->SignalMucStatusUpdate.connect(
  605. this, &CallClient::OnMucStatusUpdate);
  606. presence_push_->Start();
  607. presence_out_ = new buzz::PresenceOutTask(xmpp_client_);
  608. SetAvailable(xmpp_client_->jid(), &my_status_);
  609. SetCaps(media_client_->GetCapabilities(), &my_status_);
  610. SendStatus(my_status_);
  611. presence_out_->Start();
  612. muc_invite_recv_ = new buzz::MucInviteRecvTask(xmpp_client_);
  613. muc_invite_recv_->SignalInviteReceived.connect(this,
  614. &CallClient::OnMucInviteReceived);
  615. muc_invite_recv_->Start();
  616. muc_invite_send_ = new buzz::MucInviteSendTask(xmpp_client_);
  617. muc_invite_send_->Start();
  618. friend_invite_send_ = new buzz::FriendInviteSendTask(xmpp_client_);
  619. friend_invite_send_->Start();
  620. StartXmppPing();
  621. }
  622. void CallClient::StartXmppPing() {
  623. buzz::PingTask* ping = new buzz::PingTask(
  624. xmpp_client_, talk_base::Thread::Current(),
  625. kPingPeriodMillis, kPingTimeoutMillis);
  626. ping->SignalTimeout.connect(this, &CallClient::OnPingTimeout);
  627. ping->Start();
  628. }
  629. void CallClient::OnPingTimeout() {
  630. LOG(LS_WARNING) << "XMPP Ping timeout. Will keep trying...";
  631. StartXmppPing();
  632. // Or should we do this instead?
  633. // Quit();
  634. }
  635. void CallClient::SendStatus(const buzz::PresenceStatus& status) {
  636. presence_out_->Send(status);
  637. }
  638. void CallClient::OnStatusUpdate(const buzz::PresenceStatus& status) {
  639. RosterItem item;
  640. item.jid = status.jid();
  641. item.show = status.show();
  642. item.status = status.status();
  643. std::string key = item.jid.Str();
  644. if (status.available() && status.voice_capability()) {
  645. console_->PrintLine("Adding to roster: %s", key.c_str());
  646. (*roster_)[key] = item;
  647. // TODO: Make some of these constants.
  648. } else {
  649. console_->PrintLine("Removing from roster: %s", key.c_str());
  650. RosterMap::iterator iter = roster_->find(key);
  651. if (iter != roster_->end())
  652. roster_->erase(iter);
  653. }
  654. }
  655. void CallClient::PrintRoster() {
  656. console_->PrintLine("Roster contains %d callable", roster_->size());
  657. RosterMap::iterator iter = roster_->begin();
  658. while (iter != roster_->end()) {
  659. console_->PrintLine("%s - %s",
  660. iter->second.jid.BareJid().Str().c_str(),
  661. DescribeStatus(iter->second.show, iter->second.status));
  662. iter++;
  663. }
  664. }
  665. void CallClient::SendChat(const std::string& to, const std::string msg) {
  666. buzz::XmlElement* stanza = new buzz::XmlElement(buzz::QN_MESSAGE);
  667. stanza->AddAttr(buzz::QN_TO, to);
  668. stanza->AddAttr(buzz::QN_ID, talk_base::CreateRandomString(16));
  669. stanza->AddAttr(buzz::QN_TYPE, "chat");
  670. buzz::XmlElement* body = new buzz::XmlElement(buzz::QN_BODY);
  671. body->SetBodyText(msg);
  672. stanza->AddElement(body);
  673. xmpp_client_->SendStanza(stanza);
  674. delete stanza;
  675. }
  676. void CallClient::SendData(const std::string& stream_name,
  677. const std::string& text) {
  678. // TODO(mylesj): Support sending data over sessions other than the first.
  679. cricket::Session* session = GetFirstSession();
  680. if (!call_ || !session) {
  681. console_->PrintLine("Must be in a call to send data.");
  682. return;
  683. }
  684. if (!call_->has_data()) {
  685. console_->PrintLine("This call doesn't have a data channel.");
  686. return;
  687. }
  688. const cricket::DataContentDescription* data =
  689. cricket::GetFirstDataContentDescription(session->local_description());
  690. if (!data) {
  691. console_->PrintLine("This call doesn't have a data content.");
  692. return;
  693. }
  694. cricket::StreamParams stream;
  695. if (!cricket::GetStreamByNickAndName(
  696. data->streams(), "", stream_name, &stream)) {
  697. LOG(LS_WARNING) << "Could not send data: no such stream: "
  698. << stream_name << ".";
  699. return;
  700. }
  701. cricket::SendDataParams params;
  702. params.ssrc = stream.first_ssrc();
  703. call_->SendData(session, params, text);
  704. }
  705. void CallClient::InviteFriend(const std::string& name) {
  706. buzz::Jid jid(name);
  707. if (!jid.IsValid() || jid.node() == "") {
  708. console_->PrintLine("Invalid JID. JIDs should be in the form user@domain.");
  709. return;
  710. }
  711. // Note: for some reason the Buzz backend does not forward our presence
  712. // subscription requests to the end user when that user is another call
  713. // client as opposed to a Smurf user. Thus, in that scenario, you must
  714. // run the friend command as the other user too to create the linkage
  715. // (and you won't be notified to do so).
  716. friend_invite_send_->Send(jid);
  717. console_->PrintLine("Requesting to befriend %s.", name.c_str());
  718. }
  719. bool CallClient::FindJid(const std::string& name, buzz::Jid* found_jid,
  720. cricket::CallOptions* options) {
  721. bool found = false;
  722. options->is_muc = false;
  723. buzz::Jid callto_jid(name);
  724. if (name.length() == 0 && mucs_.size() > 0) {
  725. // if no name, and in a MUC, establish audio with the MUC
  726. *found_jid = mucs_.begin()->first;
  727. found = true;
  728. options->is_muc = true;
  729. } else if (name[0] == '+') {
  730. // if the first character is a +, assume it's a phone number
  731. *found_jid = callto_jid;
  732. found = true;
  733. } else {
  734. // otherwise, it's a friend
  735. for (RosterMap::iterator iter = roster_->begin();
  736. iter != roster_->end(); ++iter) {
  737. if (iter->second.jid.BareEquals(callto_jid)) {
  738. found = true;
  739. *found_jid = iter->second.jid;
  740. break;
  741. }
  742. }
  743. if (!found) {
  744. if (mucs_.count(callto_jid) == 1 &&
  745. mucs_[callto_jid]->state() == buzz::Muc::MUC_JOINED) {
  746. found = true;
  747. *found_jid = callto_jid;
  748. options->is_muc = true;
  749. }
  750. }
  751. }
  752. if (found) {
  753. console_->PrintLine("Found %s '%s'",
  754. options->is_muc ? "room" : "online friend",
  755. found_jid->Str().c_str());
  756. } else {
  757. console_->PrintLine("Could not find online friend '%s'", name.c_str());
  758. }
  759. return found;
  760. }
  761. void CallClient::OnDataReceived(cricket::Call*,
  762. const cricket::ReceiveDataParams& params,
  763. const std::string& data) {
  764. // TODO(mylesj): Support receiving data on sessions other than the first.
  765. cricket::Session* session = GetFirstSession();
  766. if (!session)
  767. return;
  768. cricket::StreamParams stream;
  769. const std::vector<cricket::StreamParams>* data_streams =
  770. call_->GetDataRecvStreams(session);
  771. if (data_streams && GetStreamBySsrc(*data_streams, params.ssrc, &stream)) {
  772. console_->PrintLine(
  773. "Received data from '%s' on stream '%s' (ssrc=%u): %s",
  774. stream.nick.c_str(), stream.name.c_str(),
  775. params.ssrc, data.c_str());
  776. } else {
  777. console_->PrintLine(
  778. "Received data (ssrc=%u): %s",
  779. params.ssrc, data.c_str());
  780. }
  781. }
  782. bool CallClient::PlaceCall(const std::string& name,
  783. cricket::CallOptions options) {
  784. buzz::Jid jid;
  785. if (!FindJid(name, &jid, &options))
  786. return false;
  787. if (!call_) {
  788. call_ = media_client_->CreateCall();
  789. AddSession(call_->InitiateSession(jid, media_client_->jid(), options));
  790. }
  791. media_client_->SetFocus(call_);
  792. if (call_->has_video() && render_) {
  793. if (!options.is_muc) {
  794. call_->SetLocalRenderer(local_renderer_);
  795. }
  796. }
  797. if (options.is_muc) {
  798. const std::string& nick = mucs_[jid]->local_jid().resource();
  799. hangout_pubsub_client_ =
  800. new buzz::HangoutPubSubClient(xmpp_client_, jid, nick);
  801. hangout_pubsub_client_->SignalPresenterStateChange.connect(
  802. this, &CallClient::OnPresenterStateChange);
  803. hangout_pubsub_client_->SignalAudioMuteStateChange.connect(
  804. this, &CallClient::OnAudioMuteStateChange);
  805. hangout_pubsub_client_->SignalRecordingStateChange.connect(
  806. this, &CallClient::OnRecordingStateChange);
  807. hangout_pubsub_client_->SignalRemoteMute.connect(
  808. this, &CallClient::OnRemoteMuted);
  809. hangout_pubsub_client_->SignalMediaBlock.connect(
  810. this, &CallClient::OnMediaBlocked);
  811. hangout_pubsub_client_->SignalRequestError.connect(
  812. this, &CallClient::OnHangoutRequestError);
  813. hangout_pubsub_client_->SignalPublishAudioMuteError.connect(
  814. this, &CallClient::OnHangoutPublishAudioMuteError);
  815. hangout_pubsub_client_->SignalPublishPresenterError.connect(
  816. this, &CallClient::OnHangoutPublishPresenterError);
  817. hangout_pubsub_client_->SignalPublishRecordingError.connect(
  818. this, &CallClient::OnHangoutPublishRecordingError);
  819. hangout_pubsub_client_->SignalRemoteMuteError.connect(
  820. this, &CallClient::OnHangoutRemoteMuteError);
  821. hangout_pubsub_client_->RequestAll();
  822. }
  823. return true;
  824. }
  825. bool CallClient::InitiateAdditionalSession(const std::string& name,
  826. cricket::CallOptions options) {
  827. // Can't add a session if there is no call yet.
  828. if (!call_)
  829. return false;
  830. buzz::Jid jid;
  831. if (!FindJid(name, &jid, &options))
  832. return false;
  833. std::vector<cricket::Session*>& call_sessions = sessions_[call_->id()];
  834. call_sessions.push_back(
  835. call_->InitiateSession(jid,
  836. buzz::Jid(call_sessions[0]->remote_name()),
  837. options));
  838. return true;
  839. }
  840. void CallClient::TerminateAndRemoveSession(cricket::Call* call,
  841. const std::string& id) {
  842. std::vector<cricket::Session*>& call_sessions = sessions_[call->id()];
  843. for (std::vector<cricket::Session*>::iterator iter = call_sessions.begin();
  844. iter != call_sessions.end(); ++iter) {
  845. if ((*iter)->id() == id) {
  846. RenderAllStreams(call, *iter, false);
  847. call_->TerminateSession(*iter);
  848. call_sessions.erase(iter);
  849. break;
  850. }
  851. }
  852. }
  853. void CallClient::PrintCalls() {
  854. const std::map<uint32, cricket::Call*>& calls = media_client_->calls();
  855. for (std::map<uint32, cricket::Call*>::const_iterator i = calls.begin();
  856. i != calls.end(); ++i) {
  857. console_->PrintLine("Call (id:%d), is %s",
  858. i->first,
  859. i->second == call_ ? "active" : "on hold");
  860. std::vector<cricket::Session *>& sessions = sessions_[call_->id()];
  861. for (std::vector<cricket::Session *>::const_iterator j = sessions.begin();
  862. j != sessions.end(); ++j) {
  863. console_->PrintLine("|--Session (id:%s), to %s", (*j)->id().c_str(),
  864. (*j)->remote_name().c_str());
  865. std::vector<cricket::StreamParams>::const_iterator k;
  866. const std::vector<cricket::StreamParams>* streams =
  867. i->second->GetAudioRecvStreams(*j);
  868. if (streams)
  869. for (k = streams->begin(); k != streams->end(); ++k) {
  870. console_->PrintLine("|----Audio Stream: %s", k->ToString().c_str());
  871. }
  872. streams = i->second->GetVideoRecvStreams(*j);
  873. if (streams)
  874. for (k = streams->begin(); k != streams->end(); ++k) {
  875. console_->PrintLine("|----Video Stream: %s", k->ToString().c_str());
  876. }
  877. streams = i->second->GetDataRecvStreams(*j);
  878. if (streams)
  879. for (k = streams->begin(); k != streams->end(); ++k) {
  880. console_->PrintLine("|----Data Stream: %s", k->ToString().c_str());
  881. }
  882. }
  883. }
  884. }
  885. void CallClient::SwitchToCall(uint32 call_id) {
  886. const std::map<uint32, cricket::Call*>& calls = media_client_->calls();
  887. std::map<uint32, cricket::Call*>::const_iterator call_iter =
  888. calls.find(call_id);
  889. if (call_iter != calls.end()) {
  890. media_client_->SetFocus(call_iter->second);
  891. call_ = call_iter->second;
  892. } else {
  893. console_->PrintLine("Unable to find call: %d", call_id);
  894. }
  895. }
  896. void CallClient::OnPresenterStateChange(
  897. const std::string& nick, bool was_presenting, bool is_presenting) {
  898. if (!was_presenting && is_presenting) {
  899. console_->PrintLine("%s now presenting.", nick.c_str());
  900. } else if (was_presenting && !is_presenting) {
  901. console_->PrintLine("%s no longer presenting.", nick.c_str());
  902. } else if (was_presenting && is_presenting) {
  903. console_->PrintLine("%s still presenting.", nick.c_str());
  904. } else if (!was_presenting && !is_presenting) {
  905. console_->PrintLine("%s still not presenting.", nick.c_str());
  906. }
  907. }
  908. void CallClient::OnAudioMuteStateChange(
  909. const std::string& nick, bool was_muted, bool is_muted) {
  910. if (!was_muted && is_muted) {
  911. console_->PrintLine("%s now muted.", nick.c_str());
  912. } else if (was_muted && !is_muted) {
  913. console_->PrintLine("%s no longer muted.", nick.c_str());
  914. }
  915. }
  916. void CallClient::OnRecordingStateChange(
  917. const std::string& nick, bool was_recording, bool is_recording) {
  918. if (!was_recording && is_recording) {
  919. console_->PrintLine("%s now recording.", nick.c_str());
  920. } else if (was_recording && !is_recording) {
  921. console_->PrintLine("%s no longer recording.", nick.c_str());
  922. }
  923. }
  924. void CallClient::OnRemoteMuted(const std::string& mutee_nick,
  925. const std::string& muter_nick,
  926. bool should_mute_locally) {
  927. if (should_mute_locally) {
  928. call_->Mute(true);
  929. console_->PrintLine("Remote muted by %s.", muter_nick.c_str());
  930. } else {
  931. console_->PrintLine("%s remote muted by %s.",
  932. mutee_nick.c_str(), muter_nick.c_str());
  933. }
  934. }
  935. void CallClient::OnMediaBlocked(const std::string& blockee_nick,
  936. const std::string& blocker_nick) {
  937. console_->PrintLine("%s blocked by %s.",
  938. blockee_nick.c_str(), blocker_nick.c_str());
  939. }
  940. void CallClient::OnHangoutRequestError(const std::string& node,
  941. const buzz::XmlElement* stanza) {
  942. console_->PrintLine("Failed request pub sub items for node %s.",
  943. node.c_str());
  944. }
  945. void CallClient::OnHangoutPublishAudioMuteError(
  946. const std::string& task_id, const buzz::XmlElement* stanza) {
  947. console_->PrintLine("Failed to publish audio mute state.");
  948. }
  949. void CallClient::OnHangoutPublishPresenterError(
  950. const std::string& task_id, const buzz::XmlElement* stanza) {
  951. console_->PrintLine("Failed to publish presenting state.");
  952. }
  953. void CallClient::OnHangoutPublishRecordingError(
  954. const std::string& task_id, const buzz::XmlElement* stanza) {
  955. console_->PrintLine("Failed to publish recording state.");
  956. }
  957. void CallClient::OnHangoutRemoteMuteError(const std::string& task_id,
  958. const std::string& mutee_nick,
  959. const buzz::XmlElement* stanza) {
  960. console_->PrintLine("Failed to remote mute.");
  961. }
  962. void CallClient::Accept(const cricket::CallOptions& options) {
  963. ASSERT(call_ && incoming_call_);
  964. ASSERT(sessions_[call_->id()].size() == 1);
  965. cricket::Session* session = GetFirstSession();
  966. call_->AcceptSession(session, options);
  967. media_client_->SetFocus(call_);
  968. if (call_->has_video() && render_) {
  969. call_->SetLocalRenderer(local_renderer_);
  970. RenderAllStreams(call_, session, true);
  971. }
  972. SetupAcceptedCall();
  973. incoming_call_ = false;
  974. }
  975. void CallClient::SetupAcceptedCall() {
  976. if (call_->has_data()) {
  977. call_->SignalDataReceived.connect(this, &CallClient::OnDataReceived);
  978. }
  979. }
  980. void CallClient::Reject() {
  981. ASSERT(call_ && incoming_call_);
  982. call_->RejectSession(call_->sessions()[0]);
  983. incoming_call_ = false;
  984. }
  985. void CallClient::Quit() {
  986. talk_base::Thread::Current()->Quit();
  987. }
  988. void CallClient::SetNick(const std::string& muc_nick) {
  989. my_status_.set_nick(muc_nick);
  990. // TODO: We might want to re-send presence, but right
  991. // now, it appears to be ignored by the MUC.
  992. //
  993. // presence_out_->Send(my_status_); for (MucMap::const_iterator itr
  994. // = mucs_.begin(); itr != mucs_.end(); ++itr) {
  995. // presence_out_->SendDirected(itr->second->local_jid(),
  996. // my_status_); }
  997. console_->PrintLine("Nick set to '%s'.", muc_nick.c_str());
  998. }
  999. void CallClient::LookupAndJoinMuc(const std::string& room_name) {
  1000. // The room_name can't be empty for lookup task.
  1001. if (room_name.empty()) {
  1002. console_->PrintLine("Please provide a room name or room jid.");
  1003. return;
  1004. }
  1005. std::string room = room_name;
  1006. std::string domain = xmpp_client_->jid().domain();
  1007. if (room_name.find("@") != std::string::npos) {
  1008. // Assume the room_name is a fully qualified room name.
  1009. // We'll find the room name string and domain name string from it.
  1010. room = room_name.substr(0, room_name.find("@"));
  1011. domain = room_name.substr(room_name.find("@") + 1);
  1012. }
  1013. buzz::MucRoomLookupTask* lookup_query_task =
  1014. buzz::MucRoomLookupTask::CreateLookupTaskForRoomName(
  1015. xmpp_client_, buzz::Jid(buzz::STR_GOOGLE_MUC_LOOKUP_JID), room,
  1016. domain);
  1017. lookup_query_task->SignalResult.connect(this,
  1018. &CallClient::OnRoomLookupResponse);
  1019. lookup_query_task->SignalError.connect(this,
  1020. &CallClient::OnRoomLookupError);
  1021. lookup_query_task->Start();
  1022. }
  1023. void CallClient::JoinMuc(const std::string& room_jid_str) {
  1024. if (room_jid_str.empty()) {
  1025. buzz::Jid room_jid = GenerateRandomMucJid();
  1026. console_->PrintLine("Generated a random room jid: %s",
  1027. room_jid.Str().c_str());
  1028. JoinMuc(room_jid);
  1029. } else {
  1030. JoinMuc(buzz::Jid(room_jid_str));
  1031. }
  1032. }
  1033. void CallClient::JoinMuc(const buzz::Jid& room_jid) {
  1034. if (!room_jid.IsValid()) {
  1035. console_->PrintLine("Unable to make valid muc endpoint for %s",
  1036. room_jid.Str().c_str());
  1037. return;
  1038. }
  1039. std::string room_nick = room_jid.resource();
  1040. if (room_nick.empty()) {
  1041. room_nick = (xmpp_client_->jid().node()
  1042. + "_" + xmpp_client_->jid().resource());
  1043. }
  1044. MucMap::iterator elem = mucs_.find(room_jid);
  1045. if (elem != mucs_.end()) {
  1046. console_->PrintLine("This MUC already exists.");
  1047. return;
  1048. }
  1049. buzz::Muc* muc = new buzz::Muc(room_jid.BareJid(), room_nick);
  1050. mucs_[muc->jid()] = muc;
  1051. presence_out_->SendDirected(muc->local_jid(), my_status_);
  1052. }
  1053. void CallClient::OnRoomLookupResponse(buzz::MucRoomLookupTask* task,
  1054. const buzz::MucRoomInfo& room) {
  1055. // The server requires the room be "configured" before being used.
  1056. // We only need to configure it if we create it, but rooms are
  1057. // auto-created at lookup, so there's currently no way to know if we
  1058. // created it. So, we configure it every time, just in case.
  1059. // Luckily, it appears to be safe to configure a room that's already
  1060. // configured. Our current flow is:
  1061. // 1. Lookup/auto-create
  1062. // 2. Configure
  1063. // 3. Join
  1064. // TODO: In the future, once the server supports it, we
  1065. // should:
  1066. // 1. Lookup
  1067. // 2. Create and Configure if necessary
  1068. // 3. Join
  1069. std::vector<std::string> room_features;
  1070. room_features.push_back(buzz::STR_MUC_ROOM_FEATURE_ENTERPRISE);
  1071. buzz::MucRoomConfigTask* room_config_task = new buzz::MucRoomConfigTask(
  1072. xmpp_client_, room.jid, room.full_name(), room_features);
  1073. room_config_task->SignalResult.connect(this,
  1074. &CallClient::OnRoomConfigResult);
  1075. room_config_task->SignalError.connect(this,
  1076. &CallClient::OnRoomConfigError);
  1077. room_config_task->Start();
  1078. }
  1079. void CallClient::OnRoomLookupError(buzz::IqTask* task,
  1080. const buzz::XmlElement* stanza) {
  1081. if (stanza == NULL) {
  1082. console_->PrintLine("Room lookup failed.");
  1083. } else {
  1084. console_->PrintLine("Room lookup error: ", stanza->Str().c_str());
  1085. }
  1086. }
  1087. void CallClient::OnRoomConfigResult(buzz::MucRoomConfigTask* task) {
  1088. JoinMuc(task->room_jid());
  1089. }
  1090. void CallClient::OnRoomConfigError(buzz::IqTask* task,
  1091. const buzz::XmlElement* stanza) {
  1092. console_->PrintLine("Room config failed.");
  1093. // We join the muc anyway, because if the room is already
  1094. // configured, the configure will fail, but we still want to join.
  1095. // Idealy, we'd know why the room config failed and only do this on
  1096. // "already configured" errors. But right now all we get back is
  1097. // "not-allowed".
  1098. buzz::MucRoomConfigTask* config_task =
  1099. static_cast<buzz::MucRoomConfigTask*>(task);
  1100. JoinMuc(config_task->room_jid());
  1101. }
  1102. void CallClient::OnMucInviteReceived(const buzz::Jid& inviter,
  1103. const buzz::Jid& room,
  1104. const std::vector<buzz::AvailableMediaEntry>& avail) {
  1105. console_->PrintLine("Invited to join %s by %s.", room.Str().c_str(),
  1106. inviter.Str().c_str());
  1107. console_->PrintLine("Available media:");
  1108. if (avail.size() > 0) {
  1109. for (std::vector<buzz::AvailableMediaEntry>::const_iterator i =
  1110. avail.begin();
  1111. i != avail.end();
  1112. ++i) {
  1113. console_->PrintLine(" %s, %s",
  1114. buzz::AvailableMediaEntry::TypeAsString(i->type),
  1115. buzz::AvailableMediaEntry::StatusAsString(i->status));
  1116. }
  1117. } else {
  1118. console_->PrintLine(" None");
  1119. }
  1120. // We automatically join the room.
  1121. JoinMuc(room);
  1122. }
  1123. void CallClient::OnMucJoined(const buzz::Jid& endpoint) {
  1124. MucMap::iterator elem = mucs_.find(endpoint);
  1125. ASSERT(elem != mucs_.end() &&
  1126. elem->second->state() == buzz::Muc::MUC_JOINING);
  1127. buzz::Muc* muc = elem->second;
  1128. muc->set_state(buzz::Muc::MUC_JOINED);
  1129. console_->PrintLine("Joined \"%s\"", muc->jid().Str().c_str());
  1130. }
  1131. void CallClient::OnMucStatusUpdate(const buzz::Jid& jid,
  1132. const buzz::MucPresenceStatus& status) {
  1133. // Look up this muc.
  1134. MucMap::iterator elem = mucs_.find(jid);
  1135. ASSERT(elem != mucs_.end());
  1136. buzz::Muc* muc = elem->second;
  1137. if (status.jid().IsBare() || status.jid() == muc->local_jid()) {
  1138. // We are only interested in status about other users.
  1139. return;
  1140. }
  1141. if (!status.available()) {
  1142. // Remove them from the room.
  1143. muc->members().erase(status.jid().resource());
  1144. }
  1145. }
  1146. bool CallClient::InMuc() {
  1147. const buzz::Jid* muc_jid = FirstMucJid();
  1148. if (!muc_jid) return false;
  1149. return muc_jid->IsValid();
  1150. }
  1151. const buzz::Jid* CallClient::FirstMucJid() {
  1152. if (mucs_.empty()) return NULL;
  1153. return &(mucs_.begin()->first);
  1154. }
  1155. void CallClient::LeaveMuc(const std::string& room) {
  1156. buzz::Jid room_jid;
  1157. const buzz::Jid* muc_jid = FirstMucJid();
  1158. if (room.length() > 0) {
  1159. room_jid = buzz::Jid(room);
  1160. } else if (mucs_.size() > 0) {
  1161. // leave the first MUC if no JID specified
  1162. if (muc_jid) {
  1163. room_jid = *(muc_jid);
  1164. }
  1165. }
  1166. if (!room_jid.IsValid()) {
  1167. console_->PrintLine("Invalid MUC JID.");
  1168. return;
  1169. }
  1170. MucMap::iterator elem = mucs_.find(room_jid);
  1171. if (elem == mucs_.end()) {
  1172. console_->PrintLine("No such MUC.");
  1173. return;
  1174. }
  1175. buzz::Muc* muc = elem->second;
  1176. muc->set_state(buzz::Muc::MUC_LEAVING);
  1177. buzz::PresenceStatus status;
  1178. status.set_jid(my_status_.jid());
  1179. status.set_available(false);
  1180. status.set_priority(0);
  1181. presence_out_->SendDirected(muc->local_jid(), status);
  1182. }
  1183. void CallClient::OnMucLeft(const buzz::Jid& endpoint, int error) {
  1184. // We could be kicked from a room from any state. We would hope this
  1185. // happens While in the MUC_LEAVING state
  1186. MucMap::iterator elem = mucs_.find(endpoint);
  1187. if (elem == mucs_.end())
  1188. return;
  1189. buzz::Muc* muc = elem->second;
  1190. if (muc->state() == buzz::Muc::MUC_JOINING) {
  1191. console_->PrintLine("Failed to join \"%s\", code=%d",
  1192. muc->jid().Str().c_str(), error);
  1193. } else if (muc->state() == buzz::Muc::MUC_JOINED) {
  1194. console_->PrintLine("Kicked from \"%s\"",
  1195. muc->jid().Str().c_str());
  1196. }
  1197. delete muc;
  1198. mucs_.erase(elem);
  1199. }
  1200. void CallClient::InviteToMuc(const std::string& given_user,
  1201. const std::string& room) {
  1202. std::string user = given_user;
  1203. // First find the room.
  1204. const buzz::Muc* found_muc;
  1205. if (room.length() == 0) {
  1206. if (mucs_.size() == 0) {
  1207. console_->PrintLine("Not in a room yet; can't invite.");
  1208. return;
  1209. }
  1210. // Invite to the first muc
  1211. found_muc = mucs_.begin()->second;
  1212. } else {
  1213. MucMap::iterator elem = mucs_.find(buzz::Jid(room));
  1214. if (elem == mucs_.end()) {
  1215. console_->PrintLine("Not in room %s.", room.c_str());
  1216. return;
  1217. }
  1218. found_muc = elem->second;
  1219. }
  1220. buzz::Jid invite_to = found_muc->jid();
  1221. // Now find the user. We invite all of their resources.
  1222. bool found_user = false;
  1223. buzz::Jid user_jid(user);
  1224. for (RosterMap::iterator iter = roster_->begin();
  1225. iter != roster_->end(); ++iter) {
  1226. if (iter->second.jid.BareEquals(user_jid)) {
  1227. buzz::Jid invitee = iter->second.jid;
  1228. muc_invite_send_->Send(invite_to, invitee);
  1229. found_user = true;
  1230. }
  1231. }
  1232. if (!found_user) {
  1233. buzz::Jid invitee = user_jid;
  1234. muc_invite_send_->Send(invite_to, invitee);
  1235. }
  1236. }
  1237. void CallClient::GetDevices() {
  1238. std::vector<std::string> names;
  1239. media_client_->GetAudioInputDevices(&names);
  1240. console_->PrintLine("Audio input devices:");
  1241. PrintDevices(names);
  1242. media_client_->GetAudioOutputDevices(&names);
  1243. console_->PrintLine("Audio output devices:");
  1244. PrintDevices(names);
  1245. media_client_->GetVideoCaptureDevices(&names);
  1246. console_->PrintLine("Video capture devices:");
  1247. PrintDevices(names);
  1248. }
  1249. void CallClient::PrintDevices(const std::vector<std::string>& names) {
  1250. for (size_t i = 0; i < names.size(); ++i) {
  1251. console_->PrintLine("%d: %s", static_cast<int>(i), names[i].c_str());
  1252. }
  1253. }
  1254. void CallClient::OnDevicesChange() {
  1255. console_->PrintLine("Devices changed.");
  1256. SetMediaCaps(media_client_->GetCapabilities(), &my_status_);
  1257. SendStatus(my_status_);
  1258. }
  1259. void CallClient::SetVolume(const std::string& level) {
  1260. media_client_->SetOutputVolume(strtol(level.c_str(), NULL, 10));
  1261. }
  1262. void CallClient::OnMediaStreamsUpdate(cricket::Call* call,
  1263. cricket::Session* session,
  1264. const cricket::MediaStreams& added,
  1265. const cricket::MediaStreams& removed) {
  1266. if (call && call->has_video()) {
  1267. for (std::vector<cricket::StreamParams>::const_iterator
  1268. it = removed.video().begin(); it != removed.video().end(); ++it) {
  1269. RemoveStaticRenderedView(it->first_ssrc());
  1270. }
  1271. if (render_) {
  1272. RenderStreams(call, session, added.video(), true);
  1273. }
  1274. SendViewRequest(call, session);
  1275. }
  1276. }
  1277. void CallClient::RenderAllStreams(cricket::Call* call,
  1278. cricket::Session* session,
  1279. bool enable) {
  1280. const std::vector<cricket::StreamParams>* video_streams =
  1281. call->GetVideoRecvStreams(session);
  1282. if (video_streams) {
  1283. RenderStreams(call, session, *video_streams, enable);
  1284. }
  1285. }
  1286. void CallClient::RenderStreams(
  1287. cricket::Call* call,
  1288. cricket::Session* session,
  1289. const std::vector<cricket::StreamParams>& video_streams,
  1290. bool enable) {
  1291. std::vector<cricket::StreamParams>::const_iterator stream;
  1292. for (stream = video_streams.begin(); stream != video_streams.end();
  1293. ++stream) {
  1294. RenderStream(call, session, *stream, enable);
  1295. }
  1296. }
  1297. void CallClient::RenderStream(cricket::Call* call,
  1298. cricket::Session* session,
  1299. const cricket::StreamParams& stream,
  1300. bool enable) {
  1301. if (!stream.has_ssrcs()) {
  1302. // Nothing to see here; move along.
  1303. return;
  1304. }
  1305. uint32 ssrc = stream.first_ssrc();
  1306. StaticRenderedViews::iterator iter =
  1307. static_rendered_views_.find(std::make_pair(session, ssrc));
  1308. if (enable) {
  1309. if (iter == static_rendered_views_.end()) {
  1310. // TODO(pthatcher): Make dimensions and positions more configurable.
  1311. int offset = (50 * static_views_accumulated_count_) % 300;
  1312. AddStaticRenderedView(session, ssrc, 640, 400, 30,
  1313. offset, offset);
  1314. // Should have it now.
  1315. iter = static_rendered_views_.find(std::make_pair(session, ssrc));
  1316. }
  1317. call->SetVideoRenderer(session, ssrc, iter->second.renderer);
  1318. } else {
  1319. if (iter != static_rendered_views_.end()) {
  1320. call->SetVideoRenderer(session, ssrc, NULL);
  1321. RemoveStaticRenderedView(ssrc);
  1322. }
  1323. }
  1324. }
  1325. // TODO: Would these methods to add and remove views make
  1326. // more sense in call.cc? Would other clients use them?
  1327. void CallClient::AddStaticRenderedView(
  1328. cricket::Session* session,
  1329. uint32 ssrc, int width, int height, int framerate,
  1330. int x_offset, int y_offset) {
  1331. StaticRenderedView rendered_view(
  1332. cricket::StaticVideoView(ssrc, width, height, framerate),
  1333. cricket::VideoRendererFactory::CreateGuiVideoRenderer(
  1334. x_offset, y_offset));
  1335. rendered_view.renderer->SetSize(width, height, 0);
  1336. static_rendered_views_.insert(std::make_pair(std::make_pair(session, ssrc),
  1337. rendered_view));
  1338. ++static_views_accumulated_count_;
  1339. console_->PrintLine("Added renderer for ssrc %d", ssrc);
  1340. }
  1341. bool CallClient::RemoveStaticRenderedView(uint32 ssrc) {
  1342. for (StaticRenderedViews::iterator it = static_rendered_views_.begin();
  1343. it != static_rendered_views_.end(); ++it) {
  1344. if (it->second.view.ssrc == ssrc) {
  1345. delete it->second.renderer;
  1346. static_rendered_views_.erase(it);
  1347. console_->PrintLine("Removed renderer for ssrc %d", ssrc);
  1348. return true;
  1349. }
  1350. }
  1351. return false;
  1352. }
  1353. void CallClient::RemoveCallsStaticRenderedViews(cricket::Call* call) {
  1354. std::vector<cricket::Session*>& sessions = sessions_[call->id()];
  1355. std::set<cricket::Session*> call_sessions(sessions.begin(), sessions.end());
  1356. for (StaticRenderedViews::iterator it = static_rendered_views_.begin();
  1357. it != static_rendered_views_.end(); ) {
  1358. if (call_sessions.find(it->first.first) != call_sessions.end()) {
  1359. delete it->second.renderer;
  1360. static_rendered_views_.erase(it++);
  1361. } else {
  1362. ++it;
  1363. }
  1364. }
  1365. }
  1366. void CallClient::SendViewRequest(cricket::Call* call,
  1367. cricket::Session* session) {
  1368. cricket::ViewRequest request;
  1369. for (StaticRenderedViews::iterator it = static_rendered_views_.begin();
  1370. it != static_rendered_views_.end(); ++it) {
  1371. if (it->first.first == session) {
  1372. request.static_video_views.push_back(it->second.view);
  1373. }
  1374. }
  1375. call->SendViewRequest(session, request);
  1376. }
  1377. buzz::Jid CallClient::GenerateRandomMucJid() {
  1378. // Generate a GUID of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX,
  1379. // for an eventual JID of private-chat-<GUID>@groupchat.google.com.
  1380. char guid[37], guid_room[256];
  1381. for (size_t i = 0; i < ARRAY_SIZE(guid) - 1;) {
  1382. if (i == 8 || i == 13 || i == 18 || i == 23) {
  1383. guid[i++] = '-';
  1384. } else {
  1385. sprintf(guid + i, "%04x", rand());
  1386. i += 4;
  1387. }
  1388. }
  1389. talk_base::sprintfn(guid_room,
  1390. ARRAY_SIZE(guid_room),
  1391. "private-chat-%s@%s",
  1392. guid,
  1393. pmuc_domain_.c_str());
  1394. return buzz::Jid(guid_room);
  1395. }
  1396. bool CallClient::SelectFirstDesktopScreencastId(
  1397. cricket::ScreencastId* screencastid) {
  1398. if (!talk_base::WindowPickerFactory::IsSupported()) {
  1399. LOG(LS_WARNING) << "Window picker not suported on this OS.";
  1400. return false;
  1401. }
  1402. talk_base::WindowPicker* picker =
  1403. talk_base::WindowPickerFactory::CreateWindowPicker();
  1404. if (!picker) {
  1405. LOG(LS_WARNING) << "Could not create a window picker.";
  1406. return false;
  1407. }
  1408. talk_base::DesktopDescriptionList desktops;
  1409. if (!picker->GetDesktopList(&desktops) || desktops.empty()) {
  1410. LOG(LS_WARNING) << "Could not get a list of desktops.";
  1411. return false;
  1412. }
  1413. *screencastid = cricket::ScreencastId(desktops[0].id());
  1414. return true;
  1415. }
  1416. void CallClient::PrintStats() const {
  1417. const cricket::VoiceMediaInfo& vmi = call_->last_voice_media_info();
  1418. for (std::vector<cricket::VoiceSenderInfo>::const_iterator it =
  1419. vmi.senders.begin(); it != vmi.senders.end(); ++it) {
  1420. console_->PrintLine("Sender: ssrc=%u codec='%s' bytes=%d packets=%d "
  1421. "rtt=%d jitter=%d",
  1422. it->ssrc, it->codec_name.c_str(), it->bytes_sent,
  1423. it->packets_sent, it->rtt_ms, it->jitter_ms);
  1424. }
  1425. for (std::vector<cricket::VoiceReceiverInfo>::const_iterator it =
  1426. vmi.receivers.begin(); it != vmi.receivers.end(); ++it) {
  1427. console_->PrintLine("Receiver: ssrc=%u bytes=%d packets=%d "
  1428. "jitter=%d loss=%.2f",
  1429. it->ssrc, it->bytes_rcvd, it->packets_rcvd,
  1430. it->jitter_ms, it->fraction_lost);
  1431. }
  1432. }