1 /*
2 * Copyright (C) 2019 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
17 #include <webrtc/VP8Packetizer.h>
18
19 #include "Utils.h"
20
21 #include <webrtc/RTPSocketHandler.h>
22
23 #include <https/SafeCallbackable.h>
24 #include <https/Support.h>
25
26 using namespace android;
27
VP8Packetizer(std::shared_ptr<RunLoop> runLoop,std::shared_ptr<StreamingSource> frameBufferSource)28 VP8Packetizer::VP8Packetizer(
29 std::shared_ptr<RunLoop> runLoop,
30 std::shared_ptr<StreamingSource> frameBufferSource)
31 : Packetizer(runLoop, frameBufferSource) {
32 }
33
packetize(const std::shared_ptr<SBuffer> & accessUnit,int64_t timeUs)34 void VP8Packetizer::packetize(const std::shared_ptr<SBuffer> &accessUnit, int64_t timeUs) {
35 static constexpr uint8_t PT = 96;
36 static constexpr uint32_t SSRC = 0xdeadbeef;
37
38 // XXX Retransmission packets add 2 bytes (for the original seqNum), should
39 // probably reserve that amount in the original packets so we don't exceed
40 // the MTU on retransmission.
41 static const size_t kMaxSRTPPayloadSize =
42 RTPSocketHandler::kMaxUDPPayloadSize - SRTP_MAX_TRAILER_LEN;
43
44 const uint8_t *src = accessUnit->data();
45 size_t srcSize = accessUnit->size();
46
47 uint32_t rtpTime = ((timeUs - mediaStartTime()) * 9) / 100;
48
49 LOG(VERBOSE) << "got accessUnit of size " << srcSize;
50
51 size_t srcOffset = 0;
52 while (srcOffset < srcSize) {
53 size_t packetSize = 12; // generic RTP header
54
55 packetSize += 1; // VP8 Payload Descriptor
56
57 auto copy = std::min(srcSize - srcOffset, kMaxSRTPPayloadSize - packetSize);
58
59 packetSize += copy;
60
61 std::vector<uint8_t> packet(packetSize);
62 uint8_t *dst = packet.data();
63
64 dst[0] = 0x80;
65
66 dst[1] = PT;
67 if (srcOffset + copy == srcSize) {
68 dst[1] |= 0x80; // (M)ark
69 }
70
71 SET_U16(&dst[2], 0); // seqNum
72 SET_U32(&dst[4], rtpTime);
73 SET_U32(&dst[8], SSRC);
74
75 size_t dstOffset = 12;
76
77 // VP8 Payload Descriptor
78 dst[dstOffset++] = (srcOffset == 0) ? 0x10 : 0x00; // S
79
80 memcpy(&dst[dstOffset], &src[srcOffset], copy);
81 dstOffset += copy;
82
83 CHECK_EQ(dstOffset, packetSize);
84
85 srcOffset += copy;
86
87 queueRTPDatagram(&packet);
88 }
89 }
90
rtpNow() const91 uint32_t VP8Packetizer::rtpNow() const {
92 return (timeSinceStart() * 90) / 1000;
93 }
94