1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "camera_streamer.h"
17
18 #include <android-base/logging.h>
19 #include <chrono>
20 #include "common/libs/utils/vsock_connection.h"
21
22 namespace cuttlefish {
23 namespace webrtc_streaming {
24
CameraStreamer(unsigned int port,unsigned int cid)25 CameraStreamer::CameraStreamer(unsigned int port, unsigned int cid)
26 : cid_(cid), port_(port), camera_session_active_(false) {}
27
~CameraStreamer()28 CameraStreamer::~CameraStreamer() { Disconnect(); }
29
30 // We are getting frames from the client so try forwarding those to the CVD
OnFrame(const webrtc::VideoFrame & client_frame)31 void CameraStreamer::OnFrame(const webrtc::VideoFrame& client_frame) {
32 std::lock_guard<std::mutex> lock(onframe_mutex_);
33 if (!cvd_connection_.IsConnected() && !pending_connection_.valid()) {
34 // Start new connection
35 pending_connection_ = cvd_connection_.ConnectAsync(port_, cid_);
36 return;
37 } else if (pending_connection_.valid()) {
38 if (!IsConnectionReady()) {
39 return;
40 }
41 std::lock_guard<std::mutex> lock(settings_mutex_);
42 if (!cvd_connection_.WriteMessage(settings_buffer_)) {
43 LOG(ERROR) << "Failed writing camera settings:";
44 return;
45 }
46 StartReadLoop();
47 LOG(INFO) << "Connected!";
48 }
49 auto resolution = resolution_.load();
50 if (resolution.height <= 0 || resolution.width <= 0 ||
51 !camera_session_active_.load()) {
52 // Nobody is receiving frames or we don't have a valid resolution that is
53 // necessary for potential frame scaling
54 return;
55 }
56 auto frame = client_frame.video_frame_buffer()->ToI420().get();
57 if (frame->width() != resolution.width ||
58 frame->height() != resolution.height) {
59 // incoming resolution does not match with the resolution we
60 // have communicated to the CVD - scaling required
61 if (!scaled_frame_ || resolution.width != scaled_frame_->width() ||
62 resolution.height != scaled_frame_->height()) {
63 scaled_frame_ =
64 webrtc::I420Buffer::Create(resolution.width, resolution.height);
65 }
66 scaled_frame_->CropAndScaleFrom(*frame);
67 frame = scaled_frame_.get();
68 }
69 if (!VsockSendYUVFrame(frame)) {
70 LOG(ERROR) << "Sending frame over vsock failed";
71 }
72 }
73
74 // Handle message json coming from client
HandleMessage(const Json::Value & message)75 void CameraStreamer::HandleMessage(const Json::Value& message) {
76 auto command = message["command"].asString();
77 if (command == "camera_settings") {
78 // save local copy of resolution that is required for frame scaling
79 resolution_ = GetResolutionFromSettings(message);
80 Json::StreamWriterBuilder factory;
81 std::string new_settings = Json::writeString(factory, message);
82 if (!settings_buffer_.empty() && new_settings != settings_buffer_) {
83 // Settings have changed - disconnect
84 // Next incoming frames will trigger re-connection
85 Disconnect();
86 }
87 std::lock_guard<std::mutex> lock(settings_mutex_);
88 settings_buffer_ = new_settings;
89 LOG(INFO) << "New camera settings received:" << new_settings;
90 }
91 }
92
93 // Handle binary blobs coming from client
HandleMessage(const std::vector<char> & message)94 void CameraStreamer::HandleMessage(const std::vector<char>& message) {
95 LOG(INFO) << "Pass through " << message.size() << "bytes";
96 std::lock_guard<std::mutex> lock(frame_mutex_);
97 cvd_connection_.WriteMessage(message);
98 }
99
GetResolutionFromSettings(const Json::Value & settings)100 CameraStreamer::Resolution CameraStreamer::GetResolutionFromSettings(
101 const Json::Value& settings) {
102 return {.width = settings["width"].asInt(),
103 .height = settings["height"].asInt()};
104 }
105
VsockSendYUVFrame(const webrtc::I420BufferInterface * frame)106 bool CameraStreamer::VsockSendYUVFrame(
107 const webrtc::I420BufferInterface* frame) {
108 int32_t size = frame->width() * frame->height() +
109 2 * frame->ChromaWidth() * frame->ChromaHeight();
110 const char* y = reinterpret_cast<const char*>(frame->DataY());
111 const char* u = reinterpret_cast<const char*>(frame->DataU());
112 const char* v = reinterpret_cast<const char*>(frame->DataV());
113 auto chroma_width = frame->ChromaWidth();
114 auto chroma_height = frame->ChromaHeight();
115 std::lock_guard<std::mutex> lock(frame_mutex_);
116 return cvd_connection_.Write(size) &&
117 cvd_connection_.WriteStrides(y, frame->width(), frame->height(),
118 frame->StrideY()) &&
119 cvd_connection_.WriteStrides(u, chroma_width, chroma_height,
120 frame->StrideU()) &&
121 cvd_connection_.WriteStrides(v, chroma_width, chroma_height,
122 frame->StrideV());
123 }
124
IsConnectionReady()125 bool CameraStreamer::IsConnectionReady() {
126 if (!pending_connection_.valid()) {
127 return cvd_connection_.IsConnected();
128 } else if (pending_connection_.wait_for(std::chrono::seconds(0)) !=
129 std::future_status::ready) {
130 // Still waiting for connection
131 return false;
132 } else if (settings_buffer_.empty()) {
133 // connection is ready but we have not yet received client
134 // camera settings
135 return false;
136 }
137 return pending_connection_.get();
138 }
139
StartReadLoop()140 void CameraStreamer::StartReadLoop() {
141 if (reader_thread_.joinable()) {
142 reader_thread_.join();
143 }
144 reader_thread_ = std::thread([this] {
145 while (cvd_connection_.IsConnected()) {
146 static constexpr auto kEventKey = "event";
147 static constexpr auto kMessageStart =
148 "VIRTUAL_DEVICE_START_CAMERA_SESSION";
149 static constexpr auto kMessageStop = "VIRTUAL_DEVICE_STOP_CAMERA_SESSION";
150 auto json_value = cvd_connection_.ReadJsonMessage();
151 if (json_value[kEventKey] == kMessageStart) {
152 camera_session_active_ = true;
153 } else if (json_value[kEventKey] == kMessageStop) {
154 camera_session_active_ = false;
155 }
156 if (!json_value.empty()) {
157 SendMessage(json_value);
158 }
159 }
160 LOG(INFO) << "Exit reader thread";
161 });
162 }
163
Disconnect()164 void CameraStreamer::Disconnect() {
165 cvd_connection_.Disconnect();
166 if (reader_thread_.joinable()) {
167 reader_thread_.join();
168 }
169 }
170
171 } // namespace webrtc_streaming
172 } // namespace cuttlefish
173