ARTPSession.cpp revision 389636ce967af15e72817e2133907a2cb2efd1ae
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#include "ARTPSession.h"
18
19#include <media/stagefright/foundation/ABuffer.h>
20#include <media/stagefright/foundation/ADebug.h>
21#include <media/stagefright/foundation/AMessage.h>
22#include <media/stagefright/foundation/hexdump.h>
23
24#include <ctype.h>
25#include <arpa/inet.h>
26#include <sys/socket.h>
27
28#include "APacketSource.h"
29#include "ARTPConnection.h"
30#include "ASessionDescription.h"
31
32namespace android {
33
34ARTPSession::ARTPSession()
35    : mInitCheck(NO_INIT) {
36}
37
38status_t ARTPSession::setup(const sp<ASessionDescription> &desc) {
39    CHECK_EQ(mInitCheck, (status_t)NO_INIT);
40
41    mDesc = desc;
42
43    mRTPConn = new ARTPConnection(
44            ARTPConnection::kFakeTimestamps
45                | ARTPConnection::kRegularlyRequestFIR);
46
47    looper()->registerHandler(mRTPConn);
48
49    for (size_t i = 1; i < mDesc->countTracks(); ++i) {
50        AString connection;
51        if (!mDesc->findAttribute(i, "c=", &connection)) {
52            // No per-stream connection information, try global fallback.
53            if (!mDesc->findAttribute(0, "c=", &connection)) {
54                LOG(ERROR) << "Unable to find connection attribtue.";
55                return mInitCheck;
56            }
57        }
58        if (!(connection == "IN IP4 127.0.0.1")) {
59            LOG(ERROR) << "We only support localhost connections for now.";
60            return mInitCheck;
61        }
62
63        unsigned port;
64        if (!validateMediaFormat(i, &port) || (port & 1) != 0) {
65            LOG(ERROR) << "Invalid media format.";
66            return mInitCheck;
67        }
68
69        sp<APacketSource> source = new APacketSource(mDesc, i);
70        if (source->initCheck() != OK) {
71            LOG(ERROR) << "Unsupported format.";
72            return mInitCheck;
73        }
74
75        int rtpSocket = MakeUDPSocket(port);
76        int rtcpSocket = MakeUDPSocket(port + 1);
77
78        mTracks.push(TrackInfo());
79        TrackInfo *info = &mTracks.editItemAt(mTracks.size() - 1);
80        info->mRTPSocket = rtpSocket;
81        info->mRTCPSocket = rtcpSocket;
82
83        sp<AMessage> notify = new AMessage(kWhatAccessUnitComplete, id());
84        notify->setSize("track-index", mTracks.size() - 1);
85
86        mRTPConn->addStream(
87                rtpSocket, rtcpSocket, mDesc, i, notify, false /* injected */);
88
89        info->mPacketSource = source;
90    }
91
92    mInitCheck = OK;
93
94    return OK;
95}
96
97// static
98int ARTPSession::MakeUDPSocket(unsigned port) {
99    int s = socket(AF_INET, SOCK_DGRAM, 0);
100    CHECK_GE(s, 0);
101
102    struct sockaddr_in addr;
103    memset(addr.sin_zero, 0, sizeof(addr.sin_zero));
104    addr.sin_family = AF_INET;
105    addr.sin_addr.s_addr = INADDR_ANY;
106    addr.sin_port = htons(port);
107
108    CHECK_EQ(0, bind(s, (const struct sockaddr *)&addr, sizeof(addr)));
109
110    return s;
111}
112
113ARTPSession::~ARTPSession() {
114    for (size_t i = 0; i < mTracks.size(); ++i) {
115        TrackInfo *info = &mTracks.editItemAt(i);
116
117        info->mPacketSource->signalEOS(UNKNOWN_ERROR);
118
119        close(info->mRTPSocket);
120        close(info->mRTCPSocket);
121    }
122}
123
124void ARTPSession::onMessageReceived(const sp<AMessage> &msg) {
125    switch (msg->what()) {
126        case kWhatAccessUnitComplete:
127        {
128            int32_t firstRTCP;
129            if (msg->findInt32("first-rtcp", &firstRTCP)) {
130                // There won't be an access unit here, it's just a notification
131                // that the data communication worked since we got the first
132                // rtcp packet.
133                break;
134            }
135
136            size_t trackIndex;
137            CHECK(msg->findSize("track-index", &trackIndex));
138
139            int32_t eos;
140            if (msg->findInt32("eos", &eos) && eos) {
141                TrackInfo *info = &mTracks.editItemAt(trackIndex);
142                info->mPacketSource->signalEOS(ERROR_END_OF_STREAM);
143                break;
144            }
145
146            sp<RefBase> obj;
147            CHECK(msg->findObject("access-unit", &obj));
148
149            sp<ABuffer> accessUnit = static_cast<ABuffer *>(obj.get());
150
151            uint64_t ntpTime;
152            CHECK(accessUnit->meta()->findInt64(
153                        "ntp-time", (int64_t *)&ntpTime));
154
155#if 0
156#if 0
157            printf("access unit complete size=%d\tntp-time=0x%016llx\n",
158                   accessUnit->size(), ntpTime);
159#else
160            LOG(INFO) << "access unit complete, "
161                      << "size=" << accessUnit->size() << ", "
162                      << "ntp-time=" << ntpTime;
163            hexdump(accessUnit->data(), accessUnit->size());
164#endif
165#endif
166
167#if 0
168            CHECK_GE(accessUnit->size(), 5u);
169            CHECK(!memcmp("\x00\x00\x00\x01", accessUnit->data(), 4));
170            unsigned x = accessUnit->data()[4];
171
172            LOG(INFO) << "access unit complete: "
173                      << StringPrintf("nalType=0x%02x, nalRefIdc=0x%02x",
174                                      x & 0x1f, (x & 0x60) >> 5);
175#endif
176
177            accessUnit->meta()->setInt64("ntp-time", ntpTime);
178            accessUnit->meta()->setInt64("timeUs", 0);
179
180#if 0
181            int32_t damaged;
182            if (accessUnit->meta()->findInt32("damaged", &damaged)
183                    && damaged != 0) {
184                LOG(INFO) << "ignoring damaged AU";
185            } else
186#endif
187            {
188                TrackInfo *info = &mTracks.editItemAt(trackIndex);
189                info->mPacketSource->queueAccessUnit(accessUnit);
190            }
191            break;
192        }
193
194        default:
195            TRESPASS();
196            break;
197    }
198}
199
200bool ARTPSession::validateMediaFormat(size_t index, unsigned *port) const {
201    AString format;
202    mDesc->getFormat(index, &format);
203
204    ssize_t i = format.find(" ");
205    if (i < 0) {
206        return false;
207    }
208
209    ++i;
210    size_t j = i;
211    while (isdigit(format.c_str()[j])) {
212        ++j;
213    }
214    if (format.c_str()[j] != ' ') {
215        return false;
216    }
217
218    AString portString(format, i, j - i);
219
220    char *end;
221    unsigned long x = strtoul(portString.c_str(), &end, 10);
222    if (end == portString.c_str() || *end != '\0') {
223        return false;
224    }
225
226    if (x == 0 || x > 65535) {
227        return false;
228    }
229
230    *port = x;
231
232    return true;
233}
234
235size_t ARTPSession::countTracks() {
236    return mTracks.size();
237}
238
239sp<MediaSource> ARTPSession::trackAt(size_t index) {
240    CHECK_LT(index, mTracks.size());
241    return mTracks.editItemAt(index).mPacketSource;
242}
243
244}  // namespace android
245