audio_rtp_session.cpp 8.14 KB
Newer Older
1
/*
2
 *  Copyright (C) 2004-2012 Savoir-Faire Linux Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 *  Author: Pierre-Luc Bacon <pierre-luc.bacon@savoirfairelinux.com>
 *  Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
 *  Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
 *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Additional permission under GNU GPL version 3 section 7:
 *
 *  If you modify this program, or any covered work, by linking or
 *  combining it with the OpenSSL project's OpenSSL library (or a
 *  modified version of that library), containing parts covered by the
 *  terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc.
 *  grants you additional permission to convey the resulting work.
 *  Corresponding Source for a non-source form of such a combination
 *  shall include the source code for the parts of OpenSSL used as well
 *  as that of the covered work.
 */

35
#include "audio_rtp_session.h"
36
#include "logger.h"
37
#include "sip/sdp.h"
38
#include "sip/sipcall.h"
39
#include <ccrtp/oqueue.h>
40
#include "manager.h"
41

42
namespace sfl {
43 44 45
AudioRtpSession::AudioRtpSession(SIPCall &call, ost::RTPDataQueue &queue, ost::Thread &thread) :
    AudioRtpRecordHandler(call)
    , call_(call)
46 47
    , timestamp_(0)
    , timestampIncrement_(0)
48
    , transportRate_(20)
49
    , queue_(queue)
50 51 52 53
    , isStarted_(false)
    , remote_ip_()
    , remote_port_(0)
    , timestampCount_(0)
54
    , thread_(thread)
55
{
56
    queue_.setTypeOfService(ost::RTPDataQueue::tosEnhanced);
57 58 59 60
}

AudioRtpSession::~AudioRtpSession()
{
61
    queue_.disableStack();
62 63
}

64
void AudioRtpSession::updateSessionMedia(AudioCodec &audioCodec)
65
{
66
    int lastSamplingRate = audioRtpRecord_.codecSampleRate_;
67

68
    setSessionMedia(audioCodec);
69

70
    Manager::instance().audioSamplingRateChanged(audioRtpRecord_.codecSampleRate_);
71

72
#if HAVE_SPEEXDSP
73
    if (lastSamplingRate != audioRtpRecord_.codecSampleRate_) {
74 75
        DEBUG("Update noise suppressor with sampling rate %d and frame size %d",
              getCodecSampleRate(), getCodecFrameSize());
76
        initNoiseSuppress();
77
    }
78
#endif
79 80
}

81
void AudioRtpSession::setSessionMedia(AudioCodec &audioCodec)
82
{
83
    setRtpMedia(&audioCodec);
84

85
    // G722 requires timestamp to be incremented at 8kHz
86 87 88 89 90 91 92 93 94 95
    const ost::PayloadType payloadType = getCodecPayloadType();
    if (payloadType == ost::sptG722) {
        const int G722_RTP_TIME_INCREMENT = 160;
        timestampIncrement_ = G722_RTP_TIME_INCREMENT;
    } else
        timestampIncrement_ = getCodecFrameSize();

    if (payloadType == ost::sptG722) {
        const int G722_RTP_CLOCK_RATE = 8000;
        queue_.setPayloadFormat(ost::DynamicPayloadFormat( payloadType, G722_RTP_CLOCK_RATE));
96
    } else {
97 98 99 100
        if (getHasDynamicPayload())
            queue_.setPayloadFormat(ost::DynamicPayloadFormat(payloadType, getCodecSampleRate()));
        else
            queue_.setPayloadFormat(ost::StaticPayloadFormat(static_cast<ost::StaticPayloadType>(payloadType)));
101
    }
102 103 104 105 106 107

    call_.setRecordingSmplRate(getCodecSampleRate());

    int transportRate = getCodecFrameSize() / (getCodecSampleRate() / 1000);
    transportRate_ = (transportRate > 0)?transportRate:20;
    DEBUG("Switching to a transport rate of %d ms",transportRate_);
108
}
109

110
void AudioRtpSession::sendDtmfEvent()
111
{
112 113
    DTMFEvent &dtmf(audioRtpRecord_.dtmfQueue_.front());
    DEBUG("Send RTP Dtmf (%d)", dtmf.payload.event);
114

115 116
    const int increment = getIncrementForDTMF();
    timestamp_ += increment;
117 118 119 120 121

    // discard equivalent size of audio
    processDataEncode();

    // change Payload type for DTMF payload
122
    queue_.setPayloadFormat(ost::DynamicPayloadFormat((ost::PayloadType) getDtmfPayloadType(), 8000));
123

124 125 126 127
    // Set marker in case this is a new Event
    if (dtmf.newevent)
        queue_.setMark(true);
    queue_.sendImmediate(timestamp_, (const unsigned char *) (& (dtmf.payload)), sizeof (ost::RTPPacket::RFC2833Payload));
128

129 130 131 132 133 134 135
    // This is no longer a new event
    if (dtmf.newevent) {
        dtmf.newevent = false;
        queue_.setMark(false);
    }

    // restore the payload to audio
136 137
    const ost::StaticPayloadFormat pf(static_cast<ost::StaticPayloadType>(getCodecPayloadType()));
    queue_.setPayloadFormat(pf);
138 139 140 141 142 143 144 145 146

    // decrease length remaining to process for this event
    dtmf.length -= increment;
    dtmf.payload.duration++;
    // next packet is going to be the last one
    if ((dtmf.length - increment) < increment)
        dtmf.payload.ebit = true;
    if (dtmf.length < increment)
        audioRtpRecord_.dtmfQueue_.pop_front();
147 148 149
}


150
void AudioRtpSession::receiveSpeakerData()
151
{
152
    const ost::AppDataUnit* adu = queue_.getData(queue_.getFirstTimestamp());
153

154
    if (!adu)
155 156
        return;

157
    unsigned char* spkrDataIn = (unsigned char*) adu->getData(); // data in char
158
    size_t size = adu->getSize(); // size in char
159 160

    // DTMF over RTP, size must be over 4 in order to process it as voice data
161
    if (size > 4)
162
        processDataDecode(spkrDataIn, size, adu->getType());
163 164 165 166 167 168 169 170 171 172

    delete adu;
}


void AudioRtpSession::sendMicData()
{
    int compSize = processDataEncode();

    // if no data return
173
    if (compSize == 0)
174 175 176
        return;

    // Increment timestamp for outgoing packet
177
    timestamp_ += timestampIncrement_;
178

179
    // putData puts the data on RTP queue, sendImmediate bypass this queue
180
    queue_.sendImmediate(timestamp_, getMicDataEncoded(), compSize);
181 182 183
}


184
void AudioRtpSession::setSessionTimeouts()
185
{
186 187
    const int schedulingTimeout = 4000;
    const int expireTimeout = 1000000;
188
    DEBUG("Set session scheduling timeout (%d) and expireTimeout (%d)",
189
          schedulingTimeout, expireTimeout);
190

191 192
    queue_.setSchedulingTimeout(schedulingTimeout);
    queue_.setExpireTimeout(expireTimeout);
193 194
}

195
void AudioRtpSession::setDestinationIpAddress()
196 197
{
    // Store remote ip in case we would need to forget current destination
198
    remote_ip_ = ost::InetHostAddress(call_.getLocalSDP()->getRemoteIP().c_str());
199

200
    if (!remote_ip_) {
201
        WARN("Target IP address (%s) is not correct!",
202
              call_.getLocalSDP()->getRemoteIP().data());
203 204 205 206
        return;
    }

    // Store remote port in case we would need to forget current destination
207
    remote_port_ = (unsigned short) call_.getLocalSDP()->getRemoteAudioPort();
208

209
    DEBUG("New remote address for session: %s:%d",
210
          call_.getLocalSDP()->getRemoteIP().data(), remote_port_);
211

212
    if (!queue_.addDestination(remote_ip_, remote_port_)) {
213
        WARN("Can't add new destination to session!");
214 215 216 217
        return;
    }
}

218
void AudioRtpSession::updateDestinationIpAddress()
219
{
220
    DEBUG("Update destination ip address");
221 222 223 224

    // Destination address are stored in a list in ccrtp
    // This method remove the current destination entry

225
    if (!queue_.forgetDestination(remote_ip_, remote_port_, remote_port_ + 1))
226
        DEBUG("Did not remove previous destination");
227 228 229 230 231 232 233

    // new destination is stored in call
    // we just need to recall this method
    setDestinationIpAddress();
}


234
int AudioRtpSession::startRtpThread(AudioCodec &audiocodec)
235
{
236
    if (isStarted_)
237 238
        return 0;

239
    DEBUG("Starting main thread");
240

241
    isStarted_ = true;
242
    setSessionTimeouts();
243
    setSessionMedia(audiocodec);
244
    initBuffers();
245
#if HAVE_SPEEXDSP
246
    initNoiseSuppress();
247
#endif
248

249
    queue_.enableStack();
250 251
    thread_.start();
    return 0;
252 253 254
}


255
bool AudioRtpSession::onRTPPacketRecv(ost::IncomingRTPPkt&)
256 257 258 259 260
{
    receiveSpeakerData();
    return true;
}

261 262 263 264 265
int AudioRtpSession::getIncrementForDTMF() const
{
    return timestampIncrement_;
}

266
}