| 6 |
| #include "../PrivateDefines.h" |
| 7 | #include "VideoPacketSender.h" |
| 8 | #include "VideoFEC.h" |
| 9 |
| 10 | #include <algorithm> |
| 11 |
| 12 | using namespace tgvoip; |
| 13 | using namespace tgvoip::video; |
| 14 |
| 15 | VideoPacketSender::VideoPacketSender(VoIPController* controller, VideoSource* videoSource, std::shared_ptr<VoIPController::Stream> stream) |
| 16 | : PacketSender(controller) |
| 17 | , m_stm(std::move(stream)) |
| 18 | { |
| 19 | SetSource(videoSource); |
| 20 | } |
| 21 |
| 22 | VideoPacketSender::~VideoPacketSender() = default; |
| 23 |
| 24 | std::uint32_t VideoPacketSender::GetBitrate() const |
| 25 | { |
| 26 | return m_currentVideoBitrate; |
| 27 | } |
| 28 |
| 29 | void VideoPacketSender::PacketAcknowledged(std::uint32_t seq, double sendTime, double ackTime, PktType type, std::uint32_t size) |
| 30 | { |
| 31 | std::uint32_t bytesNewlyAcked = 0; |
| 32 | // video frames are stored in sentVideoFrames in order of increasing numbers |
| 33 | // so if a frame (or part of it) is acknowledged but isn't sentVideoFrames[0], we know there was a packet loss |
| 34 | for (SentVideoFrame& frame : m_sentVideoFrames) |
| 35 | { |
| 36 | for (auto s = frame.unacknowledgedPackets.begin(); s != frame.unacknowledgedPackets.end();) |
| 37 | { |
| 38 | if (*s == seq) |
| 39 | { |
| 40 | s = frame.unacknowledgedPackets.erase(s); |
| 41 | bytesNewlyAcked = size; |
| 42 | break; |
| 43 | } |
| 44 | else |
| 45 | { |
| 46 | ++s; |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | for (auto frame = m_sentVideoFrames.begin(); frame != m_sentVideoFrames.end();) |
| 51 | { |
| 52 | if (frame->unacknowledgedPackets.empty() && frame->fragmentsInQueue == 0) |
| 53 | { |
| 54 | frame = m_sentVideoFrames.erase(frame); |
| 55 | continue; |
| 56 | } |
| 57 | ++frame; |
| 58 | } |
| 59 | if (bytesNewlyAcked != 0) |
| 60 | { |
| 61 | float _sendTime = static_cast<float>(sendTime - GetConnectionInitTime()); |
| 62 | float recvTime = static_cast<float>(ackTime); |
| 63 | float oneWayDelay = recvTime - _sendTime; |
| 64 | m_videoCongestionControl.ProcessAcks(oneWayDelay, bytesNewlyAcked, m_videoPacketLossCount, RTTHistory().Average(5)); |
| 65 | } |
| 66 | } |
| 67 |
| 68 | void VideoPacketSender::PacketLost(std::uint32_t seq, PktType type, std::uint32_t size) |
| 69 | { |
| 70 | if (type == PktType::STREAM_EC) |
| 71 | return; |
| 72 | LOGW("VideoPacketSender::PacketLost: %u (size %u)", seq, size); |
| 73 | for (auto frame = m_sentVideoFrames.begin(); frame != m_sentVideoFrames.end(); ++frame) |
| 74 | { |
| 75 | auto pkt = std::find(frame->unacknowledgedPackets.begin(), frame->unacknowledgedPackets.end(), seq); |
| 76 | if (pkt == frame->unacknowledgedPackets.end()) |
| 77 | continue; |
| 78 | LOGW("Lost packet belongs to frame %u", frame->seq); |
| 79 | m_videoPacketLossCount++; |
| 80 | m_videoCongestionControl.ProcessPacketLost(size); |
| 81 | if (!m_videoKeyframeRequested) |
| 82 | { |
| 83 | m_videoKeyframeRequested = true; |
| 84 | m_source->RequestKeyFrame(); |
| 85 | } |
| 86 | frame->unacknowledgedPackets.erase(pkt); |
| 87 | if (frame->unacknowledgedPackets.empty() && frame->fragmentsInQueue == 0) |
| 88 | { |
| 89 | m_sentVideoFrames.erase(frame); |
| 90 | } |
| 91 | return; |
| 92 | } |
| 93 | } |
| 94 |
| 95 | void VideoPacketSender::SetSource(VideoSource* source) |
| 96 | { |
| 97 | if (m_source == source) |
| 98 | return; |
| 99 |
| 100 | if (m_source != nullptr) |
| 101 | { |
| 102 | m_source->Stop(); |
| 103 | m_source->SetCallback(nullptr); |
| 104 | } |
| 105 |
| 106 | m_source = source; |
| 107 |
| 108 | if (source == nullptr) |
| 109 | return; |
| 110 |
| 111 | m_sourceChangeTime = m_lastVideoResolutionChangeTime = VoIPController::GetCurrentTime(); |
| 112 | std::uint32_t bitrate = m_videoCongestionControl.GetBitrate(); |
| 113 | m_currentVideoBitrate = bitrate; |
| 114 | source->SetBitrate(bitrate); |
| 115 | source->Reset(m_stm->codec, m_stm->resolution = static_cast<int>(GetVideoResolutionForCurrentBitrate())); |
| 116 | source->Start(); |
| 117 | source->SetCallback(std::bind(&VideoPacketSender::SendFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); |
| 118 | source->SetStreamStateCallback([this](bool paused) |
| 119 | { |
| 120 | m_stm->paused = paused; |
| 121 | GetMessageThread().Post([this]() |
| 122 | { |
| 123 | SendStreamFlags(*m_stm); |
| 124 | }); |
| 125 | }); |
| 126 | } |
| 127 |
| 128 | void VideoPacketSender::SendFrame(const Buffer& _frame, std::uint32_t flags, std::uint32_t rotation) |
| 129 | { |
| 130 | std::shared_ptr<Buffer> framePtr = std::make_shared<Buffer>(Buffer::CopyOf(_frame)); |
| 131 | GetMessageThread().Post([this, framePtr, flags, rotation] { |
| 132 | const Buffer& frame = *framePtr; |
| 133 |
| 134 | double currentTime = VoIPController::GetCurrentTime(); |
| 135 |
| 136 | if (m_firstVideoFrameTime == 0.0) |
| 137 | m_firstVideoFrameTime = currentTime; |
| 138 |
| 139 | m_videoCongestionControl.UpdateMediaRate(static_cast<std::uint32_t>(frame.Length())); |
| 140 | std::uint32_t bitrate = m_videoCongestionControl.GetBitrate(); |
| 141 | if (bitrate != m_currentVideoBitrate) |
| 142 | { |
| 143 | m_currentVideoBitrate = bitrate; |
| 144 | LOGD("Setting video bitrate to %u", bitrate); |
| 145 | m_source->SetBitrate(bitrate); |
| 146 | } |
| 147 | int resolutionFromBitrate = static_cast<int>(GetVideoResolutionForCurrentBitrate()); |
| 148 | if (resolutionFromBitrate != m_stm->resolution && currentTime - m_lastVideoResolutionChangeTime > 3.0 && currentTime - m_sourceChangeTime > 10.0) |
| 149 | { |
| 150 | LOGI("Changing video resolution: %d -> %d", m_stm->resolution, resolutionFromBitrate); |
| 151 | m_stm->resolution = resolutionFromBitrate; |
| 152 | GetMessageThread().Post([this, resolutionFromBitrate] |
| 153 | { |
| 154 | m_source->Reset(m_stm->codec, resolutionFromBitrate); |
| 155 | m_stm->csdIsValid = false; |
| 156 | }); |
| 157 | m_lastVideoResolutionChangeTime = currentTime; |
| 158 | return; |
| 159 | } |
| 160 |
| 161 | if (m_videoKeyframeRequested) |
| 162 | { |
| 163 | if (flags & VIDEO_FRAME_FLAG_KEYFRAME) |
| 164 | { |
| 165 | m_videoKeyframeRequested = false; |
| 166 | } |
| 167 | else |
| 168 | { |
| 169 | LOGV("Dropping input video frame waiting for key frame"); |
| 170 | } |
| 171 | } |
| 172 |
| 173 | std::uint32_t pts = m_videoFrameCount++; |
| 174 | bool csdInvalidated = !m_stm->csdIsValid; |
| 175 | if (!m_stm->csdIsValid) |
| 176 | { |
| 177 | std::vector<Buffer>& csd = m_source->GetCodecSpecificData(); |
| 178 | m_stm->codecSpecificData.clear(); |
| 179 | for (Buffer& b : csd) |
| 180 | { |
| 181 | m_stm->codecSpecificData.emplace_back(Buffer::CopyOf(b)); |
| 182 | } |
| 183 | m_stm->csdIsValid = true; |
| 184 | m_stm->width = m_source->GetFrameWidth(); |
| 185 | m_stm->height = m_source->GetFrameHeight(); |
| 186 | } |
| 187 |
| 188 | Buffer csd; |
| 189 | if (flags & VIDEO_FRAME_FLAG_KEYFRAME) |
| 190 | { |
| 191 | BufferOutputStream os(256); |
| 192 | os.WriteUInt16(static_cast<std::uint16_t>(m_stm->width)); |
| 193 | os.WriteUInt16(static_cast<std::uint16_t>(m_stm->height)); |
| 194 | std::uint8_t sizeAndFlag = static_cast<std::uint8_t>(m_stm->codecSpecificData.size()); |
| 195 | if (csdInvalidated) |
| 196 | sizeAndFlag |= 0x80; |
| 197 | os.WriteUInt8(sizeAndFlag); |
| 198 | for (const Buffer& b : m_stm->codecSpecificData) |
| 199 | { |
| 200 | assert(b.Length() < 255); |
| 201 | os.WriteUInt8(static_cast<std::uint8_t>(b.Length())); |
| 202 | os.WriteBytes(b); |
| 203 | } |
| 204 | csd = std::move(os); |
| 205 | } |
| 206 |
| 207 | ++m_frameSeq; |
| 208 | std::size_t totalLength = csd.Length() + frame.Length(); |
| 209 | std::size_t segmentCount = totalLength / 1024; |
| 210 | if (totalLength % 1024 > 0) |
| 211 | ++segmentCount; |
| 212 | SentVideoFrame sentFrame; |
| 213 | sentFrame.seq = m_frameSeq; |
| 214 | sentFrame.fragmentCount = static_cast<std::uint32_t>(segmentCount); |
| 215 | sentFrame.fragmentsInQueue = 0; |
| 216 | std::size_t offset = 0; |
| 217 | std::size_t packetSize = totalLength / segmentCount; |
| 218 | for (std::size_t seg = 0; seg < segmentCount; ++seg) |
| 219 | { |
| 220 | BufferOutputStream pkt(1500); |
| 221 | std::size_t len; |
| 222 | if (seg == segmentCount - 1) |
| 223 | { |
| 224 | len = frame.Length() - offset; |
| 225 | } |
| 226 | else |
| 227 | { |
| 228 | len = packetSize; |
| 229 | } |
| 230 | std::uint8_t pflags = STREAM_DATA_FLAG_LEN16; |
| 231 | pkt.WriteUInt8(static_cast<std::uint8_t>(m_stm->id | pflags)); // streamID + flags |
| 232 | std::uint16_t lengthAndFlags = static_cast<std::uint16_t>(len & 0x7FF); |
| 233 | if (segmentCount > 1) |
| 234 | lengthAndFlags |= STREAM_DATA_XFLAG_FRAGMENTED; |
| 235 | if (flags & VIDEO_FRAME_FLAG_KEYFRAME) |
| 236 | lengthAndFlags |= STREAM_DATA_XFLAG_KEYFRAME; |
| 237 | pkt.WriteUInt16(lengthAndFlags); |
| 238 | pkt.WriteUInt32(pts); |
| 239 | if (segmentCount > 1) |
| 240 | { |
| 241 | pkt.WriteUInt8(static_cast<std::uint8_t>(seg)); |
| 242 | pkt.WriteUInt8(static_cast<std::uint8_t>(segmentCount)); |
| 243 | } |
| 244 | pkt.WriteUInt8(static_cast<std::uint8_t>(m_frameSeq)); |
| 245 | std::size_t dataOffset = pkt.GetLength(); |
| 246 | if (seg == 0) |
| 247 | { |
| 248 | VideoRotation _rotation; |
| 249 | switch (rotation) |
| 250 | { |
| 251 | case 90: |
| 252 | _rotation = VideoRotation::_90; |
| 253 | break; |
| 254 | case 180: |
| 255 | _rotation = VideoRotation::_180; |
| 256 | break; |
| 257 | case 270: |
| 258 | _rotation = VideoRotation::_270; |
| 259 | break; |
| 260 | case 0: |
| 261 | default: |
| 262 | _rotation = VideoRotation::_0; |
| 263 | break; |
| 264 | } |
| 265 | pkt.WriteUInt8(static_cast<std::uint8_t>(_rotation)); |
| 266 | dataOffset++; |
| 267 |
| 268 | if (!csd.IsEmpty()) |
| 269 | { |
| 270 | pkt.WriteBytes(csd); |
| 271 | len -= csd.Length(); |
| 272 | } |
| 273 | } |
| 274 | pkt.WriteBytes(frame, offset, len); |
| 275 |
| 276 | Buffer fecPacketData(pkt.GetLength() - dataOffset); |
| 277 | fecPacketData.CopyFrom(pkt.GetBuffer() + dataOffset, 0, pkt.GetLength() - dataOffset); |
| 278 | m_packetsForFEC.emplace_back(std::move(fecPacketData)); |
| 279 | offset += len; |
| 280 |
| 281 | std::size_t pktLength = pkt.GetLength(); |
| 282 | Buffer packetData(std::move(pkt)); |
| 283 |
| 284 | std::size_t packetDataLength = packetData.Length(); |
| 285 | VoIPController::PendingOutgoingPacket p { |
| 286 | /*.seq=*/ 0, |
| 287 | /*.type=*/ PktType::STREAM_DATA, |
| 288 | /*.len=*/ packetDataLength, |
| 289 | /*.data=*/ std::move(packetData), |
| 290 | /*.endpoint=*/0, |
| 291 | }; |
| 292 | IncrementUnsentStreamPackets(); |
| 293 | std::uint32_t seq = SendPacket(std::move(p)); |
| 294 | m_videoCongestionControl.ProcessPacketSent(static_cast<unsigned int>(pktLength)); |
| 295 | sentFrame.unacknowledgedPackets.emplace_back(seq); |
| 296 | } |
| 297 | ++m_fecFrameCount; |
| 298 | if (m_fecFrameCount >= 3) |
| 299 | { |
| 300 | Buffer fecPacket = ParityFEC::Encode(m_packetsForFEC); |
| 301 |
| 302 | m_packetsForFEC.clear(); |
| 303 | m_fecFrameCount = 0; |
| 304 | LOGV("FEC packet length: %u", static_cast<unsigned int>(fecPacket.Length())); |
| 305 | BufferOutputStream out(1500); |
| 306 | out.WriteUInt8(m_stm->id); |
| 307 | out.WriteUInt8(static_cast<std::uint8_t>(m_frameSeq)); |
| 308 | out.WriteUInt8(FEC_SCHEME_XOR); |
| 309 | out.WriteUInt8(3); |
| 310 | out.WriteUInt16(static_cast<std::uint16_t>(fecPacket.Length())); |
| 311 | out.WriteBytes(fecPacket); |
| 312 |
| 313 | std::size_t outLength = out.GetLength(); |
| 314 | VoIPController::PendingOutgoingPacket p |
| 315 | { |
| 316 | 0, |
| 317 | PktType::STREAM_EC, |
| 318 | outLength, |
| 319 | Buffer(std::move(out)), |
| 320 | 0 |
| 321 | }; |
| 322 | std::uint32_t seq = SendPacket(std::move(p)); |
| 323 | } |
| 324 | m_sentVideoFrames.emplace_back(sentFrame); |
| 325 | }); |
| 326 | } |
| 327 |
| 328 | InitVideoRes VideoPacketSender::GetVideoResolutionForCurrentBitrate() |
| 329 | { |
| 330 | InitVideoRes peerMaxVideoResolution = GetProtocolInfo().maxVideoResolution; |
| 331 | InitVideoRes resolutionFromBitrate = InitVideoRes::_1080; |
| 332 | if (VoIPController::GetCurrentTime() - m_sourceChangeTime > 10.0) |
| 333 | { |
| 334 | // TODO: probably move this to server config |
| 335 | if (m_stm->codec == CODEC_AVC || m_stm->codec == CODEC_VP8) |
| 336 | { |
| 337 | if (m_currentVideoBitrate > 400000) |
| 338 | { |
| 339 | resolutionFromBitrate = InitVideoRes::_720; |
| 340 | } |
| 341 | else if (m_currentVideoBitrate > 250000) |
| 342 | { |
| 343 | resolutionFromBitrate = InitVideoRes::_480; |
| 344 | } |
| 345 | else |
| 346 | { |
| 347 | resolutionFromBitrate = InitVideoRes::_360; |
| 348 | } |
| 349 | } |
| 350 | else if (m_stm->codec == CODEC_HEVC || m_stm->codec == CODEC_VP9) |
| 351 | { |
| 352 | if (m_currentVideoBitrate > 400000) |
| 353 | { |
| 354 | resolutionFromBitrate = InitVideoRes::_1080; |
| 355 | } |
| 356 | else if (m_currentVideoBitrate > 250000) |
| 357 | { |
| 358 | resolutionFromBitrate = InitVideoRes::_720; |
| 359 | } |
| 360 | else if (m_currentVideoBitrate > 100000) |
| 361 | { |
| 362 | resolutionFromBitrate = InitVideoRes::_480; |
| 363 | } |
| 364 | else |
| 365 | { |
| 366 | resolutionFromBitrate = InitVideoRes::_360; |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | else |
| 371 | { |
| 372 | if (m_stm->codec == CODEC_AVC || m_stm->codec == CODEC_VP8) |
| 373 | resolutionFromBitrate = InitVideoRes::_720; |
| 374 | else if (m_stm->codec == CODEC_HEVC || m_stm->codec == CODEC_VP9) |
| 375 | resolutionFromBitrate = InitVideoRes::_1080; |
| 376 | } |
| 377 | return static_cast<InitVideoRes>(std::min(static_cast<std::uint8_t>(peerMaxVideoResolution), |
| 378 | static_cast<std::uint8_t>(resolutionFromBitrate))); |
| 379 | } |
| 380 |