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.

490 lines
15 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2012, 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/peerconnection/client/conductor.h"
  28. #include <utility>
  29. #include "talk/base/common.h"
  30. #include "talk/base/json.h"
  31. #include "talk/base/logging.h"
  32. #include "talk/examples/peerconnection/client/defaults.h"
  33. #include "talk/media/devices/devicemanager.h"
  34. // Names used for a IceCandidate JSON object.
  35. const char kCandidateSdpMidName[] = "sdpMid";
  36. const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex";
  37. const char kCandidateSdpName[] = "candidate";
  38. // Names used for a SessionDescription JSON object.
  39. const char kSessionDescriptionTypeName[] = "type";
  40. const char kSessionDescriptionSdpName[] = "sdp";
  41. class DummySetSessionDescriptionObserver
  42. : public webrtc::SetSessionDescriptionObserver {
  43. public:
  44. static DummySetSessionDescriptionObserver* Create() {
  45. return
  46. new talk_base::RefCountedObject<DummySetSessionDescriptionObserver>();
  47. }
  48. virtual void OnSuccess() {
  49. LOG(INFO) << __FUNCTION__;
  50. }
  51. virtual void OnFailure(const std::string& error) {
  52. LOG(INFO) << __FUNCTION__ << " " << error;
  53. }
  54. protected:
  55. DummySetSessionDescriptionObserver() {}
  56. ~DummySetSessionDescriptionObserver() {}
  57. };
  58. Conductor::Conductor(PeerConnectionClient* client, MainWindow* main_wnd)
  59. : peer_id_(-1),
  60. client_(client),
  61. main_wnd_(main_wnd) {
  62. client_->RegisterObserver(this);
  63. main_wnd->RegisterObserver(this);
  64. }
  65. Conductor::~Conductor() {
  66. ASSERT(peer_connection_.get() == NULL);
  67. }
  68. bool Conductor::connection_active() const {
  69. return peer_connection_.get() != NULL;
  70. }
  71. void Conductor::Close() {
  72. client_->SignOut();
  73. DeletePeerConnection();
  74. }
  75. bool Conductor::InitializePeerConnection() {
  76. ASSERT(peer_connection_factory_.get() == NULL);
  77. ASSERT(peer_connection_.get() == NULL);
  78. peer_connection_factory_ = webrtc::CreatePeerConnectionFactory();
  79. if (!peer_connection_factory_.get()) {
  80. main_wnd_->MessageBox("Error",
  81. "Failed to initialize PeerConnectionFactory", true);
  82. DeletePeerConnection();
  83. return false;
  84. }
  85. webrtc::JsepInterface::IceServers servers;
  86. webrtc::JsepInterface::IceServer server;
  87. server.uri = GetPeerConnectionString();
  88. servers.push_back(server);
  89. peer_connection_ = peer_connection_factory_->CreatePeerConnection(servers,
  90. NULL,
  91. this);
  92. if (!peer_connection_.get()) {
  93. main_wnd_->MessageBox("Error",
  94. "CreatePeerConnection failed", true);
  95. DeletePeerConnection();
  96. }
  97. AddStreams();
  98. return peer_connection_.get() != NULL;
  99. }
  100. void Conductor::DeletePeerConnection() {
  101. peer_connection_ = NULL;
  102. active_streams_.clear();
  103. main_wnd_->StopLocalRenderer();
  104. main_wnd_->StopRemoteRenderer();
  105. peer_connection_factory_ = NULL;
  106. peer_id_ = -1;
  107. }
  108. void Conductor::EnsureStreamingUI() {
  109. ASSERT(peer_connection_.get() != NULL);
  110. if (main_wnd_->IsWindow()) {
  111. if (main_wnd_->current_ui() != MainWindow::STREAMING)
  112. main_wnd_->SwitchToStreamingUI();
  113. }
  114. }
  115. //
  116. // PeerConnectionObserver implementation.
  117. //
  118. void Conductor::OnError() {
  119. LOG(LS_ERROR) << __FUNCTION__;
  120. main_wnd_->QueueUIThreadCallback(PEER_CONNECTION_ERROR, NULL);
  121. }
  122. // Called when a remote stream is added
  123. void Conductor::OnAddStream(webrtc::MediaStreamInterface* stream) {
  124. LOG(INFO) << __FUNCTION__ << " " << stream->label();
  125. stream->AddRef();
  126. main_wnd_->QueueUIThreadCallback(NEW_STREAM_ADDED,
  127. stream);
  128. }
  129. void Conductor::OnRemoveStream(webrtc::MediaStreamInterface* stream) {
  130. LOG(INFO) << __FUNCTION__ << " " << stream->label();
  131. stream->AddRef();
  132. main_wnd_->QueueUIThreadCallback(STREAM_REMOVED,
  133. stream);
  134. }
  135. void Conductor::OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
  136. LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index();
  137. Json::StyledWriter writer;
  138. Json::Value jmessage;
  139. jmessage[kCandidateSdpMidName] = candidate->sdp_mid();
  140. jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index();
  141. std::string sdp;
  142. if (!candidate->ToString(&sdp)) {
  143. LOG(LS_ERROR) << "Failed to serialize candidate";
  144. return;
  145. }
  146. jmessage[kCandidateSdpName] = sdp;
  147. SendMessage(writer.write(jmessage));
  148. }
  149. //
  150. // PeerConnectionClientObserver implementation.
  151. //
  152. void Conductor::OnSignedIn() {
  153. LOG(INFO) << __FUNCTION__;
  154. main_wnd_->SwitchToPeerList(client_->peers());
  155. }
  156. void Conductor::OnDisconnected() {
  157. LOG(INFO) << __FUNCTION__;
  158. DeletePeerConnection();
  159. if (main_wnd_->IsWindow())
  160. main_wnd_->SwitchToConnectUI();
  161. }
  162. void Conductor::OnPeerConnected(int id, const std::string& name) {
  163. LOG(INFO) << __FUNCTION__;
  164. // Refresh the list if we're showing it.
  165. if (main_wnd_->current_ui() == MainWindow::LIST_PEERS)
  166. main_wnd_->SwitchToPeerList(client_->peers());
  167. }
  168. void Conductor::OnPeerDisconnected(int id) {
  169. LOG(INFO) << __FUNCTION__;
  170. if (id == peer_id_) {
  171. LOG(INFO) << "Our peer disconnected";
  172. main_wnd_->QueueUIThreadCallback(PEER_CONNECTION_CLOSED, NULL);
  173. } else {
  174. // Refresh the list if we're showing it.
  175. if (main_wnd_->current_ui() == MainWindow::LIST_PEERS)
  176. main_wnd_->SwitchToPeerList(client_->peers());
  177. }
  178. }
  179. void Conductor::OnMessageFromPeer(int peer_id, const std::string& message) {
  180. ASSERT(peer_id_ == peer_id || peer_id_ == -1);
  181. ASSERT(!message.empty());
  182. if (!peer_connection_.get()) {
  183. ASSERT(peer_id_ == -1);
  184. peer_id_ = peer_id;
  185. if (!InitializePeerConnection()) {
  186. LOG(LS_ERROR) << "Failed to initialize our PeerConnection instance";
  187. client_->SignOut();
  188. return;
  189. }
  190. } else if (peer_id != peer_id_) {
  191. ASSERT(peer_id_ != -1);
  192. LOG(WARNING) << "Received a message from unknown peer while already in a "
  193. "conversation with a different peer.";
  194. return;
  195. }
  196. Json::Reader reader;
  197. Json::Value jmessage;
  198. if (!reader.parse(message, jmessage)) {
  199. LOG(WARNING) << "Received unknown message. " << message;
  200. return;
  201. }
  202. std::string type;
  203. std::string json_object;
  204. GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type);
  205. if (!type.empty()) {
  206. std::string sdp;
  207. if (!GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp)) {
  208. LOG(WARNING) << "Can't parse received session description message.";
  209. return;
  210. }
  211. webrtc::SessionDescriptionInterface* session_description(
  212. webrtc::CreateSessionDescription(type, sdp));
  213. if (!session_description) {
  214. LOG(WARNING) << "Can't parse received session description message.";
  215. return;
  216. }
  217. LOG(INFO) << " Received session description :" << message;
  218. peer_connection_->SetRemoteDescription(
  219. DummySetSessionDescriptionObserver::Create(), session_description);
  220. if (session_description->type() ==
  221. webrtc::SessionDescriptionInterface::kOffer) {
  222. peer_connection_->CreateAnswer(this, NULL);
  223. }
  224. return;
  225. } else {
  226. std::string sdp_mid;
  227. int sdp_mlineindex = 0;
  228. std::string sdp;
  229. if (!GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid) ||
  230. !GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName,
  231. &sdp_mlineindex) ||
  232. !GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) {
  233. LOG(WARNING) << "Can't parse received message.";
  234. return;
  235. }
  236. talk_base::scoped_ptr<webrtc::IceCandidateInterface> candidate(
  237. webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp));
  238. if (!candidate.get()) {
  239. LOG(WARNING) << "Can't parse received candidate message.";
  240. return;
  241. }
  242. if (!peer_connection_->AddIceCandidate(candidate.get())) {
  243. LOG(WARNING) << "Failed to apply the received candidate";
  244. return;
  245. }
  246. LOG(INFO) << " Received candidate :" << message;
  247. return;
  248. }
  249. }
  250. void Conductor::OnMessageSent(int err) {
  251. // Process the next pending message if any.
  252. main_wnd_->QueueUIThreadCallback(SEND_MESSAGE_TO_PEER, NULL);
  253. }
  254. void Conductor::OnServerConnectionFailure() {
  255. main_wnd_->MessageBox("Error", ("Failed to connect to " + server_).c_str(),
  256. true);
  257. }
  258. //
  259. // MainWndCallback implementation.
  260. //
  261. void Conductor::StartLogin(const std::string& server, int port) {
  262. if (client_->is_connected())
  263. return;
  264. server_ = server;
  265. client_->Connect(server, port, GetPeerName());
  266. }
  267. void Conductor::DisconnectFromServer() {
  268. if (client_->is_connected())
  269. client_->SignOut();
  270. }
  271. void Conductor::ConnectToPeer(int peer_id) {
  272. ASSERT(peer_id_ == -1);
  273. ASSERT(peer_id != -1);
  274. if (peer_connection_.get()) {
  275. main_wnd_->MessageBox("Error",
  276. "We only support connecting to one peer at a time", true);
  277. return;
  278. }
  279. if (InitializePeerConnection()) {
  280. peer_id_ = peer_id;
  281. peer_connection_->CreateOffer(this, NULL);
  282. } else {
  283. main_wnd_->MessageBox("Error", "Failed to initialize PeerConnection", true);
  284. }
  285. }
  286. cricket::VideoCapturer* Conductor::OpenVideoCaptureDevice() {
  287. talk_base::scoped_ptr<cricket::DeviceManagerInterface> dev_manager(
  288. cricket::DeviceManagerFactory::Create());
  289. if (!dev_manager->Init()) {
  290. LOG(LS_ERROR) << "Can't create device manager";
  291. return NULL;
  292. }
  293. std::vector<cricket::Device> devs;
  294. if (!dev_manager->GetVideoCaptureDevices(&devs)) {
  295. LOG(LS_ERROR) << "Can't enumerate video devices";
  296. return NULL;
  297. }
  298. std::vector<cricket::Device>::iterator dev_it = devs.begin();
  299. cricket::VideoCapturer* capturer = NULL;
  300. for (; dev_it != devs.end(); ++dev_it) {
  301. capturer = dev_manager->CreateVideoCapturer(*dev_it);
  302. if (capturer != NULL)
  303. break;
  304. }
  305. return capturer;
  306. }
  307. void Conductor::AddStreams() {
  308. if (active_streams_.find(kStreamLabel) != active_streams_.end())
  309. return; // Already added.
  310. talk_base::scoped_refptr<webrtc::LocalAudioTrackInterface> audio_track(
  311. peer_connection_factory_->CreateLocalAudioTrack(kAudioLabel, NULL));
  312. talk_base::scoped_refptr<webrtc::LocalVideoTrackInterface> video_track(
  313. peer_connection_factory_->CreateLocalVideoTrack(
  314. kVideoLabel, OpenVideoCaptureDevice()));
  315. main_wnd_->StartLocalRenderer(video_track);
  316. talk_base::scoped_refptr<webrtc::LocalMediaStreamInterface> stream =
  317. peer_connection_factory_->CreateLocalMediaStream(kStreamLabel);
  318. stream->AddTrack(audio_track);
  319. stream->AddTrack(video_track);
  320. if (!peer_connection_->AddStream(stream, NULL)) {
  321. LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
  322. }
  323. typedef std::pair<std::string,
  324. talk_base::scoped_refptr<webrtc::MediaStreamInterface> >
  325. MediaStreamPair;
  326. active_streams_.insert(MediaStreamPair(stream->label(), stream));
  327. main_wnd_->SwitchToStreamingUI();
  328. }
  329. void Conductor::DisconnectFromCurrentPeer() {
  330. LOG(INFO) << __FUNCTION__;
  331. if (peer_connection_.get()) {
  332. client_->SendHangUp(peer_id_);
  333. DeletePeerConnection();
  334. }
  335. if (main_wnd_->IsWindow())
  336. main_wnd_->SwitchToPeerList(client_->peers());
  337. }
  338. void Conductor::UIThreadCallback(int msg_id, void* data) {
  339. switch (msg_id) {
  340. case PEER_CONNECTION_CLOSED:
  341. LOG(INFO) << "PEER_CONNECTION_CLOSED";
  342. DeletePeerConnection();
  343. ASSERT(active_streams_.empty());
  344. if (main_wnd_->IsWindow()) {
  345. if (client_->is_connected()) {
  346. main_wnd_->SwitchToPeerList(client_->peers());
  347. } else {
  348. main_wnd_->SwitchToConnectUI();
  349. }
  350. } else {
  351. DisconnectFromServer();
  352. }
  353. break;
  354. case SEND_MESSAGE_TO_PEER: {
  355. LOG(INFO) << "SEND_MESSAGE_TO_PEER";
  356. std::string* msg = reinterpret_cast<std::string*>(data);
  357. if (msg) {
  358. // For convenience, we always run the message through the queue.
  359. // This way we can be sure that messages are sent to the server
  360. // in the same order they were signaled without much hassle.
  361. pending_messages_.push_back(msg);
  362. }
  363. if (!pending_messages_.empty() && !client_->IsSendingMessage()) {
  364. msg = pending_messages_.front();
  365. pending_messages_.pop_front();
  366. if (!client_->SendToPeer(peer_id_, *msg) && peer_id_ != -1) {
  367. LOG(LS_ERROR) << "SendToPeer failed";
  368. DisconnectFromServer();
  369. }
  370. delete msg;
  371. }
  372. if (!peer_connection_.get())
  373. peer_id_ = -1;
  374. break;
  375. }
  376. case PEER_CONNECTION_ERROR:
  377. main_wnd_->MessageBox("Error", "an unknown error occurred", true);
  378. break;
  379. case NEW_STREAM_ADDED: {
  380. webrtc::MediaStreamInterface* stream =
  381. reinterpret_cast<webrtc::MediaStreamInterface*>(
  382. data);
  383. talk_base::scoped_refptr<webrtc::VideoTracks> tracks =
  384. stream->video_tracks();
  385. // Only render the first track.
  386. if (tracks->count() > 0) {
  387. webrtc::VideoTrackInterface* track = tracks->at(0);
  388. main_wnd_->StartRemoteRenderer(track);
  389. }
  390. stream->Release();
  391. break;
  392. }
  393. case STREAM_REMOVED: {
  394. // Remote peer stopped sending a stream.
  395. webrtc::MediaStreamInterface* stream =
  396. reinterpret_cast<webrtc::MediaStreamInterface*>(
  397. data);
  398. stream->Release();
  399. break;
  400. }
  401. default:
  402. ASSERT(false);
  403. break;
  404. }
  405. }
  406. void Conductor::OnSuccess(webrtc::SessionDescriptionInterface* desc) {
  407. peer_connection_->SetLocalDescription(
  408. DummySetSessionDescriptionObserver::Create(), desc);
  409. Json::StyledWriter writer;
  410. Json::Value jmessage;
  411. jmessage[kSessionDescriptionTypeName] = desc->type();
  412. std::string sdp;
  413. desc->ToString(&sdp);
  414. jmessage[kSessionDescriptionSdpName] = sdp;
  415. SendMessage(writer.write(jmessage));
  416. }
  417. void Conductor::OnFailure(const std::string& error) {
  418. LOG(LERROR) << error;
  419. }
  420. void Conductor::SendMessage(const std::string& json_object) {
  421. std::string* msg = new std::string(json_object);
  422. main_wnd_->QueueUIThreadCallback(SEND_MESSAGE_TO_PEER, msg);
  423. }