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