sip: integrate PJSIP pjmedia G.722 and G.711 codecs and direct aplay ringbuffer playout
This commit is contained in:
1 parent
0af39d9fa0
commit
83dd79fe76
6 files changed
+619
-353
No files matched your search
+182
-352
@@ -12,6 +12,7 @@
|
||||
|
||||
#include "../sxmo-dwm/dwm_plugin.h"
|
||||
#include "net_tls.h"
|
||||
#include "pjsip_media.h"
|
||||
|
||||
#include <openssl/aes.h>
|
||||
#include <openssl/bn.h>
|
||||
@@ -26,7 +27,10 @@
|
||||
#include <gsm.h>
|
||||
#endif
|
||||
|
||||
#include <sys/timerfd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <deque>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
@@ -148,63 +152,21 @@ std::string cyclePreferredCodec(const std::string& cur) {
|
||||
return "AUTO";
|
||||
}
|
||||
|
||||
// G.711 u-law and A-law codecs (ITU-T G.711)
|
||||
// G.711 u-law and A-law codecs (via PJSIP / pjmedia alaw_ulaw)
|
||||
uint8_t linearToUlaw(int16_t pcmVal) {
|
||||
constexpr int kBias = 0x84;
|
||||
constexpr int kClip = 32635;
|
||||
int pcm = pcmVal;
|
||||
int mask = (pcm < 0) ? 0x7f : 0xff;
|
||||
if (pcm < 0) pcm = -pcm;
|
||||
if (pcm > kClip) pcm = kClip;
|
||||
pcm += kBias;
|
||||
int seg = 0;
|
||||
for (int thr = 0xFF; seg < 7 && pcm > thr; ++seg, thr = (thr << 1) | 1) {
|
||||
}
|
||||
uint8_t uval = static_cast<uint8_t>((seg << 4) | ((pcm >> (seg + 3)) & 0x0f));
|
||||
return static_cast<uint8_t>(uval ^ mask);
|
||||
return pjsip::linear2ulaw(pcmVal);
|
||||
}
|
||||
|
||||
int16_t ulawToLinear(uint8_t uval) {
|
||||
uval = static_cast<uint8_t>(~uval);
|
||||
int t = (((uval & 0x0f) << 3) + 0x84) << ((uval & 0x70) >> 4);
|
||||
return static_cast<int16_t>((uval & 0x80) ? (0x84 - t) : (t - 0x84));
|
||||
return pjsip::ulaw2linear(uval);
|
||||
}
|
||||
|
||||
uint8_t linearToAlaw(int16_t pcmVal) {
|
||||
int pcm = pcmVal;
|
||||
int mask = 0x55;
|
||||
if (pcm >= 0) {
|
||||
mask |= 0x80;
|
||||
} else {
|
||||
pcm = -pcm - 1;
|
||||
}
|
||||
if (pcm > 32767) pcm = 32767;
|
||||
int seg = 0;
|
||||
for (int thr = 0xFF; seg < 7 && pcm > thr; ++seg, thr = (thr << 1) | 1) {
|
||||
}
|
||||
uint8_t aval = (seg == 0)
|
||||
? static_cast<uint8_t>((pcm >> 4) & 0x0f)
|
||||
: static_cast<uint8_t>((seg << 4) | ((pcm >> (seg + 3)) & 0x0f));
|
||||
return static_cast<uint8_t>(aval ^ mask);
|
||||
return pjsip::linear2alaw(pcmVal);
|
||||
}
|
||||
|
||||
int16_t alawToLinear(uint8_t aval) {
|
||||
aval ^= 0x55;
|
||||
int t = (aval & 0x0f) << 4;
|
||||
int seg = (static_cast<unsigned>(aval) & 0x70) >> 4;
|
||||
switch (seg) {
|
||||
case 0:
|
||||
t += 8;
|
||||
break;
|
||||
case 1:
|
||||
t += 0x108;
|
||||
break;
|
||||
default:
|
||||
t += 0x108;
|
||||
t <<= seg - 1;
|
||||
break;
|
||||
}
|
||||
return static_cast<int16_t>((aval & 0x80) ? t : -t);
|
||||
return pjsip::alaw2linear(aval);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -381,229 +343,10 @@ struct G726_32State {
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// ITU-T G.722 Wideband 16 kHz (64 kbps SB-ADPCM) Codec (RFC 3551 PT 9)
|
||||
// ITU-T G.722 Wideband 16 kHz (64 kbps SB-ADPCM) Codec (via PJSIP / pjmedia)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class G722State {
|
||||
public:
|
||||
G722State() { reset(); }
|
||||
|
||||
void reset() {
|
||||
band_[0] = Band{};
|
||||
band_[1] = Band{};
|
||||
band_[0].det = 32;
|
||||
band_[1].det = 8;
|
||||
std::memset(txQmf_, 0, sizeof(txQmf_));
|
||||
std::memset(rxQmf_, 0, sizeof(rxQmf_));
|
||||
}
|
||||
|
||||
size_t encodeFrame(const int16_t* pcm16k, size_t numSamples, uint8_t* outBuf) {
|
||||
size_t outIdx = 0;
|
||||
for (size_t i = 0; i + 1 < numSamples; i += 2) {
|
||||
// 24-tap QMF analysis filter
|
||||
for (int j = 23; j >= 2; --j) {
|
||||
txQmf_[j] = txQmf_[j - 2];
|
||||
}
|
||||
txQmf_[1] = pcm16k[i];
|
||||
txQmf_[0] = pcm16k[i + 1];
|
||||
|
||||
int sumEven = 0;
|
||||
int sumOdd = 0;
|
||||
for (int j = 0; j < 12; ++j) {
|
||||
sumEven += txQmf_[2 * j] * kQmfCoeffs[j];
|
||||
sumOdd += txQmf_[2 * j + 1] * kQmfCoeffs[11 - j];
|
||||
}
|
||||
int xlow = std::clamp((sumEven + sumOdd) >> 14, -16384, 16383);
|
||||
int xhigh = std::clamp((sumEven - sumOdd) >> 14, -16384, 16383);
|
||||
|
||||
// Lower sub-band (6-bit quantizer)
|
||||
int el = std::clamp(xlow - band_[0].s, -16384, 16383);
|
||||
int wd = (el >= 0) ? el : -(el + 1);
|
||||
int mila = 0;
|
||||
for (int m = 1; m < 30; ++m) {
|
||||
if (wd < ((kQ6[m] * band_[0].det) >> 12)) break;
|
||||
mila = m;
|
||||
}
|
||||
int il = (el < 0) ? kMisn[mila] : kMisp[mila];
|
||||
int ril = il >> 2;
|
||||
int dlt = (band_[0].det * kQ6m4[ril]) >> 15;
|
||||
updateBand(0, dlt, ril, true);
|
||||
|
||||
// Higher sub-band (2-bit quantizer)
|
||||
int eh = std::clamp(xhigh - band_[1].s, -16384, 16383);
|
||||
int wdh = (eh >= 0) ? eh : -(eh + 1);
|
||||
int mih = (wdh >= ((564 * band_[1].det) >> 12)) ? 2 : 1;
|
||||
int ih = (eh < 0) ? ((mih == 1) ? 1 : 0) : ((mih == 1) ? 3 : 2);
|
||||
int dhy = (band_[1].det * kQm2[ih]) >> 15;
|
||||
updateBand(1, dhy, ih, false);
|
||||
|
||||
outBuf[outIdx++] = static_cast<uint8_t>(((ih & 0x03) << 6) | (il & 0x3f));
|
||||
}
|
||||
return outIdx;
|
||||
}
|
||||
|
||||
size_t decodeFrame(const uint8_t* inBuf, size_t inLen, int16_t* outPcm16k, size_t maxSamples) {
|
||||
size_t outCount = 0;
|
||||
for (size_t i = 0; i < inLen && outCount + 1 < maxSamples; ++i) {
|
||||
uint8_t code = inBuf[i];
|
||||
int il = code & 0x3f;
|
||||
int ih = (code >> 6) & 0x03;
|
||||
|
||||
// Lower sub-band reconstruction (6-bit)
|
||||
int ril = il >> 2;
|
||||
int dlt = (band_[0].det * kQ6b[il]) >> 15;
|
||||
int rlow = std::clamp(band_[0].s + dlt, -16384, 16383);
|
||||
updateBand(0, (band_[0].det * kQ6m4[ril]) >> 15, ril, true);
|
||||
|
||||
// Higher sub-band reconstruction (2-bit)
|
||||
int dhy = (band_[1].det * kQm2[ih]) >> 15;
|
||||
int rhigh = std::clamp(band_[1].s + dhy, -16384, 16383);
|
||||
updateBand(1, dhy, ih, false);
|
||||
|
||||
// 24-tap QMF synthesis filter
|
||||
for (int j = 23; j >= 2; --j) {
|
||||
rxQmf_[j] = rxQmf_[j - 2];
|
||||
}
|
||||
rxQmf_[1] = rlow - rhigh;
|
||||
rxQmf_[0] = rlow + rhigh;
|
||||
|
||||
int sumA = 0;
|
||||
int sumB = 0;
|
||||
for (int j = 0; j < 12; ++j) {
|
||||
sumA += rxQmf_[2 * j] * kQmfCoeffs[j];
|
||||
sumB += rxQmf_[2 * j + 1] * kQmfCoeffs[11 - j];
|
||||
}
|
||||
outPcm16k[outCount++] = static_cast<int16_t>(std::clamp(sumB >> 13, -32768, 32767));
|
||||
outPcm16k[outCount++] = static_cast<int16_t>(std::clamp(sumA >> 13, -32768, 32767));
|
||||
}
|
||||
return outCount;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Band {
|
||||
int s = 0;
|
||||
int sp = 0;
|
||||
int sz = 0;
|
||||
int r[3] {};
|
||||
int a[3] {};
|
||||
int ap[3] {};
|
||||
int p[3] {};
|
||||
int d[7] {};
|
||||
int b[7] {};
|
||||
int bp[7] {};
|
||||
int sg[7] {};
|
||||
int nb = 0;
|
||||
int det = 32;
|
||||
};
|
||||
|
||||
void updateBand(int bIdx, int dlt, int idx, bool isLow) {
|
||||
Band& b = band_[bIdx];
|
||||
b.d[0] = dlt;
|
||||
b.r[0] = std::clamp(b.s + dlt, -16384, 16383);
|
||||
b.p[0] = std::clamp(b.sz + dlt, -16384, 16383);
|
||||
|
||||
// Adaptive zero section
|
||||
for (int i = 1; i <= 6; ++i) {
|
||||
int wd1 = (dlt == 0) ? 0 : (((dlt ^ b.d[i]) >= 0) ? 128 : -128);
|
||||
int wd2 = (b.b[i] * 32640) >> 15;
|
||||
b.bp[i] = std::clamp(wd1 + wd2, -32768, 32767);
|
||||
}
|
||||
|
||||
// Adaptive pole section
|
||||
b.sg[0] = (b.p[0] >= 0) ? 0 : 1;
|
||||
b.sg[1] = (b.p[1] >= 0) ? 0 : 1;
|
||||
b.sg[2] = (b.p[2] >= 0) ? 0 : 1;
|
||||
|
||||
int wd1 = std::clamp(b.a[1], -8191, 8191);
|
||||
int wd2 = (b.sg[0] == b.sg[1]) ? -wd1 : wd1;
|
||||
if (wd2 > 32767) wd2 = 32767;
|
||||
int wd3 = (b.sg[0] == b.sg[2]) ? 128 : -128;
|
||||
wd3 += (wd2 >> 7);
|
||||
wd3 += (b.a[2] * 32512) >> 15;
|
||||
b.ap[2] = std::clamp(wd3, -12288, 12288);
|
||||
|
||||
int wd4 = (b.p[0] == 0) ? 0 : ((b.sg[0] == b.sg[1]) ? 192 : -192);
|
||||
int wd5 = (b.a[1] * 32640) >> 15;
|
||||
int limit = 15360 - b.ap[2];
|
||||
b.ap[1] = std::clamp(wd4 + wd5, -limit, limit);
|
||||
|
||||
// Log scale factor adaptation
|
||||
int wl = isLow ? kWl[idx] : kWh[idx];
|
||||
b.nb = std::clamp(((b.nb * 127) >> 7) + wl, 0, isLow ? 18432 : 22528);
|
||||
int shift = (b.nb >> 11) + (isLow ? 0 : 2);
|
||||
int ilb = kIlb[(b.nb & 0x7ff) >> 6];
|
||||
b.det = std::max(1, (shift >= 9) ? (ilb << (shift - 9)) : (ilb >> (9 - shift)));
|
||||
|
||||
// Shift delay lines and compute new predictor outputs
|
||||
for (int i = 6; i >= 1; --i) {
|
||||
b.d[i] = b.d[i - 1];
|
||||
b.b[i] = b.bp[i];
|
||||
}
|
||||
b.r[2] = b.r[1];
|
||||
b.r[1] = b.r[0];
|
||||
b.p[2] = b.p[1];
|
||||
b.p[1] = b.p[0];
|
||||
b.a[2] = b.ap[2];
|
||||
b.a[1] = b.ap[1];
|
||||
|
||||
b.sz = 0;
|
||||
for (int i = 1; i <= 6; ++i) {
|
||||
b.sz += (b.b[i] * b.d[i]) >> 14;
|
||||
}
|
||||
b.sz = std::clamp(b.sz, -16384, 16383);
|
||||
b.sp = std::clamp(((b.a[1] * b.r[1]) + (b.a[2] * b.r[2])) >> 14, -16384, 16383);
|
||||
b.s = std::clamp(b.sp + b.sz, -16384, 16383);
|
||||
}
|
||||
|
||||
static constexpr int kQmfCoeffs[12] = {
|
||||
3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11
|
||||
};
|
||||
static constexpr int kQ6[30] = {
|
||||
0, 35, 72, 110, 150, 190, 233, 276, 323, 370,
|
||||
422, 473, 530, 587, 650, 714, 786, 858, 940, 1023,
|
||||
1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195, 2557, 2919
|
||||
};
|
||||
static constexpr int kMisn[30] = {
|
||||
63, 62, 31, 30, 29, 28, 27, 26, 25, 24,
|
||||
23, 22, 21, 20, 19, 18, 17, 16, 15, 14,
|
||||
13, 12, 11, 10, 9, 8, 7, 6, 5, 4
|
||||
};
|
||||
static constexpr int kMisp[30] = {
|
||||
61, 60, 59, 58, 57, 56, 55, 54, 53, 52,
|
||||
51, 50, 49, 48, 47, 46, 45, 44, 43, 42,
|
||||
41, 40, 39, 38, 37, 36, 35, 34, 33, 32
|
||||
};
|
||||
static constexpr int kQ6m4[16] = {
|
||||
0, -20456, -12896, -8968, -6288, -4240, -2584, -1200,
|
||||
20456, 12896, 8968, 6288, 4240, 2584, 1200, 0
|
||||
};
|
||||
static constexpr int kQ6b[64] = {
|
||||
-136, -136, -136, -136, -24808, -21904, -19008, -16704,
|
||||
-14984, -13512, -12280, -11192, -10232, -9360, -8576, -7856,
|
||||
-7192, -6576, -6000, -5456, -4944, -4464, -4008, -3576,
|
||||
-3168, -2776, -2400, -2032, -1688, -1360, -1040, -728,
|
||||
24808, 21904, 19008, 16704, 14984, 13512, 12280, 11192,
|
||||
10232, 9360, 8576, 7856, 7192, 6576, 6000, 5456,
|
||||
4944, 4464, 4008, 3576, 3168, 2776, 2400, 2032,
|
||||
1688, 1360, 1040, 728, 432, 136, -432, -136
|
||||
};
|
||||
static constexpr int kQm2[4] = { -7408, -1616, 7408, 1616 };
|
||||
static constexpr int kWl[16] = {
|
||||
-60, 3042, 1198, 538, 334, 172, 58, -30,
|
||||
3042, 1198, 538, 334, 172, 58, -30, -60
|
||||
};
|
||||
static constexpr int kWh[4] = { 798, -214, 798, -214 };
|
||||
static constexpr int kIlb[32] = {
|
||||
2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383,
|
||||
2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,
|
||||
2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,
|
||||
3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008
|
||||
};
|
||||
|
||||
Band band_[2];
|
||||
int txQmf_[24] {};
|
||||
int rxQmf_[24] {};
|
||||
};
|
||||
using G722State = pjsip::G722Codec;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// RFC 6189 ZRTP & RFC 3711 SRTP Cryptographic Helpers
|
||||
@@ -1404,11 +1147,11 @@ bool codecMatchesPreference(SipCodecId id, const std::string& pref) {
|
||||
|
||||
std::vector<SipCodecId> orderedCodecsForPreference(const std::string& pref) {
|
||||
static const SipCodecId kDefaultOrder[] = {
|
||||
SipCodecId::G722,
|
||||
SipCodecId::Opus,
|
||||
SipCodecId::Pcmu,
|
||||
SipCodecId::Pcma,
|
||||
SipCodecId::Gsm,
|
||||
SipCodecId::Opus,
|
||||
SipCodecId::G722,
|
||||
SipCodecId::G726_32,
|
||||
SipCodecId::Dvi4_8k,
|
||||
SipCodecId::Dvi4_16k,
|
||||
@@ -1582,20 +1325,9 @@ void parseSdpMedia(const std::string& msg, const std::string& preferredCodec,
|
||||
}
|
||||
}
|
||||
|
||||
// 2. In AUTO mode, prefer our ordered priority list (G.711 PCMU/PCMA first)
|
||||
// among all codecs offered by the peer.
|
||||
for (SipCodecId prefId : orderedCodecsForPreference("AUTO")) {
|
||||
for (int pt : offeredPts) {
|
||||
auto it = outPtMap.find(pt);
|
||||
if (it != outPtMap.end() && it->second == prefId) {
|
||||
outCodec = it->second;
|
||||
outPayloadType = pt;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Otherwise pick the first mutually supported codec in peer's m=audio line
|
||||
// 2. Auto-negotiate per RFC 3264: pick the first mutually supported codec in
|
||||
// the remote peer's m=audio line (offeredPts[0] is the codec the remote
|
||||
// peer selected and will transmit).
|
||||
for (int pt : offeredPts) {
|
||||
auto it = outPtMap.find(pt);
|
||||
if (it != outPtMap.end()) {
|
||||
@@ -1640,8 +1372,9 @@ class RtpAudioSession {
|
||||
return false;
|
||||
}
|
||||
if (running_.load() && sock_ >= 0 && remoteIp == activeRemoteIp_ &&
|
||||
remotePort == activeRemotePort_ && codec == codec_ &&
|
||||
payloadType == payloadType_) {
|
||||
remotePort == activeRemotePort_) {
|
||||
codec_.store(codec);
|
||||
payloadType_.store(payloadType);
|
||||
dtmfPt_ = (dtmfPt > 0 && dtmfPt <= 127) ? dtmfPt : 101;
|
||||
return true;
|
||||
}
|
||||
@@ -1694,8 +1427,9 @@ class RtpAudioSession {
|
||||
remAddr_ = remAddr;
|
||||
activeRemoteIp_ = remoteIp;
|
||||
activeRemotePort_ = remotePort;
|
||||
codec_ = codec;
|
||||
payloadType_ = payloadType;
|
||||
codec_.store(codec);
|
||||
payloadType_.store(payloadType);
|
||||
codecChanged_.store(false);
|
||||
dtmfPt_ = (dtmfPt > 0 && dtmfPt <= 127) ? dtmfPt : 101;
|
||||
rxPtMap_ = ptMap;
|
||||
rxPtMap_[payloadType] = codec;
|
||||
@@ -1731,8 +1465,14 @@ class RtpAudioSession {
|
||||
}
|
||||
|
||||
bool isZrtpSecure() const { return zrtpSecure_.load(); }
|
||||
SipCodecId activeCodec() const { return codec_; }
|
||||
const char* activeCodecName() const { return codecShortName(codec_); }
|
||||
SipCodecId activeCodec() const { return codec_.load(); }
|
||||
const char* activeCodecName() const { return codecShortName(codec_.load()); }
|
||||
|
||||
bool consumeCodecNotification(SipCodecId& outCodec) {
|
||||
if (!codecChanged_.exchange(false)) return false;
|
||||
outCodec = codec_.load();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool consumeZrtpNotification(std::string& outSas) {
|
||||
if (!zrtpSecure_.load() || zrtpNotified_.load()) return false;
|
||||
@@ -2350,10 +2090,13 @@ class RtpAudioSession {
|
||||
void runLoop() {
|
||||
::system("amixer -c 0 cset \"name='PRI_MI2S_RX Audio Mixer MultiMedia1'\" 1 >/dev/null 2>&1; "
|
||||
"amixer -c 0 cset \"name='MultiMedia2 Mixer TERT_MI2S_TX'\" 1 >/dev/null 2>&1");
|
||||
int audioRate = codecAudioSampleRate(codec_);
|
||||
size_t frameSamples = static_cast<size_t>(audioRate / 50); // 160 @ 8k, 320 @ 16k
|
||||
size_t frameBytes = frameSamples * sizeof(int16_t);
|
||||
std::string rateStr = std::to_string(audioRate);
|
||||
|
||||
// Always run ALSA/PipeWire capture & playback at 16000 Hz so wideband
|
||||
// (G.722, Opus, DVI4-16k, L16-16k) and narrowband (G.711 PCMU/PCMA, GSM,
|
||||
// G.726-32, DVI4-8k, L16-8k) codecs can switch dynamically without
|
||||
// reopening audio pipes.
|
||||
constexpr size_t kFrameSamples16k = 320; // 20 ms @ 16000 Hz
|
||||
constexpr size_t kFrameBytes16k = kFrameSamples16k * sizeof(int16_t);
|
||||
|
||||
int capPipe[2] = {-1, -1};
|
||||
int capFd = -1;
|
||||
@@ -2371,7 +2114,7 @@ class RtpAudioSession {
|
||||
if (nullFd > 2) ::close(nullFd);
|
||||
}
|
||||
::execlp("arecord", "arecord", "-q", "--buffer-time=160000",
|
||||
"--period-time=20000", "-f", "S16_LE", "-r", rateStr.c_str(),
|
||||
"--period-time=20000", "-f", "S16_LE", "-r", "16000",
|
||||
"-c", "1", "-t", "raw", static_cast<char*>(nullptr));
|
||||
::_exit(1);
|
||||
} else if (capPid > 0) {
|
||||
@@ -2401,8 +2144,9 @@ class RtpAudioSession {
|
||||
::dup2(nullFd, STDERR_FILENO);
|
||||
if (nullFd > 2) ::close(nullFd);
|
||||
}
|
||||
::execlp("aplay", "aplay", "-q", "--buffer-time=200000",
|
||||
"--period-time=20000", "-f", "S16_LE", "-r", rateStr.c_str(),
|
||||
::execlp("aplay", "aplay", "-q", "--buffer-time=160000",
|
||||
"--period-time=20000", "--start-delay=60000",
|
||||
"-f", "S16_LE", "-r", "16000",
|
||||
"-c", "1", "-t", "raw", static_cast<char*>(nullptr));
|
||||
::_exit(1);
|
||||
} else if (playPid > 0) {
|
||||
@@ -2417,6 +2161,14 @@ class RtpAudioSession {
|
||||
}
|
||||
}
|
||||
|
||||
int timerFd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
|
||||
if (timerFd >= 0) {
|
||||
struct itimerspec its {};
|
||||
its.it_value.tv_nsec = 20000000;
|
||||
its.it_interval.tv_nsec = 20000000;
|
||||
::timerfd_settime(timerFd, 0, &its, nullptr);
|
||||
}
|
||||
|
||||
int opusErr = OPUS_OK;
|
||||
OpusEncoder* opusEnc = opus_encoder_create(16000, 1, OPUS_APPLICATION_VOIP, &opusErr);
|
||||
if (opusEnc) {
|
||||
@@ -2440,16 +2192,29 @@ class RtpAudioSession {
|
||||
uint32_t ts = static_cast<uint32_t>(nowMs() * 8);
|
||||
uint32_t ssrc = 0x51504241u ^ static_cast<uint32_t>(::getpid());
|
||||
int64_t nextTxMs = nowMs() + 20;
|
||||
bool playPrimed = false;
|
||||
uint8_t capRing[2560];
|
||||
|
||||
uint8_t capRing[3840];
|
||||
size_t capAvail = 0;
|
||||
|
||||
bool playPrimed = false;
|
||||
int64_t lastRxAudioMs = 0;
|
||||
int16_t lastRx8k = 0;
|
||||
bool hasLastRx8k = false;
|
||||
|
||||
while (running_.load()) {
|
||||
// Drain available microphone capture bytes into capRing without blocking
|
||||
if (capFd >= 0 && capAvail < sizeof(capRing)) {
|
||||
ssize_t r = ::read(capFd, capRing + capAvail, sizeof(capRing) - capAvail);
|
||||
if (r > 0) {
|
||||
capAvail += static_cast<size_t>(r);
|
||||
// Cap capture latency at 120 ms (1920 samples = 3840 bytes)
|
||||
if (capAvail > 2560) {
|
||||
size_t drop = ((capAvail - 1280) / kFrameBytes16k) * kFrameBytes16k;
|
||||
if (drop > 0 && drop <= capAvail) {
|
||||
capAvail -= drop;
|
||||
std::memmove(capRing, capRing + drop, capAvail);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2475,12 +2240,20 @@ class RtpAudioSession {
|
||||
if (!unprotectRtpPacket(rxPkt, pktLen, hdrLen)) {
|
||||
continue;
|
||||
}
|
||||
if (pt == dtmfPt_) continue;
|
||||
if (pt == dtmfPt_ || pt == 13 || pt == 19) continue;
|
||||
|
||||
auto itCodec = rxPtMap_.find(pt);
|
||||
if (itCodec == rxPtMap_.end()) continue;
|
||||
SipCodecId rxCodec = itCodec->second;
|
||||
|
||||
// Auto-negotiate / adapt TX codec if peer transmits a different
|
||||
// supported audio payload type than initially assumed.
|
||||
if (rxCodec != codec_.load() || pt != payloadType_.load()) {
|
||||
codec_.store(rxCodec);
|
||||
payloadType_.store(pt);
|
||||
codecChanged_.store(true);
|
||||
}
|
||||
|
||||
const uint8_t* payload = rxPkt + hdrLen;
|
||||
size_t payLen = pktLen - hdrLen;
|
||||
if (playFd < 0 || payLen == 0) continue;
|
||||
@@ -2540,45 +2313,59 @@ class RtpAudioSession {
|
||||
}
|
||||
|
||||
if (decodedSamples > 0) {
|
||||
if (!playPrimed) {
|
||||
int64_t rxNow = nowMs();
|
||||
if (!playPrimed || (rxNow - lastRxAudioMs > 220)) {
|
||||
int16_t prefill[640] = {0};
|
||||
(void)::write(playFd, prefill, sizeof(prefill));
|
||||
playPrimed = true;
|
||||
int16_t silence[960] = {0};
|
||||
(void)::write(playFd, silence, frameSamples * 3 * sizeof(int16_t));
|
||||
}
|
||||
lastRxAudioMs = rxNow;
|
||||
|
||||
int rxRate = codecAudioSampleRate(rxCodec);
|
||||
if (rxRate == audioRate) {
|
||||
if (rxRate == 8000) {
|
||||
int16_t pcm16kOut[3840];
|
||||
size_t outCount = 0;
|
||||
for (size_t i = 0; i < decodedSamples && outCount + 1 < 3840; ++i) {
|
||||
int16_t s = pcmDecoded[i];
|
||||
int16_t prev = hasLastRx8k ? lastRx8k : s;
|
||||
pcm16kOut[outCount++] =
|
||||
static_cast<int16_t>((static_cast<int>(prev) + s) / 2);
|
||||
pcm16kOut[outCount++] = s;
|
||||
lastRx8k = s;
|
||||
hasLastRx8k = true;
|
||||
}
|
||||
(void)::write(playFd, pcm16kOut, outCount * sizeof(int16_t));
|
||||
} else {
|
||||
(void)::write(playFd, pcmDecoded, decodedSamples * sizeof(int16_t));
|
||||
} else if (rxRate == 8000 && audioRate == 16000) {
|
||||
int16_t pcmUp[1920];
|
||||
size_t upCount = 0;
|
||||
for (size_t i = 0; i < decodedSamples && upCount + 1 < 1920; ++i) {
|
||||
int16_t s0 = pcmDecoded[i];
|
||||
int16_t s1 = (i + 1 < decodedSamples) ? pcmDecoded[i + 1] : s0;
|
||||
pcmUp[upCount++] = s0;
|
||||
pcmUp[upCount++] = static_cast<int16_t>((static_cast<int>(s0) + s1) / 2);
|
||||
}
|
||||
(void)::write(playFd, pcmUp, upCount * sizeof(int16_t));
|
||||
} else if (rxRate == 16000 && audioRate == 8000) {
|
||||
int16_t pcmDown[960];
|
||||
size_t downCount = 0;
|
||||
for (size_t i = 0; i + 1 < decodedSamples && downCount < 960; i += 2) {
|
||||
pcmDown[downCount++] = static_cast<int16_t>(
|
||||
(static_cast<int>(pcmDecoded[i]) + pcmDecoded[i + 1]) / 2);
|
||||
}
|
||||
(void)::write(playFd, pcmDown, downCount * sizeof(int16_t));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Transmit 20ms audio frame or RFC 2833 DTMF event + ZRTP tick
|
||||
int64_t now = nowMs();
|
||||
periodicZrtpTick(ssrc, now);
|
||||
|
||||
if (now >= nextTxMs) {
|
||||
nextTxMs += 20;
|
||||
if (now - nextTxMs > 60) {
|
||||
nextTxMs = now + 20;
|
||||
// 2. Process 20 ms transmit ticks
|
||||
uint64_t ticks = 0;
|
||||
if (timerFd >= 0) {
|
||||
uint64_t exp = 0;
|
||||
if (::read(timerFd, &exp, sizeof(exp)) == sizeof(exp) && exp > 0) {
|
||||
ticks = std::min<uint64_t>(exp, 3);
|
||||
}
|
||||
} else {
|
||||
int64_t now = nowMs();
|
||||
if (now >= nextTxMs) {
|
||||
ticks = 1;
|
||||
nextTxMs += 20;
|
||||
if (now - nextTxMs > 60) nextTxMs = now + 20;
|
||||
}
|
||||
}
|
||||
|
||||
if (ticks > 0) {
|
||||
int64_t now = nowMs();
|
||||
periodicZrtpTick(ssrc, now);
|
||||
}
|
||||
|
||||
for (uint64_t t = 0; t < ticks; ++t) {
|
||||
// Transmit 20 ms RTP audio frame or RFC 2833 DTMF event
|
||||
SipCodecId txCodec = codec_.load();
|
||||
int txPt = payloadType_.load();
|
||||
char dtmfCh = '\0';
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(dtmfMtx_);
|
||||
@@ -2612,20 +2399,33 @@ class RtpAudioSession {
|
||||
reinterpret_cast<const struct sockaddr*>(&remAddr_),
|
||||
sizeof(remAddr_));
|
||||
}
|
||||
ts += codecRtpTimestampStep20ms(codec_) * 3;
|
||||
ts += codecRtpTimestampStep20ms(txCodec) * 3;
|
||||
} else {
|
||||
int16_t pcmIn[320] = {0};
|
||||
if (capAvail >= frameBytes) {
|
||||
std::memcpy(pcmIn, capRing, frameBytes);
|
||||
capAvail -= frameBytes;
|
||||
int16_t pcm16k[kFrameSamples16k] = {0};
|
||||
if (capAvail >= kFrameBytes16k) {
|
||||
std::memcpy(pcm16k, capRing, kFrameBytes16k);
|
||||
capAvail -= kFrameBytes16k;
|
||||
if (capAvail > 0) {
|
||||
std::memmove(capRing, capRing + frameBytes, capAvail);
|
||||
std::memmove(capRing, capRing + kFrameBytes16k, capAvail);
|
||||
}
|
||||
}
|
||||
|
||||
int16_t pcm8k[160];
|
||||
const int16_t* pcmIn = pcm16k;
|
||||
size_t frameSamples = kFrameSamples16k;
|
||||
if (codecAudioSampleRate(txCodec) == 8000) {
|
||||
for (size_t i = 0; i < 160; ++i) {
|
||||
pcm8k[i] = static_cast<int16_t>(
|
||||
(static_cast<int>(pcm16k[2 * i]) + pcm16k[2 * i + 1]) / 2);
|
||||
}
|
||||
pcmIn = pcm8k;
|
||||
frameSamples = 160;
|
||||
}
|
||||
|
||||
uint8_t pkt[12 + 768 + 16];
|
||||
uint16_t curSeq = seq++;
|
||||
pkt[0] = 0x80;
|
||||
pkt[1] = static_cast<uint8_t>(payloadType_ & 0x7f);
|
||||
pkt[1] = static_cast<uint8_t>(txPt & 0x7f);
|
||||
uint16_t netSeq = htons(curSeq);
|
||||
uint32_t netTs = htonl(ts);
|
||||
uint32_t netSsrc = htonl(ssrc);
|
||||
@@ -2634,7 +2434,7 @@ class RtpAudioSession {
|
||||
std::memcpy(pkt + 8, &netSsrc, 4);
|
||||
|
||||
size_t encBytes = 0;
|
||||
switch (codec_) {
|
||||
switch (txCodec) {
|
||||
case SipCodecId::Opus:
|
||||
if (opusEnc) {
|
||||
int r = opus_encode(opusEnc, pcmIn, static_cast<int>(frameSamples),
|
||||
@@ -2659,7 +2459,8 @@ class RtpAudioSession {
|
||||
break;
|
||||
case SipCodecId::Gsm:
|
||||
if (gsmEnc) {
|
||||
gsm_encode(gsmEnc, pcmIn, reinterpret_cast<gsm_byte*>(pkt + 12));
|
||||
gsm_encode(gsmEnc, const_cast<gsm_signal*>(pcmIn),
|
||||
reinterpret_cast<gsm_byte*>(pkt + 12));
|
||||
encBytes = 33;
|
||||
}
|
||||
break;
|
||||
@@ -2688,15 +2489,21 @@ class RtpAudioSession {
|
||||
sizeof(remAddr_));
|
||||
++txAudioFrames_;
|
||||
}
|
||||
ts += codecRtpTimestampStep20ms(codec_);
|
||||
ts += codecRtpTimestampStep20ms(txCodec);
|
||||
}
|
||||
}
|
||||
|
||||
struct pollfd pfd { sock_, POLLIN, 0 };
|
||||
int waitMs = static_cast<int>(std::max<int64_t>(2, nextTxMs - nowMs()));
|
||||
::poll(&pfd, 1, std::min(waitMs, 20));
|
||||
struct pollfd pfds[3] {};
|
||||
int nfds = 0;
|
||||
pfds[nfds++] = { sock_, POLLIN, 0 };
|
||||
if (timerFd >= 0) pfds[nfds++] = { timerFd, POLLIN, 0 };
|
||||
if (capFd >= 0 && capAvail < sizeof(capRing)) {
|
||||
pfds[nfds++] = { capFd, POLLIN, 0 };
|
||||
}
|
||||
::poll(pfds, nfds, 20);
|
||||
}
|
||||
|
||||
if (timerFd >= 0) ::close(timerFd);
|
||||
if (opusEnc) opus_encoder_destroy(opusEnc);
|
||||
if (opusDec) opus_decoder_destroy(opusDec);
|
||||
if (gsmEnc) gsm_destroy(gsmEnc);
|
||||
@@ -2719,8 +2526,9 @@ class RtpAudioSession {
|
||||
struct sockaddr_in remAddr_ {};
|
||||
std::string activeRemoteIp_;
|
||||
int activeRemotePort_ = 0;
|
||||
SipCodecId codec_ = SipCodecId::Pcmu;
|
||||
int payloadType_ = 0;
|
||||
std::atomic<SipCodecId> codec_{SipCodecId::Pcmu};
|
||||
std::atomic<int> payloadType_{0};
|
||||
std::atomic<bool> codecChanged_{false};
|
||||
int dtmfPt_ = 101;
|
||||
std::map<int, SipCodecId> rxPtMap_;
|
||||
std::atomic<bool> running_{false};
|
||||
@@ -2783,6 +2591,13 @@ class RtpAudioSession {
|
||||
|
||||
int sip_run_main(int argc, char** argv) {
|
||||
gRunning = 1;
|
||||
const char* xdgDir = ::getenv("XDG_RUNTIME_DIR");
|
||||
if (!xdgDir || !xdgDir[0] || ::access(xdgDir, F_OK) != 0) {
|
||||
std::string fallbackDir = "/run/user/" + std::to_string(::getuid());
|
||||
if (::access(fallbackDir.c_str(), F_OK) == 0) {
|
||||
::setenv("XDG_RUNTIME_DIR", fallbackDir.c_str(), 1);
|
||||
}
|
||||
}
|
||||
bool isPreload = false;
|
||||
std::string initCmd;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
@@ -2962,14 +2777,18 @@ int sip_run_main(int argc, char** argv) {
|
||||
int answerPt = -1,
|
||||
int dtmfPt = 101) -> std::string {
|
||||
std::vector<std::pair<int, SipCodecId>> mediaCodecs;
|
||||
std::string normPref = normalizePreferredCodec(preferredCodec);
|
||||
if (answerCodec && answerPt >= 0) {
|
||||
mediaCodecs.push_back({answerPt, *answerCodec});
|
||||
}
|
||||
for (SipCodecId c : orderedCodecsForPreference(preferredCodec)) {
|
||||
if (answerCodec && c == *answerCodec) continue;
|
||||
int pt = codecDefaultPt(c);
|
||||
if (answerPt == pt || dtmfPt == pt) continue;
|
||||
mediaCodecs.push_back({pt, c});
|
||||
} else {
|
||||
for (SipCodecId c : orderedCodecsForPreference(normPref)) {
|
||||
if (normPref != "AUTO" && !codecMatchesPreference(c, normPref)) {
|
||||
continue;
|
||||
}
|
||||
int pt = codecDefaultPt(c);
|
||||
if (dtmfPt == pt) continue;
|
||||
mediaCodecs.push_back({pt, c});
|
||||
}
|
||||
}
|
||||
|
||||
std::ostringstream sdp;
|
||||
@@ -3816,8 +3635,19 @@ int sip_run_main(int argc, char** argv) {
|
||||
}
|
||||
}
|
||||
|
||||
// 2b. Check if ZRTP completed handshake on active call
|
||||
// 2b. Check if RTP codec auto-adapted or ZRTP completed handshake on active call
|
||||
if (callState == SipCallState::Active) {
|
||||
SipCodecId newCodec = SipCodecId::Pcmu;
|
||||
if (rtpSession.consumeCodecNotification(newCodec)) {
|
||||
remoteCodec = newCodec;
|
||||
std::string badge = std::string("SIP/") + rtpSession.activeCodecName();
|
||||
if (rtpSession.isZrtpSecure()) {
|
||||
badge += ":" + rtpSession.getZrtpSas();
|
||||
}
|
||||
sendPluginCommand("callscreen",
|
||||
"ACTIVE sip:1 " + activePeerUri + " " + badge);
|
||||
if (visible) render();
|
||||
}
|
||||
std::string sas;
|
||||
if (rtpSession.consumeZrtpNotification(sas)) {
|
||||
sendPluginCommand("callscreen",
|
||||
|
||||
Reference in new issue
Block a user