ARTPConnection.cpp revision 100a4408968b90e314526185d572c72ea4cc784a
1/*
2 * Copyright (C) 2010 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//#define LOG_NDEBUG 0
18#define LOG_TAG "ARTPConnection"
19#include <utils/Log.h>
20
21#include "ARTPConnection.h"
22
23#include "ARTPSource.h"
24#include "ASessionDescription.h"
25
26#include <media/stagefright/foundation/ABuffer.h>
27#include <media/stagefright/foundation/ADebug.h>
28#include <media/stagefright/foundation/AMessage.h>
29#include <media/stagefright/foundation/AString.h>
30#include <media/stagefright/foundation/hexdump.h>
31
32#include <arpa/inet.h>
33#include <sys/socket.h>
34
35namespace android {
36
37static const size_t kMaxUDPSize = 1500;
38
39static uint16_t u16at(const uint8_t *data) {
40    return data[0] << 8 | data[1];
41}
42
43static uint32_t u32at(const uint8_t *data) {
44    return u16at(data) << 16 | u16at(&data[2]);
45}
46
47static uint64_t u64at(const uint8_t *data) {
48    return (uint64_t)(u32at(data)) << 32 | u32at(&data[4]);
49}
50
51// static
52const int64_t ARTPConnection::kSelectTimeoutUs = 1000ll;
53
54struct ARTPConnection::StreamInfo {
55    int mRTPSocket;
56    int mRTCPSocket;
57    sp<ASessionDescription> mSessionDesc;
58    size_t mIndex;
59    sp<AMessage> mNotifyMsg;
60    KeyedVector<uint32_t, sp<ARTPSource> > mSources;
61
62    int64_t mNumRTCPPacketsReceived;
63    int64_t mNumRTPPacketsReceived;
64    struct sockaddr_in mRemoteRTCPAddr;
65
66    bool mIsInjected;
67};
68
69ARTPConnection::ARTPConnection(uint32_t flags)
70    : mFlags(flags),
71      mPollEventPending(false),
72      mLastReceiverReportTimeUs(-1) {
73}
74
75ARTPConnection::~ARTPConnection() {
76}
77
78void ARTPConnection::addStream(
79        int rtpSocket, int rtcpSocket,
80        const sp<ASessionDescription> &sessionDesc,
81        size_t index,
82        const sp<AMessage> &notify,
83        bool injected) {
84    sp<AMessage> msg = new AMessage(kWhatAddStream, id());
85    msg->setInt32("rtp-socket", rtpSocket);
86    msg->setInt32("rtcp-socket", rtcpSocket);
87    msg->setObject("session-desc", sessionDesc);
88    msg->setSize("index", index);
89    msg->setMessage("notify", notify);
90    msg->setInt32("injected", injected);
91    msg->post();
92}
93
94void ARTPConnection::removeStream(int rtpSocket, int rtcpSocket) {
95    sp<AMessage> msg = new AMessage(kWhatRemoveStream, id());
96    msg->setInt32("rtp-socket", rtpSocket);
97    msg->setInt32("rtcp-socket", rtcpSocket);
98    msg->post();
99}
100
101static void bumpSocketBufferSize(int s) {
102    int size = 256 * 1024;
103    CHECK_EQ(setsockopt(s, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)), 0);
104}
105
106// static
107void ARTPConnection::MakePortPair(
108        int *rtpSocket, int *rtcpSocket, unsigned *rtpPort) {
109    *rtpSocket = socket(AF_INET, SOCK_DGRAM, 0);
110    CHECK_GE(*rtpSocket, 0);
111
112    bumpSocketBufferSize(*rtpSocket);
113
114    *rtcpSocket = socket(AF_INET, SOCK_DGRAM, 0);
115    CHECK_GE(*rtcpSocket, 0);
116
117    bumpSocketBufferSize(*rtcpSocket);
118
119    unsigned start = (rand() * 1000)/ RAND_MAX + 15550;
120    start &= ~1;
121
122    for (unsigned port = start; port < 65536; port += 2) {
123        struct sockaddr_in addr;
124        memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
125        addr.sin_family = AF_INET;
126        addr.sin_addr.s_addr = INADDR_ANY;
127        addr.sin_port = htons(port);
128
129        if (bind(*rtpSocket,
130                 (const struct sockaddr *)&addr, sizeof(addr)) < 0) {
131            continue;
132        }
133
134        addr.sin_port = htons(port + 1);
135
136        if (bind(*rtcpSocket,
137                 (const struct sockaddr *)&addr, sizeof(addr)) == 0) {
138            *rtpPort = port;
139            return;
140        }
141    }
142
143    TRESPASS();
144}
145
146void ARTPConnection::onMessageReceived(const sp<AMessage> &msg) {
147    switch (msg->what()) {
148        case kWhatAddStream:
149        {
150            onAddStream(msg);
151            break;
152        }
153
154        case kWhatRemoveStream:
155        {
156            onRemoveStream(msg);
157            break;
158        }
159
160        case kWhatPollStreams:
161        {
162            onPollStreams();
163            break;
164        }
165
166        case kWhatInjectPacket:
167        {
168            onInjectPacket(msg);
169            break;
170        }
171
172        default:
173        {
174            TRESPASS();
175            break;
176        }
177    }
178}
179
180void ARTPConnection::onAddStream(const sp<AMessage> &msg) {
181    mStreams.push_back(StreamInfo());
182    StreamInfo *info = &*--mStreams.end();
183
184    int32_t s;
185    CHECK(msg->findInt32("rtp-socket", &s));
186    info->mRTPSocket = s;
187    CHECK(msg->findInt32("rtcp-socket", &s));
188    info->mRTCPSocket = s;
189
190    int32_t injected;
191    CHECK(msg->findInt32("injected", &injected));
192
193    info->mIsInjected = injected;
194
195    sp<RefBase> obj;
196    CHECK(msg->findObject("session-desc", &obj));
197    info->mSessionDesc = static_cast<ASessionDescription *>(obj.get());
198
199    CHECK(msg->findSize("index", &info->mIndex));
200    CHECK(msg->findMessage("notify", &info->mNotifyMsg));
201
202    info->mNumRTCPPacketsReceived = 0;
203    info->mNumRTPPacketsReceived = 0;
204    memset(&info->mRemoteRTCPAddr, 0, sizeof(info->mRemoteRTCPAddr));
205
206    if (!injected) {
207        postPollEvent();
208    }
209}
210
211void ARTPConnection::onRemoveStream(const sp<AMessage> &msg) {
212    int32_t rtpSocket, rtcpSocket;
213    CHECK(msg->findInt32("rtp-socket", &rtpSocket));
214    CHECK(msg->findInt32("rtcp-socket", &rtcpSocket));
215
216    List<StreamInfo>::iterator it = mStreams.begin();
217    while (it != mStreams.end()
218           && (it->mRTPSocket != rtpSocket || it->mRTCPSocket != rtcpSocket)) {
219        ++it;
220    }
221
222    if (it == mStreams.end()) {
223        TRESPASS();
224    }
225
226    mStreams.erase(it);
227}
228
229void ARTPConnection::postPollEvent() {
230    if (mPollEventPending) {
231        return;
232    }
233
234    sp<AMessage> msg = new AMessage(kWhatPollStreams, id());
235    msg->post();
236
237    mPollEventPending = true;
238}
239
240void ARTPConnection::onPollStreams() {
241    mPollEventPending = false;
242
243    if (mStreams.empty()) {
244        return;
245    }
246
247    struct timeval tv;
248    tv.tv_sec = 0;
249    tv.tv_usec = kSelectTimeoutUs;
250
251    fd_set rs;
252    FD_ZERO(&rs);
253
254    int maxSocket = -1;
255    for (List<StreamInfo>::iterator it = mStreams.begin();
256         it != mStreams.end(); ++it) {
257        if ((*it).mIsInjected) {
258            continue;
259        }
260
261        FD_SET(it->mRTPSocket, &rs);
262        FD_SET(it->mRTCPSocket, &rs);
263
264        if (it->mRTPSocket > maxSocket) {
265            maxSocket = it->mRTPSocket;
266        }
267        if (it->mRTCPSocket > maxSocket) {
268            maxSocket = it->mRTCPSocket;
269        }
270    }
271
272    if (maxSocket == -1) {
273        return;
274    }
275
276    int res = select(maxSocket + 1, &rs, NULL, NULL, &tv);
277    CHECK_GE(res, 0);
278
279    if (res > 0) {
280        for (List<StreamInfo>::iterator it = mStreams.begin();
281             it != mStreams.end(); ++it) {
282            if ((*it).mIsInjected) {
283                continue;
284            }
285
286            if (FD_ISSET(it->mRTPSocket, &rs)) {
287                receive(&*it, true);
288            }
289            if (FD_ISSET(it->mRTCPSocket, &rs)) {
290                receive(&*it, false);
291            }
292        }
293    }
294
295    postPollEvent();
296
297    int64_t nowUs = ALooper::GetNowUs();
298    if (mLastReceiverReportTimeUs <= 0
299            || mLastReceiverReportTimeUs + 5000000ll <= nowUs) {
300        sp<ABuffer> buffer = new ABuffer(kMaxUDPSize);
301        for (List<StreamInfo>::iterator it = mStreams.begin();
302             it != mStreams.end(); ++it) {
303            StreamInfo *s = &*it;
304
305            if (s->mIsInjected) {
306                continue;
307            }
308
309            if (s->mNumRTCPPacketsReceived == 0) {
310                // We have never received any RTCP packets on this stream,
311                // we don't even know where to send a report.
312                continue;
313            }
314
315            buffer->setRange(0, 0);
316
317            for (size_t i = 0; i < s->mSources.size(); ++i) {
318                sp<ARTPSource> source = s->mSources.valueAt(i);
319
320                source->addReceiverReport(buffer);
321
322                if (mFlags & kRegularlyRequestFIR) {
323                    source->addFIR(buffer);
324                }
325            }
326
327            if (buffer->size() > 0) {
328                LOGV("Sending RR...");
329
330                ssize_t n = sendto(
331                        s->mRTCPSocket, buffer->data(), buffer->size(), 0,
332                        (const struct sockaddr *)&s->mRemoteRTCPAddr,
333                        sizeof(s->mRemoteRTCPAddr));
334                CHECK_EQ(n, (ssize_t)buffer->size());
335
336                mLastReceiverReportTimeUs = nowUs;
337            }
338        }
339    }
340}
341
342status_t ARTPConnection::receive(StreamInfo *s, bool receiveRTP) {
343    CHECK(!s->mIsInjected);
344
345    sp<ABuffer> buffer = new ABuffer(65536);
346
347    socklen_t remoteAddrLen =
348        (!receiveRTP && s->mNumRTCPPacketsReceived == 0)
349            ? sizeof(s->mRemoteRTCPAddr) : 0;
350
351    ssize_t nbytes = recvfrom(
352            receiveRTP ? s->mRTPSocket : s->mRTCPSocket,
353            buffer->data(),
354            buffer->capacity(),
355            0,
356            remoteAddrLen > 0 ? (struct sockaddr *)&s->mRemoteRTCPAddr : NULL,
357            remoteAddrLen > 0 ? &remoteAddrLen : NULL);
358
359    if (nbytes < 0) {
360        return -1;
361    }
362
363    buffer->setRange(0, nbytes);
364
365    // LOGI("received %d bytes.", buffer->size());
366
367    status_t err;
368    if (receiveRTP) {
369        err = parseRTP(s, buffer);
370    } else {
371        err = parseRTCP(s, buffer);
372    }
373
374    return err;
375}
376
377status_t ARTPConnection::parseRTP(StreamInfo *s, const sp<ABuffer> &buffer) {
378    if (s->mNumRTPPacketsReceived++ == 0) {
379        sp<AMessage> notify = s->mNotifyMsg->dup();
380        notify->setInt32("first-rtp", true);
381        notify->post();
382    }
383
384    size_t size = buffer->size();
385
386    if (size < 12) {
387        // Too short to be a valid RTP header.
388        return -1;
389    }
390
391    const uint8_t *data = buffer->data();
392
393    if ((data[0] >> 6) != 2) {
394        // Unsupported version.
395        return -1;
396    }
397
398    if (data[0] & 0x20) {
399        // Padding present.
400
401        size_t paddingLength = data[size - 1];
402
403        if (paddingLength + 12 > size) {
404            // If we removed this much padding we'd end up with something
405            // that's too short to be a valid RTP header.
406            return -1;
407        }
408
409        size -= paddingLength;
410    }
411
412    int numCSRCs = data[0] & 0x0f;
413
414    size_t payloadOffset = 12 + 4 * numCSRCs;
415
416    if (size < payloadOffset) {
417        // Not enough data to fit the basic header and all the CSRC entries.
418        return -1;
419    }
420
421    if (data[0] & 0x10) {
422        // Header eXtension present.
423
424        if (size < payloadOffset + 4) {
425            // Not enough data to fit the basic header, all CSRC entries
426            // and the first 4 bytes of the extension header.
427
428            return -1;
429        }
430
431        const uint8_t *extensionData = &data[payloadOffset];
432
433        size_t extensionLength =
434            4 * (extensionData[2] << 8 | extensionData[3]);
435
436        if (size < payloadOffset + 4 + extensionLength) {
437            return -1;
438        }
439
440        payloadOffset += 4 + extensionLength;
441    }
442
443    uint32_t srcId = u32at(&data[8]);
444
445    sp<ARTPSource> source = findSource(s, srcId);
446
447    uint32_t rtpTime = u32at(&data[4]);
448
449    sp<AMessage> meta = buffer->meta();
450    meta->setInt32("ssrc", srcId);
451    meta->setInt32("rtp-time", rtpTime);
452    meta->setInt32("PT", data[1] & 0x7f);
453    meta->setInt32("M", data[1] >> 7);
454
455    buffer->setInt32Data(u16at(&data[2]));
456    buffer->setRange(payloadOffset, size - payloadOffset);
457
458    source->processRTPPacket(buffer);
459
460    return OK;
461}
462
463status_t ARTPConnection::parseRTCP(StreamInfo *s, const sp<ABuffer> &buffer) {
464    if (s->mNumRTCPPacketsReceived++ == 0) {
465        sp<AMessage> notify = s->mNotifyMsg->dup();
466        notify->setInt32("first-rtcp", true);
467        notify->post();
468    }
469
470    const uint8_t *data = buffer->data();
471    size_t size = buffer->size();
472
473    while (size > 0) {
474        if (size < 8) {
475            // Too short to be a valid RTCP header
476            return -1;
477        }
478
479        if ((data[0] >> 6) != 2) {
480            // Unsupported version.
481            return -1;
482        }
483
484        if (data[0] & 0x20) {
485            // Padding present.
486
487            size_t paddingLength = data[size - 1];
488
489            if (paddingLength + 12 > size) {
490                // If we removed this much padding we'd end up with something
491                // that's too short to be a valid RTP header.
492                return -1;
493            }
494
495            size -= paddingLength;
496        }
497
498        size_t headerLength = 4 * (data[2] << 8 | data[3]) + 4;
499
500        if (size < headerLength) {
501            // Only received a partial packet?
502            return -1;
503        }
504
505        switch (data[1]) {
506            case 200:
507            {
508                parseSR(s, data, headerLength);
509                break;
510            }
511
512            case 201:  // RR
513            case 202:  // SDES
514            case 204:  // APP
515                break;
516
517            case 205:  // TSFB (transport layer specific feedback)
518            case 206:  // PSFB (payload specific feedback)
519                // hexdump(data, headerLength);
520                break;
521
522            case 203:
523            {
524                parseBYE(s, data, headerLength);
525                break;
526            }
527
528            default:
529            {
530                LOGW("Unknown RTCP packet type %u of size %d",
531                     (unsigned)data[1], headerLength);
532                break;
533            }
534        }
535
536        data += headerLength;
537        size -= headerLength;
538    }
539
540    return OK;
541}
542
543status_t ARTPConnection::parseBYE(
544        StreamInfo *s, const uint8_t *data, size_t size) {
545    size_t SC = data[0] & 0x3f;
546
547    if (SC == 0 || size < (4 + SC * 4)) {
548        // Packet too short for the minimal BYE header.
549        return -1;
550    }
551
552    uint32_t id = u32at(&data[4]);
553
554    sp<ARTPSource> source = findSource(s, id);
555
556    source->byeReceived();
557
558    return OK;
559}
560
561status_t ARTPConnection::parseSR(
562        StreamInfo *s, const uint8_t *data, size_t size) {
563    size_t RC = data[0] & 0x1f;
564
565    if (size < (7 + RC * 6) * 4) {
566        // Packet too short for the minimal SR header.
567        return -1;
568    }
569
570    uint32_t id = u32at(&data[4]);
571    uint64_t ntpTime = u64at(&data[8]);
572    uint32_t rtpTime = u32at(&data[16]);
573
574#if 0
575    LOGI("XXX timeUpdate: ssrc=0x%08x, rtpTime %u == ntpTime %.3f",
576         id,
577         rtpTime,
578         (ntpTime >> 32) + (double)(ntpTime & 0xffffffff) / (1ll << 32));
579#endif
580
581    sp<ARTPSource> source = findSource(s, id);
582
583    source->timeUpdate(rtpTime, ntpTime);
584
585    return 0;
586}
587
588sp<ARTPSource> ARTPConnection::findSource(StreamInfo *info, uint32_t srcId) {
589    sp<ARTPSource> source;
590    ssize_t index = info->mSources.indexOfKey(srcId);
591    if (index < 0) {
592        index = info->mSources.size();
593
594        source = new ARTPSource(
595                srcId, info->mSessionDesc, info->mIndex, info->mNotifyMsg);
596
597        info->mSources.add(srcId, source);
598    } else {
599        source = info->mSources.valueAt(index);
600    }
601
602    return source;
603}
604
605void ARTPConnection::injectPacket(int index, const sp<ABuffer> &buffer) {
606    sp<AMessage> msg = new AMessage(kWhatInjectPacket, id());
607    msg->setInt32("index", index);
608    msg->setObject("buffer", buffer);
609    msg->post();
610}
611
612void ARTPConnection::onInjectPacket(const sp<AMessage> &msg) {
613    int32_t index;
614    CHECK(msg->findInt32("index", &index));
615
616    sp<RefBase> obj;
617    CHECK(msg->findObject("buffer", &obj));
618
619    sp<ABuffer> buffer = static_cast<ABuffer *>(obj.get());
620
621    List<StreamInfo>::iterator it = mStreams.begin();
622    while (it != mStreams.end()
623           && it->mRTPSocket != index && it->mRTCPSocket != index) {
624        ++it;
625    }
626
627    if (it == mStreams.end()) {
628        TRESPASS();
629    }
630
631    StreamInfo *s = &*it;
632
633    status_t err;
634    if (it->mRTPSocket == index) {
635        err = parseRTP(s, buffer);
636    } else {
637        err = parseRTCP(s, buffer);
638    }
639}
640
641}  // namespace android
642
643