From 1a150eb79fc9c041622a63d51e9a1adfd47c8bcd Mon Sep 17 00:00:00 2001 From: Anton Date: Tue, 29 Jun 2021 02:13:06 +0400 Subject: add audiovideocallcontroller and callwindow, menu action to initiate call --- pica-client/audiovideocallcontroller.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 pica-client/audiovideocallcontroller.cpp (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp new file mode 100644 index 0000000..97557af --- /dev/null +++ b/pica-client/audiovideocallcontroller.cpp @@ -0,0 +1,22 @@ +#include "audiovideocallcontroller.h" +#include "globals.h" +#include "skynet.h" +#include + +AudioVideoCallController::AudioVideoCallController(QObject *parent) + : QObject(parent), callwindow(0) +{ + +} + +void AudioVideoCallController::start_call(QByteArray peer_id) +{ + if (callwindow) + { + /* call is already in progress */ + return; + } + + callwindow = new CallWindow(peer_id); + callwindow->show(); +} -- cgit v1.2.1 From dc8dc3d49d4b98e28cee3e68cf408bc8af9633b9 Mon Sep 17 00:00:00 2001 From: Anton Date: Tue, 19 Aug 2025 17:20:35 +0400 Subject: pica-client: add call initiation & termination in skynet and audiovideocallscontroller and callwindow --- pica-client/audiovideocallcontroller.cpp | 67 +++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 97557af..9eeb89c 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -2,11 +2,33 @@ #include "globals.h" #include "skynet.h" #include +#include AudioVideoCallController::AudioVideoCallController(QObject *parent) - : QObject(parent), callwindow(0) + : QObject(parent), callwindow(0), is_active(false) { + connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); + connect(skynet, SIGNAL(CallFailed(QString)), this, SLOT(call_failed(QString))); + connect(skynet, SIGNAL(CallAccepted(QByteArray)), this, SLOT(call_accepted(QByteArray))); + connect(skynet, SIGNAL(CallRejected(QByteArray)), this, SLOT(call_rejected(QByteArray))); + connect(skynet, SIGNAL(CallHungup(QByteArray)), this, SLOT(call_hungup(QByteArray))); +} +void AudioVideoCallController::call_failed(QString reason) +{ + qDebug() << "Call failed: " << reason << "\n"; +} + +void AudioVideoCallController::call_accepted(QByteArray peer_id) +{ +} + +void AudioVideoCallController::call_rejected(QByteArray peer_id) +{ +} + +void AudioVideoCallController::call_hungup(QByteArray peer_id) +{ } void AudioVideoCallController::start_call(QByteArray peer_id) @@ -17,6 +39,47 @@ void AudioVideoCallController::start_call(QByteArray peer_id) return; } - callwindow = new CallWindow(peer_id); + m_peer_id = peer_id; + callwindow = new CallWindow(peer_id, false); + connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); + connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); callwindow->show(); } + +void AudioVideoCallController::call_from(QByteArray peer_id) +{ + if (callwindow) + { + /* HANDLE BUSY CASE!!! */ + /* call is already in progress */ + return; + } + + m_peer_id = peer_id; + callwindow = new CallWindow(peer_id, true); + connect(callwindow, SIGNAL(accept_call_pressed()), this, SLOT(accept_call())); + connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); + callwindow->show(); + + /* play ring tone */ + +} + +void AudioVideoCallController::initiate_call() +{ + skynet->StartCall(m_peer_id); +} + +void AudioVideoCallController::accept_call() +{ + skynet->AcceptCall(m_peer_id); +} + +void AudioVideoCallController::end_call() +{ + if (is_active) + skynet->HangupCall(m_peer_id); + else + skynet->RejectCall(m_peer_id); +} + -- cgit v1.2.1 From 32b5ae5d300a6e6ee571febd121ac985758c574e Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 9 Aug 2026 08:21:47 +0400 Subject: pica-client: add TonePlayer for classic telephony call tones Wires ringback, busy, special-information (unreachable) and an electromechanical-bell incoming ringtone into AudioVideoCallController, each played on its own QThread since TonePlayer::play() blocks. Device selection reads audio.playback_device and audio.ring_device from Settings so it follows what's configured in SettingsDialog. Centralizes the FFmpeg libavdevice output driver name (alsa/audiotoolbox/dsound) in AudioDevice::PlatformDriverName() rather than hardcoding ALSA, so it can also back capture/playback later. Adds toneplayer.{h,cpp} to the autotools build and adds the missing GPL v3 header to the touched files that lacked it. --- pica-client/audiovideocallcontroller.cpp | 88 +++++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 1 deletion(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 9eeb89c..65d9f3f 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -1,8 +1,26 @@ +/* + (c) Copyright 2012 - 2018 Anton Sviridenko + https://picapica.im + + 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, version 3. + + 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, see . +*/ #include "audiovideocallcontroller.h" #include "globals.h" #include "skynet.h" +#include "settings.h" #include #include +#include AudioVideoCallController::AudioVideoCallController(QObject *parent) : QObject(parent), callwindow(0), is_active(false) @@ -12,23 +30,86 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) connect(skynet, SIGNAL(CallAccepted(QByteArray)), this, SLOT(call_accepted(QByteArray))); connect(skynet, SIGNAL(CallRejected(QByteArray)), this, SLOT(call_rejected(QByteArray))); connect(skynet, SIGNAL(CallHungup(QByteArray)), this, SLOT(call_hungup(QByteArray))); + + // Earpiece tones (ringback/busy/unreachable) and the incoming call bell + // are played by two TonePlayer instances, each living on its own + // QThread since TonePlayer::play() blocks the calling thread for the + // duration of the tone sequence. + toneplayer = new TonePlayer(); + toneplayer->moveToThread(&toneplayer_thread); + toneplayer_thread.start(); + + ringtoneplayer = new TonePlayer(); + ringtoneplayer->moveToThread(&ringtoneplayer_thread); + ringtoneplayer_thread.start(); +} + +AudioVideoCallController::~AudioVideoCallController() +{ + stopTones(); + + toneplayer_thread.quit(); + toneplayer_thread.wait(); + delete toneplayer; + + ringtoneplayer_thread.quit(); + ringtoneplayer_thread.wait(); + delete ringtoneplayer; +} + +void AudioVideoCallController::playEarpieceTone(void (TonePlayer::*tone)()) +{ + Settings st(config_dbname); + QString dev = st.loadValue("audio.playback_device", "default").toString(); + + toneplayer->stop(); + QMetaObject::invokeMethod(toneplayer, "setDeviceName", Qt::QueuedConnection, Q_ARG(QString, dev)); + if (tone == &TonePlayer::playCallInProgress) + QMetaObject::invokeMethod(toneplayer, "playCallInProgress", Qt::QueuedConnection); + else if (tone == &TonePlayer::playUnreachable) + QMetaObject::invokeMethod(toneplayer, "playUnreachable", Qt::QueuedConnection); + else if (tone == &TonePlayer::playBusy) + QMetaObject::invokeMethod(toneplayer, "playBusy", Qt::QueuedConnection); +} + +void AudioVideoCallController::playRingTone() +{ + Settings st(config_dbname); + QString dev = st.loadValue("audio.ring_device", "default").toString(); + + ringtoneplayer->stop(); + QMetaObject::invokeMethod(ringtoneplayer, "setDeviceName", Qt::QueuedConnection, Q_ARG(QString, dev)); + QMetaObject::invokeMethod(ringtoneplayer, "playClassicRingtone", Qt::QueuedConnection); +} + +void AudioVideoCallController::stopTones() +{ + toneplayer->stop(); + ringtoneplayer->stop(); } void AudioVideoCallController::call_failed(QString reason) { qDebug() << "Call failed: " << reason << "\n"; + /* play unreachable */ + playEarpieceTone(&TonePlayer::playUnreachable); } void AudioVideoCallController::call_accepted(QByteArray peer_id) { + stopTones(); } void AudioVideoCallController::call_rejected(QByteArray peer_id) { + /* play busy tone */ + playEarpieceTone(&TonePlayer::playBusy); } void AudioVideoCallController::call_hungup(QByteArray peer_id) { + /* play busy tone */ + playEarpieceTone(&TonePlayer::playBusy); } void AudioVideoCallController::start_call(QByteArray peer_id) @@ -44,6 +125,8 @@ void AudioVideoCallController::start_call(QByteArray peer_id) connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); callwindow->show(); + /* play ringing tone */ + playEarpieceTone(&TonePlayer::playCallInProgress); } void AudioVideoCallController::call_from(QByteArray peer_id) @@ -62,7 +145,7 @@ void AudioVideoCallController::call_from(QByteArray peer_id) callwindow->show(); /* play ring tone */ - + playRingTone(); } void AudioVideoCallController::initiate_call() @@ -72,11 +155,14 @@ void AudioVideoCallController::initiate_call() void AudioVideoCallController::accept_call() { + stopTones(); skynet->AcceptCall(m_peer_id); } void AudioVideoCallController::end_call() { + stopTones(); + if (is_active) skynet->HangupCall(m_peer_id); else -- cgit v1.2.1 From 3fcb0660953fbf222b6cbe5e08c2b0488b7b68f8 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 9 Aug 2026 08:53:31 +0400 Subject: pica-client: play ringing tone in a correct place --- pica-client/audiovideocallcontroller.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 65d9f3f..d9b6571 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -125,8 +125,6 @@ void AudioVideoCallController::start_call(QByteArray peer_id) connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); callwindow->show(); - /* play ringing tone */ - playEarpieceTone(&TonePlayer::playCallInProgress); } void AudioVideoCallController::call_from(QByteArray peer_id) @@ -151,6 +149,8 @@ void AudioVideoCallController::call_from(QByteArray peer_id) void AudioVideoCallController::initiate_call() { skynet->StartCall(m_peer_id); + /* play ringing tone */ + playEarpieceTone(&TonePlayer::playCallInProgress); } void AudioVideoCallController::accept_call() -- cgit v1.2.1 From 4bfdcf3288b921c7a648dc1f85754ee4482c24d5 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 9 Aug 2026 14:30:20 +0400 Subject: pica-client: fix CallWindow only being usable for the first call AudioVideoCallController never cleared its callwindow pointer after a call ended, so start_call()/call_from() would see it as non-null forever and silently refuse every subsequent call. CallWindow now sets WA_DeleteOnClose and emits callwindow_closed() from closeEvent(), mirroring the ChatWindow/MsgUIRouter pattern. The controller resets its pointer to 0 in response, and end_call() closes the window once the hangup/reject has been handled. --- pica-client/audiovideocallcontroller.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index d9b6571..4e23a96 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -124,6 +124,7 @@ void AudioVideoCallController::start_call(QByteArray peer_id) callwindow = new CallWindow(peer_id, false); connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); + connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); callwindow->show(); } @@ -140,6 +141,7 @@ void AudioVideoCallController::call_from(QByteArray peer_id) callwindow = new CallWindow(peer_id, true); connect(callwindow, SIGNAL(accept_call_pressed()), this, SLOT(accept_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); + connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); callwindow->show(); /* play ring tone */ @@ -167,5 +169,12 @@ void AudioVideoCallController::end_call() skynet->HangupCall(m_peer_id); else skynet->RejectCall(m_peer_id); + + callwindow->close(); +} + +void AudioVideoCallController::callwindow_closed(CallWindow *sender_window) +{ + callwindow = 0; } -- cgit v1.2.1 From 27693e8f033b5a5bb857190d203f17a39d04c378 Mon Sep 17 00:00:00 2001 From: Anton Date: Wed, 12 Aug 2026 00:14:42 +0400 Subject: pica-client: fix call handling in audiovideocallcontroller --- pica-client/audiovideocallcontroller.cpp | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 4e23a96..2af7ced 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -91,6 +91,7 @@ void AudioVideoCallController::stopTones() void AudioVideoCallController::call_failed(QString reason) { qDebug() << "Call failed: " << reason << "\n"; + is_active = false; /* play unreachable */ playEarpieceTone(&TonePlayer::playUnreachable); } @@ -98,6 +99,8 @@ void AudioVideoCallController::call_failed(QString reason) void AudioVideoCallController::call_accepted(QByteArray peer_id) { stopTones(); + is_active = true; + callwindow->call_started(); } void AudioVideoCallController::call_rejected(QByteArray peer_id) @@ -108,16 +111,24 @@ void AudioVideoCallController::call_rejected(QByteArray peer_id) void AudioVideoCallController::call_hungup(QByteArray peer_id) { + callwindow->call_ended(); /* play busy tone */ playEarpieceTone(&TonePlayer::playBusy); + is_active = false; } void AudioVideoCallController::start_call(QByteArray peer_id) { if (callwindow) { + callwindow->show(); + + /* call is already in progress */ - return; + if (is_active) + return; + /* re-create callwindow for a new call */ + callwindow->close(); } m_peer_id = peer_id; @@ -159,6 +170,8 @@ void AudioVideoCallController::accept_call() { stopTones(); skynet->AcceptCall(m_peer_id); + is_active = true; + callwindow->call_started(); } void AudioVideoCallController::end_call() @@ -170,11 +183,13 @@ void AudioVideoCallController::end_call() else skynet->RejectCall(m_peer_id); + is_active = false; callwindow->close(); } void AudioVideoCallController::callwindow_closed(CallWindow *sender_window) { callwindow = 0; + is_active = false; } -- cgit v1.2.1 From 9c5a67f89a6f90080e171fb6c7bb0964bd9e69f3 Mon Sep 17 00:00:00 2001 From: Anton Date: Wed, 12 Aug 2026 22:52:20 +0400 Subject: pica-client: voice calls --- pica-client/audiovideocallcontroller.cpp | 121 ++++++++++++++++++++++++++++++- 1 file changed, 117 insertions(+), 4 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 2af7ced..1a4d8ae 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -23,14 +23,17 @@ #include AudioVideoCallController::AudioVideoCallController(QObject *parent) - : QObject(parent), callwindow(0), is_active(false) + : QObject(parent), callwindow(0), ringdevice(0), is_active(false), m_audioSeq(0) { connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); - connect(skynet, SIGNAL(CallFailed(QString)), this, SLOT(call_failed(QString))); + connect(skynet, SIGNAL(CallFailed(QByteArray,QString)), this, SLOT(call_failed(QByteArray,QString))); connect(skynet, SIGNAL(CallAccepted(QByteArray)), this, SLOT(call_accepted(QByteArray))); connect(skynet, SIGNAL(CallRejected(QByteArray)), this, SLOT(call_rejected(QByteArray))); connect(skynet, SIGNAL(CallHungup(QByteArray)), this, SLOT(call_hungup(QByteArray))); + connect(skynet, SIGNAL(IncomingAudioParams(QByteArray,QString,quint16)), this, SLOT(incoming_audio_params(QByteArray,QString,quint16))); + connect(skynet, SIGNAL(IncomingAudioPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_audio_packet(QByteArray,quint16,quint32,QByteArray))); + // Earpiece tones (ringback/busy/unreachable) and the incoming call bell // are played by two TonePlayer instances, each living on its own // QThread since TonePlayer::play() blocks the calling thread for the @@ -42,11 +45,25 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) ringtoneplayer = new TonePlayer(); ringtoneplayer->moveToThread(&ringtoneplayer_thread); ringtoneplayer_thread.start(); + + // Mic capture+encode and remote-audio decode+playback - same + // one-object-per-thread pattern as the tone players above, since + // AudioDevice::Capture()/Play() block their thread for the call's + // duration too. + microphone = new AudioDevice(); + microphone->moveToThread(µphone_thread); + connect(microphone, SIGNAL(packetReady(QByteArray)), this, SLOT(send_audio_packet(QByteArray))); + microphone_thread.start(); + + output = new AudioDevice(); + output->moveToThread(&output_thread); + output_thread.start(); } AudioVideoCallController::~AudioVideoCallController() { stopTones(); + stopAudioPipeline(); toneplayer_thread.quit(); toneplayer_thread.wait(); @@ -55,6 +72,14 @@ AudioVideoCallController::~AudioVideoCallController() ringtoneplayer_thread.quit(); ringtoneplayer_thread.wait(); delete ringtoneplayer; + + microphone_thread.quit(); + microphone_thread.wait(); + delete microphone; + + output_thread.quit(); + output_thread.wait(); + delete output; } void AudioVideoCallController::playEarpieceTone(void (TonePlayer::*tone)()) @@ -88,9 +113,41 @@ void AudioVideoCallController::stopTones() ringtoneplayer->stop(); } -void AudioVideoCallController::call_failed(QString reason) +void AudioVideoCallController::startAudioPipeline() +{ + Settings st(config_dbname); + QString capDev = st.loadValue("audio.capture_device", "default").toString(); + + m_audioSeq = 0; + m_callClock.start(); + + // Declare our outgoing codec to the peer, then start capturing and + // encoding right away - the peer's decoder is only ready once it has + // processed this 0x74 message, but since the call is carried over TCP, + // packets sent immediately after are guaranteed to arrive after it. + skynet->SendAudioParams(m_peer_id, QStringLiteral("opus"), 48000); + + QMetaObject::invokeMethod(microphone, "configureCapture", Qt::QueuedConnection, + Q_ARG(QString, capDev), Q_ARG(QString, QStringLiteral("opus")), Q_ARG(int, 48000)); + QMetaObject::invokeMethod(microphone, "Capture", Qt::QueuedConnection); + + // output is configured lazily, once the peer's own 0x74 (see + // incoming_audio_params()) tells us what codec/rate it is sending. +} + +void AudioVideoCallController::stopAudioPipeline() +{ + QMetaObject::invokeMethod(microphone, "Close", Qt::QueuedConnection); + QMetaObject::invokeMethod(output, "Close", Qt::QueuedConnection); +} + +void AudioVideoCallController::call_failed(QByteArray peer_id, QString reason) { qDebug() << "Call failed: " << reason << "\n"; + + if (peer_id != m_peer_id) + return; + is_active = false; /* play unreachable */ playEarpieceTone(&TonePlayer::playUnreachable); @@ -98,20 +155,39 @@ void AudioVideoCallController::call_failed(QString reason) void AudioVideoCallController::call_accepted(QByteArray peer_id) { + /* SkyNet lives in its own thread, so this signal is queued: by the time + it is delivered the local side may have already hung up and closed the + call window, or moved on to a different peer entirely. Either way the + call it refers to is gone - do not bring the audio pipeline up for it. */ + if (peer_id != m_peer_id || !callwindow) + return; + stopTones(); is_active = true; callwindow->call_started(); + startAudioPipeline(); } void AudioVideoCallController::call_rejected(QByteArray peer_id) { + if (peer_id != m_peer_id) + return; + /* play busy tone */ playEarpieceTone(&TonePlayer::playBusy); } void AudioVideoCallController::call_hungup(QByteArray peer_id) { - callwindow->call_ended(); + if (peer_id != m_peer_id) + return; + + stopAudioPipeline(); + + /* queued from the SkyNet thread as well - the window may already be closed */ + if (callwindow) + callwindow->call_ended(); + /* play busy tone */ playEarpieceTone(&TonePlayer::playBusy); is_active = false; @@ -172,11 +248,13 @@ void AudioVideoCallController::accept_call() skynet->AcceptCall(m_peer_id); is_active = true; callwindow->call_started(); + startAudioPipeline(); } void AudioVideoCallController::end_call() { stopTones(); + stopAudioPipeline(); if (is_active) skynet->HangupCall(m_peer_id); @@ -193,3 +271,38 @@ void AudioVideoCallController::callwindow_closed(CallWindow *sender_window) is_active = false; } +void AudioVideoCallController::send_audio_packet(QByteArray data) +{ + if (!is_active) + return; + + quint16 seq = m_audioSeq++; + quint32 timestamp = (quint32)m_callClock.elapsed(); + + skynet->SendAudioPacket(m_peer_id, seq, timestamp, data); +} + +void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate) +{ + if (!is_active || peer_id != m_peer_id) + return; + + Settings st(config_dbname); + QString playDev = st.loadValue("audio.playback_device", "default").toString(); + + QMetaObject::invokeMethod(output, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, playDev), Q_ARG(QString, codec), Q_ARG(int, (int)sample_rate)); + QMetaObject::invokeMethod(output, "Play", Qt::QueuedConnection); +} + +void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + Q_UNUSED(seq_num); + Q_UNUSED(timestamp); + + if (!is_active || peer_id != m_peer_id) + return; + + QMetaObject::invokeMethod(output, "enqueuePacket", Qt::QueuedConnection, Q_ARG(QByteArray, data)); +} + -- cgit v1.2.1 From f65bda4889e67dac8df0d972f3adade837a2fa79 Mon Sep 17 00:00:00 2001 From: Anton Date: Thu, 13 Aug 2026 00:19:12 +0400 Subject: pica-client: fix locking bug in audio queues --- pica-client/audiovideocallcontroller.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 1a4d8ae..964b15c 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -137,8 +137,17 @@ void AudioVideoCallController::startAudioPipeline() void AudioVideoCallController::stopAudioPipeline() { - QMetaObject::invokeMethod(microphone, "Close", Qt::QueuedConnection); - QMetaObject::invokeMethod(output, "Close", Qt::QueuedConnection); + // Close() only touches a QAtomicInt and wakes a QWaitCondition, both + // safe to reach from any thread - it must be called directly rather + // than via invokeMethod()/QueuedConnection: microphone/output's own + // thread is blocked inside Capture()/Play() for the call's duration, + // so its event loop cannot deliver a queued call back to itself until + // that blocking call returns - which is exactly what Close() is + // supposed to make happen. Routing it through the event queue would + // deadlock (the thread would never quit, and the app would hang on + // exit after a call). + microphone->Close(); + output->Close(); } void AudioVideoCallController::call_failed(QByteArray peer_id, QString reason) @@ -303,6 +312,11 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 if (!is_active || peer_id != m_peer_id) return; - QMetaObject::invokeMethod(output, "enqueuePacket", Qt::QueuedConnection, Q_ARG(QByteArray, data)); + // Direct call, not invokeMethod()/QueuedConnection - see the comment in + // stopAudioPipeline(). enqueuePacket() is mutex-protected and safe to + // call from any thread; queuing it behind output's own blocking Play() + // call would mean it's never delivered, and Play() would sit forever + // pulling from an empty jitter buffer. + output->enqueuePacket(data); } -- cgit v1.2.1 From d10deee6b3143fffd0d4d55b87bf6167c34dd459 Mon Sep 17 00:00:00 2001 From: Anton Date: Thu, 13 Aug 2026 01:28:32 +0400 Subject: pica-client: video call --- pica-client/audiovideocallcontroller.cpp | 142 ++++++++++++++++++++++++++++++- 1 file changed, 141 insertions(+), 1 deletion(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 964b15c..0df0a79 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -22,8 +22,16 @@ #include #include +// Capture/encode resolution announced to the peer in the 0x75 message. Fixed +// for now - a resolution setting is a planned follow-up, see VideoDevice for +// the rest of the encoding parameters. +static const quint16 kVideoWidth = 640; +static const quint16 kVideoHeight = 480; + + AudioVideoCallController::AudioVideoCallController(QObject *parent) - : QObject(parent), callwindow(0), ringdevice(0), is_active(false), m_audioSeq(0) + : QObject(parent), callwindow(0), ringdevice(0), is_active(false), m_audioSeq(0), + m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false) { connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); connect(skynet, SIGNAL(CallFailed(QByteArray,QString)), this, SLOT(call_failed(QByteArray,QString))); @@ -34,6 +42,9 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) connect(skynet, SIGNAL(IncomingAudioParams(QByteArray,QString,quint16)), this, SLOT(incoming_audio_params(QByteArray,QString,quint16))); connect(skynet, SIGNAL(IncomingAudioPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_audio_packet(QByteArray,quint16,quint32,QByteArray))); + connect(skynet, SIGNAL(IncomingVideoParams(QByteArray,QString,quint16,quint16)), this, SLOT(incoming_video_params(QByteArray,QString,quint16,quint16))); + connect(skynet, SIGNAL(IncomingVideoPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_video_packet(QByteArray,quint16,quint32,QByteArray))); + // Earpiece tones (ringback/busy/unreachable) and the incoming call bell // are played by two TonePlayer instances, each living on its own // QThread since TonePlayer::play() blocks the calling thread for the @@ -58,12 +69,24 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) output = new AudioDevice(); output->moveToThread(&output_thread); output_thread.start(); + + // Camera capture+encode and remote video decode - same arrangement as + // the audio devices above. + cam = new VideoDevice(); + cam->moveToThread(&cam_thread); + connect(cam, SIGNAL(packetReady(QByteArray,bool)), this, SLOT(send_video_packet(QByteArray,bool))); + cam_thread.start(); + + remotevideo = new VideoDevice(); + remotevideo->moveToThread(&remotevideo_thread); + remotevideo_thread.start(); } AudioVideoCallController::~AudioVideoCallController() { stopTones(); stopAudioPipeline(); + stopVideoPipeline(); toneplayer_thread.quit(); toneplayer_thread.wait(); @@ -80,6 +103,14 @@ AudioVideoCallController::~AudioVideoCallController() output_thread.quit(); output_thread.wait(); delete output; + + cam_thread.quit(); + cam_thread.wait(); + delete cam; + + remotevideo_thread.quit(); + remotevideo_thread.wait(); + delete remotevideo; } void AudioVideoCallController::playEarpieceTone(void (TonePlayer::*tone)()) @@ -150,6 +181,53 @@ void AudioVideoCallController::stopAudioPipeline() output->Close(); } +void AudioVideoCallController::startVideoPipeline() +{ + Settings st(config_dbname); + QString camDev = st.loadValue("video.capture_device", QString()).toString(); + + // Unlike the audio devices, which fall back to the platform's "default" + // device, there is no such name for cameras - so with nothing configured + // yet (the setting is only written once the settings dialog has been + // visited) pick the first camera found. + if (camDev.isEmpty()) + { + VideoDevice enumerator; + QList cams = enumerator.Enumerate(CAPTURE); + + if (!cams.isEmpty()) + camDev = cams.first().device; + } + + // No camera at all - the call simply carries no outgoing video. Incoming + // video is unaffected, it only depends on what the peer sends. + if (camDev.isEmpty()) + return; + + m_videoSeq = 0; + m_videoFrameTimestamp = 0; + m_videoFrameStarted = false; + + skynet->SendVideoParams(m_peer_id, QStringLiteral("h264"), kVideoWidth, kVideoHeight); + + QMetaObject::invokeMethod(cam, "configureCapture", Qt::QueuedConnection, + Q_ARG(QString, camDev), Q_ARG(QString, QStringLiteral("h264")), + Q_ARG(int, kVideoWidth), Q_ARG(int, kVideoHeight)); + QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); + + // remotevideo is configured lazily, once the peer's own 0x75 (see + // incoming_video_params()) tells us what it is sending. +} + +void AudioVideoCallController::stopVideoPipeline() +{ + // Direct calls, for the same reason stopAudioPipeline() uses them. + cam->Close(); + remotevideo->Close(); + + m_videoAssembler.reset(); +} + void AudioVideoCallController::call_failed(QByteArray peer_id, QString reason) { qDebug() << "Call failed: " << reason << "\n"; @@ -175,6 +253,7 @@ void AudioVideoCallController::call_accepted(QByteArray peer_id) is_active = true; callwindow->call_started(); startAudioPipeline(); + startVideoPipeline(); } void AudioVideoCallController::call_rejected(QByteArray peer_id) @@ -192,6 +271,7 @@ void AudioVideoCallController::call_hungup(QByteArray peer_id) return; stopAudioPipeline(); + stopVideoPipeline(); /* queued from the SkyNet thread as well - the window may already be closed */ if (callwindow) @@ -221,6 +301,9 @@ void AudioVideoCallController::start_call(QByteArray peer_id) connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); + /* decoded frames arrive from remotevideo's thread, so this is a queued + connection; it dies with the window, which is deleted on close */ + connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); callwindow->show(); } @@ -238,6 +321,8 @@ void AudioVideoCallController::call_from(QByteArray peer_id) connect(callwindow, SIGNAL(accept_call_pressed()), this, SLOT(accept_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); + /* see the same connection in start_call() */ + connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); callwindow->show(); /* play ring tone */ @@ -258,12 +343,14 @@ void AudioVideoCallController::accept_call() is_active = true; callwindow->call_started(); startAudioPipeline(); + startVideoPipeline(); } void AudioVideoCallController::end_call() { stopTones(); stopAudioPipeline(); + stopVideoPipeline(); if (is_active) skynet->HangupCall(m_peer_id); @@ -320,3 +407,56 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 output->enqueuePacket(data); } +void AudioVideoCallController::send_video_packet(QByteArray data, bool is_last_fragment) +{ + if (!is_active) + return; + + // Every fragment of one encoded frame carries the timestamp taken when + // that frame's first fragment was sent, so the receiving side can tell + // the fragments of one frame from those of the next. + if (!m_videoFrameStarted) + { + m_videoFrameTimestamp = (quint32)m_callClock.elapsed(); + m_videoFrameStarted = true; + } + + quint16 seq = m_videoSeq & VideoFrameAssembler::SeqNumMask; + m_videoSeq = (m_videoSeq + 1) & VideoFrameAssembler::SeqNumMask; + + if (is_last_fragment) + { + seq |= VideoFrameAssembler::LastFragmentFlag; + // The next fragment emitted belongs to a new frame. + m_videoFrameStarted = false; + } + + skynet->SendVideoPacket(m_peer_id, seq, m_videoFrameTimestamp, data); +} + +void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString codec, quint16 width, quint16 height) +{ + if (!is_active || peer_id != m_peer_id) + return; + + QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height)); + QMetaObject::invokeMethod(remotevideo, "Play", Qt::QueuedConnection); +} + +void AudioVideoCallController::incoming_video_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) +{ + if (!is_active || peer_id != m_peer_id) + return; + + QByteArray frame = m_videoAssembler.addFragment(seq_num, timestamp, data); + + // Still waiting for the rest of this frame's fragments. + if (frame.isEmpty()) + return; + + // Direct call, not invokeMethod()/QueuedConnection - same reason as in + // incoming_audio_packet(). + remotevideo->enqueueFrame(frame); +} + -- cgit v1.2.1 From 6ef469ba767574384c0373daa5363efb95102ed9 Mon Sep 17 00:00:00 2001 From: Anton Date: Thu, 13 Aug 2026 22:58:28 +0400 Subject: pica-client: add support for compressed video formats provided by camera: hevc, h264, mjpeg --- pica-client/audiovideocallcontroller.cpp | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 0df0a79..54dfa26 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -74,6 +74,7 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) // the audio devices above. cam = new VideoDevice(); cam->moveToThread(&cam_thread); + connect(cam, SIGNAL(captureStarted(QString,int,int)), this, SLOT(video_capture_started(QString,int,int))); connect(cam, SIGNAL(packetReady(QByteArray,bool)), this, SLOT(send_video_packet(QByteArray,bool))); cam_thread.start(); @@ -208,11 +209,16 @@ void AudioVideoCallController::startVideoPipeline() m_videoFrameTimestamp = 0; m_videoFrameStarted = false; - skynet->SendVideoParams(m_peer_id, QStringLiteral("h264"), kVideoWidth, kVideoHeight); + bool preferCompressed = st.loadValue("video.prefer_compressed", 0).toBool(); + // The peer is told what we are sending only once the camera is open and + // the format is settled - with a compressed camera stream being forwarded + // as-is, the codec is the camera's choice, not ours (see + // video_capture_started()). QMetaObject::invokeMethod(cam, "configureCapture", Qt::QueuedConnection, - Q_ARG(QString, camDev), Q_ARG(QString, QStringLiteral("h264")), - Q_ARG(int, kVideoWidth), Q_ARG(int, kVideoHeight)); + Q_ARG(QString, camDev), + Q_ARG(int, kVideoWidth), Q_ARG(int, kVideoHeight), + Q_ARG(bool, preferCompressed)); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see @@ -407,6 +413,17 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 output->enqueuePacket(data); } +void AudioVideoCallController::video_capture_started(QString codec, int width, int height) +{ + if (!is_active) + return; + + // Announced only now, because what the camera turned out to deliver + // decides it: a compressed camera stream is forwarded in the camera's own + // codec and at the camera's own size, rather than in ours. + skynet->SendVideoParams(m_peer_id, codec, (quint16)width, (quint16)height); +} + void AudioVideoCallController::send_video_packet(QByteArray data, bool is_last_fragment) { if (!is_active) -- cgit v1.2.1 From ad95ec8759777c4b8df0dcd66fd8200d24e912b1 Mon Sep 17 00:00:00 2001 From: Anton Date: Fri, 14 Aug 2026 01:29:59 +0400 Subject: pica-client: VAAPI hardware acceleration --- pica-client/audiovideocallcontroller.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 54dfa26..59ffad9 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -210,6 +210,7 @@ void AudioVideoCallController::startVideoPipeline() m_videoFrameStarted = false; bool preferCompressed = st.loadValue("video.prefer_compressed", 0).toBool(); + bool vaapiEncoding = st.loadValue("video.vaapi_encoding", 0).toBool(); // The peer is told what we are sending only once the camera is open and // the format is settled - with a compressed camera stream being forwarded @@ -218,7 +219,7 @@ void AudioVideoCallController::startVideoPipeline() QMetaObject::invokeMethod(cam, "configureCapture", Qt::QueuedConnection, Q_ARG(QString, camDev), Q_ARG(int, kVideoWidth), Q_ARG(int, kVideoHeight), - Q_ARG(bool, preferCompressed)); + Q_ARG(bool, preferCompressed), Q_ARG(bool, vaapiEncoding)); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see @@ -310,6 +311,9 @@ void AudioVideoCallController::start_call(QByteArray peer_id) /* decoded frames arrive from remotevideo's thread, so this is a queued connection; it dies with the window, which is deleted on close */ connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); +#ifdef HAVE_VAAPI + connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); +#endif callwindow->show(); } @@ -327,8 +331,11 @@ void AudioVideoCallController::call_from(QByteArray peer_id) connect(callwindow, SIGNAL(accept_call_pressed()), this, SLOT(accept_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); - /* see the same connection in start_call() */ + /* see the same connections in start_call() */ connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); +#ifdef HAVE_VAAPI + connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); +#endif callwindow->show(); /* play ring tone */ @@ -456,8 +463,13 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString if (!is_active || peer_id != m_peer_id) return; + Settings st(config_dbname); + bool vaapiDecoding = st.loadValue("video.vaapi_decoding", 0).toBool(); + bool vaapiRendering = st.loadValue("video.vaapi_rendering", 0).toBool(); + QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, - Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height)); + Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), + Q_ARG(bool, vaapiDecoding), Q_ARG(bool, vaapiRendering)); QMetaObject::invokeMethod(remotevideo, "Play", Qt::QueuedConnection); } -- cgit v1.2.1 From 1b7b9d46c84c38cbf2df293113a687481e205585 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 16 Aug 2026 03:28:51 +0400 Subject: pica-client: VAAPI on X11, two codepaths --- pica-client/audiovideocallcontroller.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 59ffad9..7d3875c 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -313,6 +313,7 @@ void AudioVideoCallController::start_call(QByteArray peer_id) connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); #ifdef HAVE_VAAPI connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); + connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed())); #endif callwindow->show(); } @@ -335,6 +336,7 @@ void AudioVideoCallController::call_from(QByteArray peer_id) connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); #ifdef HAVE_VAAPI connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); + connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed())); #endif callwindow->show(); @@ -467,6 +469,13 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString bool vaapiDecoding = st.loadValue("video.vaapi_decoding", 0).toBool(); bool vaapiRendering = st.loadValue("video.vaapi_rendering", 0).toBool(); +#ifdef HAVE_VAAPI + // A call started after one where drawing GPU frames turned out not to work + // would otherwise begin with a blank video area all over again. + if (VaapiRenderWidget::renderingKnownBroken()) + vaapiRendering = false; +#endif + QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), Q_ARG(bool, vaapiDecoding), Q_ARG(bool, vaapiRendering)); @@ -489,3 +498,17 @@ void AudioVideoCallController::incoming_video_packet(QByteArray peer_id, quint16 remotevideo->enqueueFrame(frame); } +#ifdef HAVE_VAAPI +void AudioVideoCallController::video_rendering_failed() +{ + // The window cannot draw frames that stayed in GPU memory, so stop keeping + // them there: the decoder brings them down into system memory instead and + // the window's label shows them. Decoding itself is unaffected and the + // call carries on. + // + // Direct call rather than invokeMethod() - same reason as in + // incoming_video_packet(): remotevideo's thread is blocked inside Play(). + remotevideo->disableHardwareRendering(); +} +#endif + -- cgit v1.2.1 From c9f6051380f4edf5f7ac336501ecb1f32946dc6e Mon Sep 17 00:00:00 2001 From: Anton Date: Wed, 19 Aug 2026 14:47:51 +0400 Subject: pica-client: UDP transport for calls --- pica-client/audiovideocallcontroller.cpp | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 7d3875c..4e91507 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -45,6 +45,8 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) connect(skynet, SIGNAL(IncomingVideoParams(QByteArray,QString,quint16,quint16)), this, SLOT(incoming_video_params(QByteArray,QString,quint16,quint16))); connect(skynet, SIGNAL(IncomingVideoPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_video_packet(QByteArray,quint16,quint32,QByteArray))); + connect(skynet, SIGNAL(CallMediaTransportChanged(QByteArray,bool,QString,quint32)), this, SLOT(media_transport_changed(QByteArray,bool,QString,quint32))); + // Earpiece tones (ringback/busy/unreachable) and the incoming call bell // are played by two TonePlayer instances, each living on its own // QThread since TonePlayer::play() blocks the calling thread for the @@ -209,6 +211,13 @@ void AudioVideoCallController::startVideoPipeline() m_videoFrameTimestamp = 0; m_videoFrameStarted = false; + // Datagram sized from the start, even though the call begins on the c2c + // connection where a 0x77 message could hold far more: a media connection + // may come up at any moment during the call, and frames whose fragments + // were cut before that would not fit into a datagram. Over TCP this only + // costs a few more message headers. + cam->setMaxFragmentSize(PICA_MEDIA_SAFE_PAYLOAD); + bool preferCompressed = st.loadValue("video.prefer_compressed", 0).toBool(); bool vaapiEncoding = st.loadValue("video.vaapi_encoding", 0).toBool(); @@ -408,7 +417,6 @@ void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) { - Q_UNUSED(seq_num); Q_UNUSED(timestamp); if (!is_active || peer_id != m_peer_id) @@ -419,7 +427,7 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 // call from any thread; queuing it behind output's own blocking Play() // call would mean it's never delivered, and Play() would sit forever // pulling from an empty jitter buffer. - output->enqueuePacket(data); + output->enqueuePacket(seq_num, data); } void AudioVideoCallController::video_capture_started(QString codec, int width, int height) @@ -460,6 +468,25 @@ void AudioVideoCallController::send_video_packet(QByteArray data, bool is_last_f skynet->SendVideoPacket(m_peer_id, seq, m_videoFrameTimestamp, data); } +void AudioVideoCallController::media_transport_changed(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload) +{ + if (peer_id != m_peer_id) + return; + + // Fragments stay datagram sized for the whole call (see + // startVideoPipeline()); this only lowers the size further, for when the + // media connection turns out to carry less than was assumed. Direct call, + // not invokeMethod()/QueuedConnection - see the comment in + // stopAudioPipeline(): cam's thread is blocked inside Capture(). + cam->setMaxFragmentSize(qMin((int)max_payload, (int)PICA_MEDIA_SAFE_PAYLOAD)); + + if (callwindow) + callwindow->setMediaTransport(direct_udp, ciphersuitename); + + qDebug() << "call media transport:" << (direct_udp ? "direct UDP/DTLS" : "c2c connection") + << ciphersuitename << "max payload" << max_payload; +} + void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString codec, quint16 width, quint16 height) { if (!is_active || peer_id != m_peer_id) -- cgit v1.2.1 From a4ddbc49c82e31ee980ea1096cc737db438c012e Mon Sep 17 00:00:00 2001 From: Anton Date: Mon, 24 Aug 2026 05:06:23 +0400 Subject: pica-client: echo cancellation, and native audio on Windows and macOS PlatformDriverName() now takes a direction, and answers with one of two kinds of name. A bare one - "alsa", "pulse", "oss" - is an FFmpeg libavdevice driver opened the way everything else here is opened. One prefixed "platform-" is not an FFmpeg driver at all: what follows names a platform audio API the caller drives itself through NativeAudioBackend. Windows and macOS take the second route, because both provide acoustic echo cancellation but only to streams that declare themselves part of a voice call - AudioCategory_Communications on WASAPI, the VoiceProcessingIO audio unit on CoreAudio - and libavdevice's wrappers have no way to ask for either. Doing our own cancelling on platforms that would have done it better below us is not a trade worth making. Where the platform will not do it, speexdsp does: one EchoCanceller per call, shared by both directions through a QSharedPointer, since the call is torn down without joining either audio thread. Playback feeds it the far end as it hands it to the device; capture subtracts before encoding. Alignment is left to the FIFO - in steady state its backlog settles at the sound card's buffer depth, which is also how far ahead of the speaker the playback side runs, leaving only the room for the filter tail to model. Measured 27 dB ERLE on a 60 ms echo with 1.6 dB of loss on speech when nothing is playing. On macOS the canceller is a single audio unit that renders and captures at once, so both directions share one refcounted instance. Ringtones deliberately get a plain HALOutput unit instead - opening a voice unit to play a bell would switch the microphone on and prompt for permission. Linux gains a choice of alsa or pulse, with PulseAudio device enumeration through libpulse when configure finds it. Info.plist gains NSMicrophoneUsageDescription and NSCameraUsageDescription. Without them macOS 10.14 and later kills the process on first use of the microphone or camera rather than asking, so calls did not merely fail, they took the application with them. Two things fixed along the way that were not about echo at all: the settings dialog's microphone test paced playback by counting timer ticks, which on Windows meant a 20 ms packet every ~31 ms because the system timer granularity is 15.6 ms - the recording came out slowed down and chopped up. It now paces against a QElapsedTimer. And chooseEncoderSampleFmt() uses avcodec_get_supported_config() where available, the AVCodec format arrays it replaced having been removed in FFmpeg 9. Only the Linux paths are verified here; the Windows and macOS backends compile to nothing on this machine and have been reviewed by hand. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01CBqDgvq3Ty6C6BjLFH16bw --- pica-client/audiovideocallcontroller.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 4e91507..1f6e5ce 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -155,6 +155,29 @@ void AudioVideoCallController::startAudioPipeline() m_audioSeq = 0; m_callClock.start(); + // One canceller for the call, shared by both directions: the playback + // side feeds it what it is about to play, the capture side subtracts the + // echo of that from the microphone. Ownership is shared because + // stopAudioPipeline() does not join either thread, so this has to outlive + // whichever of them returns last. + // + // It is created even on the platforms that cancel for us, because whether + // they really will is not known until the capture stream has been opened + // - see AudioDevice::captureNative(), which drops it once the backend + // says the platform has the job in hand. + if (st.loadValue("audio.echo_cancel", 1).toBool()) + m_echoCanceller = EchoCancellerPtr(new EchoCanceller(48000)); + else + m_echoCanceller.clear(); + + if (m_echoCanceller && !m_echoCanceller->isValid()) + m_echoCanceller.clear(); + + // Set before the blocking loops are started, so the queued Capture()/ + // Play() calls below are what publishes it to those threads. + microphone->setEchoCanceller(m_echoCanceller); + output->setEchoCanceller(m_echoCanceller); + // Declare our outgoing codec to the peer, then start capturing and // encoding right away - the peer's decoder is only ready once it has // processed this 0x74 message, but since the call is carried over TCP, @@ -182,6 +205,11 @@ void AudioVideoCallController::stopAudioPipeline() // exit after a call). microphone->Close(); output->Close(); + + // Drop our reference. The two audio threads still hold theirs until they + // come out of Capture()/Play(), and the canceller goes away with the last + // of them. + m_echoCanceller.clear(); } void AudioVideoCallController::startVideoPipeline() -- cgit v1.2.1 From c6649895d58bcfab864bcc33b131db222e45bfef Mon Sep 17 00:00:00 2001 From: Anton Date: Tue, 1 Sep 2026 21:09:47 +0400 Subject: pica-client: fix echo canceller and capture gain auto regulator --- pica-client/audiovideocallcontroller.cpp | 152 ++++++++++++++++++++++++++++++- 1 file changed, 148 insertions(+), 4 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 1f6e5ce..763f1b1 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -28,9 +28,29 @@ static const quint16 kVideoWidth = 640; static const quint16 kVideoHeight = 480; +// Rate we capture and encode at, announced to the peer in the 0x74 message. +// +// 16kHz rather than 48kHz because of the echo canceller. speexdsp's MDF is +// tuned for 8/16kHz, and its cost is counted in taps: a 150ms tail is 7200 +// taps at 48kHz but only 2400 at 16kHz. Convergence time and steady state +// misadjustment both scale with that length, so the 48kHz filter spent every +// call chasing and never settling - visible in the AEC log as ERLE climbing +// towards 20dB and being knocked back to zero by each doubletalk burst. +// +// Costs nothing worth having for speech: Opus codes this as wideband, an 8kHz +// audio bandwidth, which is well past telephone quality and past where voice +// intelligibility stops improving. +// +// The playback direction is NOT this constant - it follows whatever the peer +// announces (see incoming_audio_params()), so a call with an older build that +// still sends 48kHz keeps working. +static const int kCallSampleRate = 16000; + AudioVideoCallController::AudioVideoCallController(QObject *parent) - : QObject(parent), callwindow(0), ringdevice(0), is_active(false), m_audioSeq(0), + : QObject(parent), callwindow(0), ringdevice(0), is_active(false), + m_captureGain(nullptr), m_savedCaptureGain(0.0), m_haveSavedCaptureGain(false), + m_captureGainSteps(0), m_audioSeq(0), m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false) { connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); @@ -66,6 +86,12 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) microphone = new AudioDevice(); microphone->moveToThread(µphone_thread); connect(microphone, SIGNAL(packetReady(QByteArray)), this, SLOT(send_audio_packet(QByteArray))); + + // Queued rather than direct: this crosses from the capture thread, and + // warn_capture_clipping() only logs today but is where a UI notice would + // go. + connect(microphone, SIGNAL(captureClipping(double,double)), this, + SLOT(capture_clipping(double,double)), Qt::QueuedConnection); microphone_thread.start(); output = new AudioDevice(); @@ -166,7 +192,7 @@ void AudioVideoCallController::startAudioPipeline() // - see AudioDevice::captureNative(), which drops it once the backend // says the platform has the job in hand. if (st.loadValue("audio.echo_cancel", 1).toBool()) - m_echoCanceller = EchoCancellerPtr(new EchoCanceller(48000)); + m_echoCanceller = EchoCancellerPtr(new EchoCanceller(kCallSampleRate)); else m_echoCanceller.clear(); @@ -178,14 +204,18 @@ void AudioVideoCallController::startAudioPipeline() microphone->setEchoCanceller(m_echoCanceller); output->setEchoCanceller(m_echoCanceller); + // Before Capture() starts, so the gain is already read and saved by the + // time the first clipping report can come back. + startCaptureGainControl(capDev); + // Declare our outgoing codec to the peer, then start capturing and // encoding right away - the peer's decoder is only ready once it has // processed this 0x74 message, but since the call is carried over TCP, // packets sent immediately after are guaranteed to arrive after it. - skynet->SendAudioParams(m_peer_id, QStringLiteral("opus"), 48000); + skynet->SendAudioParams(m_peer_id, QStringLiteral("opus"), kCallSampleRate); QMetaObject::invokeMethod(microphone, "configureCapture", Qt::QueuedConnection, - Q_ARG(QString, capDev), Q_ARG(QString, QStringLiteral("opus")), Q_ARG(int, 48000)); + Q_ARG(QString, capDev), Q_ARG(QString, QStringLiteral("opus")), Q_ARG(int, kCallSampleRate)); QMetaObject::invokeMethod(microphone, "Capture", Qt::QueuedConnection); // output is configured lazily, once the peer's own 0x74 (see @@ -206,6 +236,12 @@ void AudioVideoCallController::stopAudioPipeline() microphone->Close(); output->Close(); + // Puts the user's gain back. Safe to do while the capture thread is still + // winding down: the control is only ever touched from this thread, and + // capture_clipping() finds m_captureGain null and does nothing if a last + // queued report arrives after this. + stopCaptureGainControl(); + // Drop our reference. The two audio threads still hold theirs until they // come out of Capture()/Play(), and the canceller goes away with the last // of them. @@ -430,6 +466,114 @@ void AudioVideoCallController::send_audio_packet(QByteArray data) skynet->SendAudioPacket(m_peer_id, seq, timestamp, data); } +// Rate limited by AudioDevice, which reports at most once every couple of +// seconds of audio, so this can log and act unconditionally. +void AudioVideoCallController::capture_clipping(double pinnedPercent, double peakDb) +{ + qWarning("Microphone is clipping: %.2f%% of samples at full scale, peak %.1f dBFS", + pinnedPercent, peakDb); + + // Either the setting is off, or nothing on this platform would let us at + // the control. The warning above is then all we can do - and it is still + // worth having, since the distortion cannot be undone anywhere else. + if (!m_captureGain) + return; + + if (m_captureGainSteps >= kMaxCaptureGainSteps) + return; + + double current = 0.0; + if (!m_captureGain->gain(¤t)) + return; + + // Size the step to how badly it is clipping. A microphone left at maximum + // is 20-30dB too hot and wants covering quickly; one that only tips over + // on the loudest syllable wants nudging, not slamming. + double factor; + if (pinnedPercent >= 5.0) + factor = 0.70; + else if (pinnedPercent >= 0.5) + factor = 0.85; + else + factor = 0.95; + + double next = current * factor; + if (next < kMinCaptureGain) + next = kMinCaptureGain; + + if (next >= current) + return; // already at the floor, nothing left to give + + if (!m_captureGain->setGain(next)) + { + qWarning() << "Could not lower the capture gain - leaving it alone"; + m_captureGainSteps = kMaxCaptureGainSteps; + return; + } + + m_captureGainSteps++; + qDebug("Capture gain %.0f%% -> %.0f%% (step %d of %d)", + current * 100.0, next * 100.0, m_captureGainSteps, kMaxCaptureGainSteps); +} + +void AudioVideoCallController::startCaptureGainControl(const QString &captureDevice) +{ + m_captureGain = nullptr; + m_savedCaptureGain = 0.0; + m_haveSavedCaptureGain = false; + m_captureGainSteps = 0; + + Settings st(config_dbname); + if (!st.loadValue("audio.auto_capture_gain", 1).toBool()) + return; + + // Whichever driver the capture side is about to open the device with - + // the mixer control has to be the one belonging to that device. + const QString driver = AudioDevice::PlatformDriverName(CAPTURE); + + m_captureGain = CaptureGainControl::create(driver, captureDevice); + if (!m_captureGain) + return; + + if (m_captureGain->gain(&m_savedCaptureGain)) + { + m_haveSavedCaptureGain = true; + qDebug() << "Automatic microphone gain using" << m_captureGain->description() + << "- currently at" << qRound(m_savedCaptureGain * 100.0) << "%"; + } + else + { + // Without a reading there is nothing to put back afterwards, and + // moving a control we cannot restore is not a trade worth making. + qWarning() << "Could not read the capture gain - not taking it over"; + delete m_captureGain; + m_captureGain = nullptr; + } +} + +void AudioVideoCallController::stopCaptureGainControl() +{ + if (!m_captureGain) + return; + + // Put the user's own setting back. Only bother if we actually moved it, + // so a call that never clipped cannot disturb a gain the user changed + // themselves while it was running. + if (m_haveSavedCaptureGain && m_captureGainSteps > 0) + { + if (m_captureGain->setGain(m_savedCaptureGain)) + qDebug() << "Capture gain restored to" << qRound(m_savedCaptureGain * 100.0) << "%"; + else + qWarning() << "Could not restore the capture gain to" + << qRound(m_savedCaptureGain * 100.0) << "% - it has been left turned down"; + } + + delete m_captureGain; + m_captureGain = nullptr; + m_haveSavedCaptureGain = false; + m_captureGainSteps = 0; +} + void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate) { if (!is_active || peer_id != m_peer_id) -- cgit v1.2.1 From e62dd7d30bec7a679013dcce8ec4bc2b2f842109 Mon Sep 17 00:00:00 2001 From: Anton Date: Thu, 3 Sep 2026 21:01:17 +0400 Subject: pica-client: more improvements of echo cancellation --- pica-client/audiovideocallcontroller.cpp | 150 +++++++++++++++++++++++++++---- 1 file changed, 131 insertions(+), 19 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 763f1b1..405746d 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -50,7 +50,9 @@ static const int kCallSampleRate = 16000; AudioVideoCallController::AudioVideoCallController(QObject *parent) : QObject(parent), callwindow(0), ringdevice(0), is_active(false), m_captureGain(nullptr), m_savedCaptureGain(0.0), m_haveSavedCaptureGain(false), - m_captureGainSteps(0), m_audioSeq(0), + m_gainCalibrating(false), m_captureGainSteps(0), m_gainStartDb(0.0), + m_haveGainDb(false), m_gainIneffectiveSteps(0), m_lastPinnedPercent(0.0), + m_gainSettleReports(0), m_audioSeq(0), m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false) { connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); @@ -476,16 +478,71 @@ void AudioVideoCallController::capture_clipping(double pinnedPercent, double pea // Either the setting is off, or nothing on this platform would let us at // the control. The warning above is then all we can do - and it is still // worth having, since the distortion cannot be undone anywhere else. - if (!m_captureGain) + if (!m_captureGain || !m_gainCalibrating) + return; + + // Calibration is a thing that happens at the start of a call, not a gain + // rider. Once the window has passed the level is whatever it is: moving it + // mid-conversation would keep dragging the echo path out from under the + // canceller, which is worse than a bit of distortion. + if (m_callClock.elapsed() > kGainCalibrationMs) + { + closeGainCalibration("calibration window has passed"); + return; + } + + // The audio in this report may predate the last adjustment. + if (m_gainSettleReports > 0) + { + m_gainSettleReports--; return; + } - if (m_captureGainSteps >= kMaxCaptureGainSteps) + // Without a dB scale there is no safe way to know how far down we have + // come, so the step count has to be the bound - and a much tighter one, + // since six steps of 0.7 is over 50 dB on a perceptual scale. + const int stepLimit = m_haveGainDb ? kMaxCaptureGainSteps : kMaxBlindGainSteps; + if (m_captureGainSteps >= stepLimit) + { + closeGainCalibration("step limit reached"); return; + } + + // Did the previous adjustment achieve anything? Two that did not means the + // stage overloading is not the one we are holding. + if (m_captureGainSteps > 0 && pinnedPercent >= m_lastPinnedPercent) + { + m_gainIneffectiveSteps++; + if (m_gainIneffectiveSteps >= kMaxGainIneffectiveSteps) + { + closeGainCalibration("lowering this control is not reducing the clipping - " + "something ahead of it (an analog mic boost, or Windows' " + "separate Microphone Boost) is what is overloading"); + return; + } + } + else + { + m_gainIneffectiveSteps = 0; + } double current = 0.0; if (!m_captureGain->gain(¤t)) return; + // The bound that matters, and the one an earlier version of this got + // wrong: how far down we have come in decibels, not where the slider sits. + double currentDb = 0.0; + if (m_haveGainDb && m_captureGain->gainDb(¤tDb)) + { + if (m_gainStartDb - currentDb >= kMaxGainReductionDb) + { + closeGainCalibration(QString("already %1 dB down and still clipping") + .arg(m_gainStartDb - currentDb, 0, 'f', 1)); + return; + } + } + // Size the step to how badly it is clipping. A microphone left at maximum // is 20-30dB too hot and wants covering quickly; one that only tips over // on the loudest syllable wants nudging, not slamming. @@ -498,22 +555,61 @@ void AudioVideoCallController::capture_clipping(double pinnedPercent, double pea factor = 0.95; double next = current * factor; - if (next < kMinCaptureGain) - next = kMinCaptureGain; - if (next >= current) - return; // already at the floor, nothing left to give + { + closeGainCalibration("control is already at its minimum"); + return; + } if (!m_captureGain->setGain(next)) { - qWarning() << "Could not lower the capture gain - leaving it alone"; - m_captureGainSteps = kMaxCaptureGainSteps; + closeGainCalibration("the control would not move"); return; } m_captureGainSteps++; - qDebug("Capture gain %.0f%% -> %.0f%% (step %d of %d)", - current * 100.0, next * 100.0, m_captureGainSteps, kMaxCaptureGainSteps); + m_lastPinnedPercent = pinnedPercent; + m_gainSettleReports = kGainSettleReports; + + double achieved = 0.0; + double newDb = 0.0; + if (m_haveGainDb && m_captureGain->gainDb(&newDb)) + { + achieved = currentDb - newDb; + qDebug("Capture gain %.0f%% -> %.0f%% (%.1f dB, %.1f dB below the user's setting)", + current * 100.0, next * 100.0, -achieved, m_gainStartDb - newDb); + + // A step that moved the slider but not the level means we are pushing + // against the end of a control that no longer does anything. + if (achieved < kMinEffectiveStepDb) + m_gainIneffectiveSteps++; + + // Close on the step that crosses the ceiling rather than waiting for + // another report, which would let one more step through first. + if (m_gainStartDb - newDb >= kMaxGainReductionDb) + closeGainCalibration(QString("reached the %1 dB limit") + .arg(kMaxGainReductionDb, 0, 'f', 0)); + } + else + { + qDebug("Capture gain %.0f%% -> %.0f%% (step %d of %d)", + current * 100.0, next * 100.0, m_captureGainSteps, kMaxCaptureGainSteps); + } + + // The echo path just changed by however many dB that was, so everything + // the filter has learned about it is now wrong. Telling it to start over + // costs a second of convergence; not telling it costs the rest of the call. + if (m_echoCanceller) + m_echoCanceller->reset(); +} + +void AudioVideoCallController::closeGainCalibration(const QString &why) +{ + if (!m_gainCalibrating) + return; + + m_gainCalibrating = false; + qDebug() << "Microphone gain calibration finished:" << why; } void AudioVideoCallController::startCaptureGainControl(const QString &captureDevice) @@ -522,9 +618,15 @@ void AudioVideoCallController::startCaptureGainControl(const QString &captureDev m_savedCaptureGain = 0.0; m_haveSavedCaptureGain = false; m_captureGainSteps = 0; + m_gainCalibrating = false; + m_gainStartDb = 0.0; + m_haveGainDb = false; + m_gainIneffectiveSteps = 0; + m_lastPinnedPercent = 0.0; + m_gainSettleReports = 0; Settings st(config_dbname); - if (!st.loadValue("audio.auto_capture_gain", 1).toBool()) + if (!st.loadValue("audio.auto_capture_gain", 0).toBool()) return; // Whichever driver the capture side is about to open the device with - @@ -535,20 +637,29 @@ void AudioVideoCallController::startCaptureGainControl(const QString &captureDev if (!m_captureGain) return; - if (m_captureGain->gain(&m_savedCaptureGain)) - { - m_haveSavedCaptureGain = true; - qDebug() << "Automatic microphone gain using" << m_captureGain->description() - << "- currently at" << qRound(m_savedCaptureGain * 100.0) << "%"; - } - else + if (!m_captureGain->gain(&m_savedCaptureGain)) { // Without a reading there is nothing to put back afterwards, and // moving a control we cannot restore is not a trade worth making. qWarning() << "Could not read the capture gain - not taking it over"; delete m_captureGain; m_captureGain = nullptr; + return; } + + m_haveSavedCaptureGain = true; + m_haveGainDb = m_captureGain->gainDb(&m_gainStartDb); + m_gainCalibrating = true; + + if (m_haveGainDb) + qDebug("Microphone gain calibration open on %s - at %.0f%% (%.1f dB), will cut at most %.0f dB", + qPrintable(m_captureGain->description()), m_savedCaptureGain * 100.0, + m_gainStartDb, kMaxGainReductionDb); + else + qDebug("Microphone gain calibration open on %s - at %.0f%%, no dB scale so bounded " + "to %d steps", + qPrintable(m_captureGain->description()), m_savedCaptureGain * 100.0, + kMaxCaptureGainSteps); } void AudioVideoCallController::stopCaptureGainControl() @@ -572,6 +683,7 @@ void AudioVideoCallController::stopCaptureGainControl() m_captureGain = nullptr; m_haveSavedCaptureGain = false; m_captureGainSteps = 0; + m_gainCalibrating = false; } void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate) -- cgit v1.2.1 From 9a84c95af6771590d4e5fe436e77bbe92a9dea92 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 13 Sep 2026 19:53:28 +0400 Subject: pica-client: use webrtc-audio-processing instead of speexdsp for echo cancellation --- pica-client/audiovideocallcontroller.cpp | 255 +++---------------------------- 1 file changed, 19 insertions(+), 236 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 405746d..72b6fc2 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -30,12 +30,10 @@ static const quint16 kVideoHeight = 480; // Rate we capture and encode at, announced to the peer in the 0x74 message. // -// 16kHz rather than 48kHz because of the echo canceller. speexdsp's MDF is -// tuned for 8/16kHz, and its cost is counted in taps: a 150ms tail is 7200 -// taps at 48kHz but only 2400 at 16kHz. Convergence time and steady state -// misadjustment both scale with that length, so the 48kHz filter spent every -// call chasing and never settling - visible in the AEC log as ERLE climbing -// towards 20dB and being knocked back to zero by each doubletalk burst. +// 16kHz rather than 48kHz because it is what the echo canceller wants. AEC3 +// does its filtering in the 0-8kHz band whatever it is handed; at 48kHz it +// splits the signal into four bands, cancels in the lowest and gates the rest, +// which is more work for a result that is no better on speech. // // Costs nothing worth having for speech: Opus codes this as wideband, an 8kHz // audio bandwidth, which is well past telephone quality and past where voice @@ -49,10 +47,7 @@ static const int kCallSampleRate = 16000; AudioVideoCallController::AudioVideoCallController(QObject *parent) : QObject(parent), callwindow(0), ringdevice(0), is_active(false), - m_captureGain(nullptr), m_savedCaptureGain(0.0), m_haveSavedCaptureGain(false), - m_gainCalibrating(false), m_captureGainSteps(0), m_gainStartDb(0.0), - m_haveGainDb(false), m_gainIneffectiveSteps(0), m_lastPinnedPercent(0.0), - m_gainSettleReports(0), m_audioSeq(0), + m_audioSeq(0), m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false) { connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); @@ -189,11 +184,11 @@ void AudioVideoCallController::startAudioPipeline() // stopAudioPipeline() does not join either thread, so this has to outlive // whichever of them returns last. // - // It is created even on the platforms that cancel for us, because whether - // they really will is not known until the capture stream has been opened - // - see AudioDevice::captureNative(), which drops it once the backend - // says the platform has the job in hand. - if (st.loadValue("audio.echo_cancel", 1).toBool()) + // Only for EchoCancellationOwn. The other two settings mean something + // below us is doing the job or nobody is, and either way running this as + // well would only take a second bite out of the speech - the devices are + // opened accordingly, see AudioDevice::captureNative(). + if (AudioDevice::EchoCancellation() == EchoCancellationOwn) m_echoCanceller = EchoCancellerPtr(new EchoCanceller(kCallSampleRate)); else m_echoCanceller.clear(); @@ -206,10 +201,6 @@ void AudioVideoCallController::startAudioPipeline() microphone->setEchoCanceller(m_echoCanceller); output->setEchoCanceller(m_echoCanceller); - // Before Capture() starts, so the gain is already read and saved by the - // time the first clipping report can come back. - startCaptureGainControl(capDev); - // Declare our outgoing codec to the peer, then start capturing and // encoding right away - the peer's decoder is only ready once it has // processed this 0x74 message, but since the call is carried over TCP, @@ -238,12 +229,6 @@ void AudioVideoCallController::stopAudioPipeline() microphone->Close(); output->Close(); - // Puts the user's gain back. Safe to do while the capture thread is still - // winding down: the control is only ever touched from this thread, and - // capture_clipping() finds m_captureGain null and does nothing if a last - // queued report arrives after this. - stopCaptureGainControl(); - // Drop our reference. The two audio threads still hold theirs until they // come out of Capture()/Play(), and the canceller goes away with the last // of them. @@ -469,222 +454,20 @@ void AudioVideoCallController::send_audio_packet(QByteArray data) } // Rate limited by AudioDevice, which reports at most once every couple of -// seconds of audio, so this can log and act unconditionally. +// seconds of audio, so this can log unconditionally. +// +// Only a warning, and deliberately: clipping happens in the converter, before +// anything here sees a sample, so nothing in this process can undo it. The +// fix is less gain ahead of the ADC, which is the capture device's own mixer +// control and the user's to set. void AudioVideoCallController::capture_clipping(double pinnedPercent, double peakDb) { - qWarning("Microphone is clipping: %.2f%% of samples at full scale, peak %.1f dBFS", + qWarning("Microphone is clipping: %.2f%% of samples at full scale, peak %.1f dBFS - " + "turn the recording level down, it distorts the speech and stops the echo " + "canceller converging", pinnedPercent, peakDb); - - // Either the setting is off, or nothing on this platform would let us at - // the control. The warning above is then all we can do - and it is still - // worth having, since the distortion cannot be undone anywhere else. - if (!m_captureGain || !m_gainCalibrating) - return; - - // Calibration is a thing that happens at the start of a call, not a gain - // rider. Once the window has passed the level is whatever it is: moving it - // mid-conversation would keep dragging the echo path out from under the - // canceller, which is worse than a bit of distortion. - if (m_callClock.elapsed() > kGainCalibrationMs) - { - closeGainCalibration("calibration window has passed"); - return; - } - - // The audio in this report may predate the last adjustment. - if (m_gainSettleReports > 0) - { - m_gainSettleReports--; - return; - } - - // Without a dB scale there is no safe way to know how far down we have - // come, so the step count has to be the bound - and a much tighter one, - // since six steps of 0.7 is over 50 dB on a perceptual scale. - const int stepLimit = m_haveGainDb ? kMaxCaptureGainSteps : kMaxBlindGainSteps; - if (m_captureGainSteps >= stepLimit) - { - closeGainCalibration("step limit reached"); - return; - } - - // Did the previous adjustment achieve anything? Two that did not means the - // stage overloading is not the one we are holding. - if (m_captureGainSteps > 0 && pinnedPercent >= m_lastPinnedPercent) - { - m_gainIneffectiveSteps++; - if (m_gainIneffectiveSteps >= kMaxGainIneffectiveSteps) - { - closeGainCalibration("lowering this control is not reducing the clipping - " - "something ahead of it (an analog mic boost, or Windows' " - "separate Microphone Boost) is what is overloading"); - return; - } - } - else - { - m_gainIneffectiveSteps = 0; - } - - double current = 0.0; - if (!m_captureGain->gain(¤t)) - return; - - // The bound that matters, and the one an earlier version of this got - // wrong: how far down we have come in decibels, not where the slider sits. - double currentDb = 0.0; - if (m_haveGainDb && m_captureGain->gainDb(¤tDb)) - { - if (m_gainStartDb - currentDb >= kMaxGainReductionDb) - { - closeGainCalibration(QString("already %1 dB down and still clipping") - .arg(m_gainStartDb - currentDb, 0, 'f', 1)); - return; - } - } - - // Size the step to how badly it is clipping. A microphone left at maximum - // is 20-30dB too hot and wants covering quickly; one that only tips over - // on the loudest syllable wants nudging, not slamming. - double factor; - if (pinnedPercent >= 5.0) - factor = 0.70; - else if (pinnedPercent >= 0.5) - factor = 0.85; - else - factor = 0.95; - - double next = current * factor; - if (next >= current) - { - closeGainCalibration("control is already at its minimum"); - return; - } - - if (!m_captureGain->setGain(next)) - { - closeGainCalibration("the control would not move"); - return; - } - - m_captureGainSteps++; - m_lastPinnedPercent = pinnedPercent; - m_gainSettleReports = kGainSettleReports; - - double achieved = 0.0; - double newDb = 0.0; - if (m_haveGainDb && m_captureGain->gainDb(&newDb)) - { - achieved = currentDb - newDb; - qDebug("Capture gain %.0f%% -> %.0f%% (%.1f dB, %.1f dB below the user's setting)", - current * 100.0, next * 100.0, -achieved, m_gainStartDb - newDb); - - // A step that moved the slider but not the level means we are pushing - // against the end of a control that no longer does anything. - if (achieved < kMinEffectiveStepDb) - m_gainIneffectiveSteps++; - - // Close on the step that crosses the ceiling rather than waiting for - // another report, which would let one more step through first. - if (m_gainStartDb - newDb >= kMaxGainReductionDb) - closeGainCalibration(QString("reached the %1 dB limit") - .arg(kMaxGainReductionDb, 0, 'f', 0)); - } - else - { - qDebug("Capture gain %.0f%% -> %.0f%% (step %d of %d)", - current * 100.0, next * 100.0, m_captureGainSteps, kMaxCaptureGainSteps); - } - - // The echo path just changed by however many dB that was, so everything - // the filter has learned about it is now wrong. Telling it to start over - // costs a second of convergence; not telling it costs the rest of the call. - if (m_echoCanceller) - m_echoCanceller->reset(); -} - -void AudioVideoCallController::closeGainCalibration(const QString &why) -{ - if (!m_gainCalibrating) - return; - - m_gainCalibrating = false; - qDebug() << "Microphone gain calibration finished:" << why; -} - -void AudioVideoCallController::startCaptureGainControl(const QString &captureDevice) -{ - m_captureGain = nullptr; - m_savedCaptureGain = 0.0; - m_haveSavedCaptureGain = false; - m_captureGainSteps = 0; - m_gainCalibrating = false; - m_gainStartDb = 0.0; - m_haveGainDb = false; - m_gainIneffectiveSteps = 0; - m_lastPinnedPercent = 0.0; - m_gainSettleReports = 0; - - Settings st(config_dbname); - if (!st.loadValue("audio.auto_capture_gain", 0).toBool()) - return; - - // Whichever driver the capture side is about to open the device with - - // the mixer control has to be the one belonging to that device. - const QString driver = AudioDevice::PlatformDriverName(CAPTURE); - - m_captureGain = CaptureGainControl::create(driver, captureDevice); - if (!m_captureGain) - return; - - if (!m_captureGain->gain(&m_savedCaptureGain)) - { - // Without a reading there is nothing to put back afterwards, and - // moving a control we cannot restore is not a trade worth making. - qWarning() << "Could not read the capture gain - not taking it over"; - delete m_captureGain; - m_captureGain = nullptr; - return; - } - - m_haveSavedCaptureGain = true; - m_haveGainDb = m_captureGain->gainDb(&m_gainStartDb); - m_gainCalibrating = true; - - if (m_haveGainDb) - qDebug("Microphone gain calibration open on %s - at %.0f%% (%.1f dB), will cut at most %.0f dB", - qPrintable(m_captureGain->description()), m_savedCaptureGain * 100.0, - m_gainStartDb, kMaxGainReductionDb); - else - qDebug("Microphone gain calibration open on %s - at %.0f%%, no dB scale so bounded " - "to %d steps", - qPrintable(m_captureGain->description()), m_savedCaptureGain * 100.0, - kMaxCaptureGainSteps); } -void AudioVideoCallController::stopCaptureGainControl() -{ - if (!m_captureGain) - return; - - // Put the user's own setting back. Only bother if we actually moved it, - // so a call that never clipped cannot disturb a gain the user changed - // themselves while it was running. - if (m_haveSavedCaptureGain && m_captureGainSteps > 0) - { - if (m_captureGain->setGain(m_savedCaptureGain)) - qDebug() << "Capture gain restored to" << qRound(m_savedCaptureGain * 100.0) << "%"; - else - qWarning() << "Could not restore the capture gain to" - << qRound(m_savedCaptureGain * 100.0) << "% - it has been left turned down"; - } - - delete m_captureGain; - m_captureGain = nullptr; - m_haveSavedCaptureGain = false; - m_captureGainSteps = 0; - m_gainCalibrating = false; -} void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate) { -- cgit v1.2.1 From 76225a538e1e960eda9e31a34846f4bc62adef87 Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 26 Sep 2026 19:00:40 +0400 Subject: pica-client: configurable resolutions, codecs, bitrates for a call --- pica-client/audiovideocallcontroller.cpp | 57 +++++++++++++++++--------------- 1 file changed, 30 insertions(+), 27 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 72b6fc2..9b4ae4d 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -18,32 +18,11 @@ #include "globals.h" #include "skynet.h" #include "settings.h" +#include "callsettings.h" #include #include #include -// Capture/encode resolution announced to the peer in the 0x75 message. Fixed -// for now - a resolution setting is a planned follow-up, see VideoDevice for -// the rest of the encoding parameters. -static const quint16 kVideoWidth = 640; -static const quint16 kVideoHeight = 480; - -// Rate we capture and encode at, announced to the peer in the 0x74 message. -// -// 16kHz rather than 48kHz because it is what the echo canceller wants. AEC3 -// does its filtering in the 0-8kHz band whatever it is handed; at 48kHz it -// splits the signal into four bands, cancels in the lowest and gates the rest, -// which is more work for a result that is no better on speech. -// -// Costs nothing worth having for speech: Opus codes this as wideband, an 8kHz -// audio bandwidth, which is well past telephone quality and past where voice -// intelligibility stops improving. -// -// The playback direction is NOT this constant - it follows whatever the peer -// announces (see incoming_audio_params()), so a call with an older build that -// still sends 48kHz keeps working. -static const int kCallSampleRate = 16000; - AudioVideoCallController::AudioVideoCallController(QObject *parent) : QObject(parent), callwindow(0), ringdevice(0), is_active(false), @@ -174,6 +153,21 @@ void AudioVideoCallController::startAudioPipeline() { Settings st(config_dbname); QString capDev = st.loadValue("audio.capture_device", "default").toString(); + const CallSettings cs = CallSettings::load(); + + // What we capture and encode at, announced to the peer in the 0x74 + // message. It follows from the codec - see callAudioSampleRate(). + // + // The playback direction is NOT this: it follows whatever the peer + // announces in its own 0x74 (see incoming_audio_params()), so a call with + // a peer that picked a different codec or rate keeps working. + const int sampleRate = callAudioSampleRate(cs.audioCodec); + + // G.722 and A-law spend a fixed number of bits per sample and have no rate + // to ask for; the setting only means anything to Opus. + const int bitrate = callAudioBitrateAdjustable(cs.audioCodec) + ? cs.audioBitrateKbps * 1000 + : 0; m_audioSeq = 0; m_callClock.start(); @@ -188,8 +182,12 @@ void AudioVideoCallController::startAudioPipeline() // below us is doing the job or nobody is, and either way running this as // well would only take a second bite out of the speech - the devices are // opened accordingly, see AudioDevice::captureNative(). + // + // Built at the rate the codec runs at rather than at a fixed one, so that + // choosing a codec does not quietly switch cancellation off: the capture + // side drops a canceller whose rate does not match its own. if (AudioDevice::EchoCancellation() == EchoCancellationOwn) - m_echoCanceller = EchoCancellerPtr(new EchoCanceller(kCallSampleRate)); + m_echoCanceller = EchoCancellerPtr(new EchoCanceller(sampleRate)); else m_echoCanceller.clear(); @@ -205,10 +203,11 @@ void AudioVideoCallController::startAudioPipeline() // encoding right away - the peer's decoder is only ready once it has // processed this 0x74 message, but since the call is carried over TCP, // packets sent immediately after are guaranteed to arrive after it. - skynet->SendAudioParams(m_peer_id, QStringLiteral("opus"), kCallSampleRate); + skynet->SendAudioParams(m_peer_id, cs.audioCodec, (quint16)sampleRate); QMetaObject::invokeMethod(microphone, "configureCapture", Qt::QueuedConnection, - Q_ARG(QString, capDev), Q_ARG(QString, QStringLiteral("opus")), Q_ARG(int, kCallSampleRate)); + Q_ARG(QString, capDev), Q_ARG(QString, cs.audioCodec), + Q_ARG(int, sampleRate), Q_ARG(int, bitrate)); QMetaObject::invokeMethod(microphone, "Capture", Qt::QueuedConnection); // output is configured lazily, once the peer's own 0x74 (see @@ -239,6 +238,7 @@ void AudioVideoCallController::startVideoPipeline() { Settings st(config_dbname); QString camDev = st.loadValue("video.capture_device", QString()).toString(); + const CallSettings cs = CallSettings::load(); // Unlike the audio devices, which fall back to the platform's "default" // device, there is no such name for cameras - so with nothing configured @@ -278,8 +278,11 @@ void AudioVideoCallController::startVideoPipeline() // video_capture_started()). QMetaObject::invokeMethod(cam, "configureCapture", Qt::QueuedConnection, Q_ARG(QString, camDev), - Q_ARG(int, kVideoWidth), Q_ARG(int, kVideoHeight), - Q_ARG(bool, preferCompressed), Q_ARG(bool, vaapiEncoding)); + Q_ARG(int, cs.captureWidth), Q_ARG(int, cs.captureHeight), + Q_ARG(int, cs.captureFrameRate), + Q_ARG(bool, preferCompressed), + Q_ARG(QString, cs.videoCodec), Q_ARG(int, cs.videoBitrateKbps * 1000), + Q_ARG(bool, vaapiEncoding)); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see -- cgit v1.2.1 From 835b124bd871afecd88c1e5e9105e3af4d4c5b27 Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 3 Oct 2026 20:33:04 +0400 Subject: pica-client: callwindow layout, video resize --- pica-client/audiovideocallcontroller.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 9b4ae4d..a6da3f5 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -374,6 +374,7 @@ void AudioVideoCallController::start_call(QByteArray peer_id) /* decoded frames arrive from remotevideo's thread, so this is a queued connection; it dies with the window, which is deleted on close */ connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); + connect(callwindow, SIGNAL(video_area_changed(QSize)), this, SLOT(video_area_changed(QSize))); #ifdef HAVE_VAAPI connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed())); @@ -397,6 +398,7 @@ void AudioVideoCallController::call_from(QByteArray peer_id) connect(callwindow, SIGNAL(callwindow_closed(CallWindow*)), this, SLOT(callwindow_closed(CallWindow*))); /* see the same connections in start_call() */ connect(remotevideo, SIGNAL(frameReady(QImage)), callwindow, SLOT(showRemoteFrame(QImage))); + connect(callwindow, SIGNAL(video_area_changed(QSize)), this, SLOT(video_area_changed(QSize))); #ifdef HAVE_VAAPI connect(remotevideo, SIGNAL(hwFrameReady(AVFramePtr)), callwindow, SLOT(showRemoteHwFrame(AVFramePtr))); connect(callwindow, SIGNAL(video_rendering_failed()), this, SLOT(video_rendering_failed())); @@ -595,6 +597,13 @@ void AudioVideoCallController::incoming_video_packet(QByteArray peer_id, quint16 remotevideo->enqueueFrame(frame); } +void AudioVideoCallController::video_area_changed(QSize area) +{ + // Direct call rather than invokeMethod() - same reason as in + // incoming_video_packet(): remotevideo's thread is blocked inside Play(). + remotevideo->setDisplaySize(area); +} + #ifdef HAVE_VAAPI void AudioVideoCallController::video_rendering_failed() { -- cgit v1.2.1 From e7a468d008de86ddfdf62c7d4cb2888678402370 Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 3 Oct 2026 22:12:26 +0400 Subject: pica-client: fix capture at requested fps --- pica-client/audiovideocallcontroller.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index a6da3f5..601f3e4 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -27,7 +27,8 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) : QObject(parent), callwindow(0), ringdevice(0), is_active(false), m_audioSeq(0), - m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false) + m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false), + m_requestedFrameRate(0) { connect(skynet, SIGNAL(IncomingCall(QByteArray)), this, SLOT(call_from(QByteArray))); connect(skynet, SIGNAL(CallFailed(QByteArray,QString)), this, SLOT(call_failed(QByteArray,QString))); @@ -78,7 +79,7 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) // the audio devices above. cam = new VideoDevice(); cam->moveToThread(&cam_thread); - connect(cam, SIGNAL(captureStarted(QString,int,int)), this, SLOT(video_capture_started(QString,int,int))); + connect(cam, SIGNAL(captureStarted(QString,int,int,double)), this, SLOT(video_capture_started(QString,int,int,double))); connect(cam, SIGNAL(packetReady(QByteArray,bool)), this, SLOT(send_video_packet(QByteArray,bool))); cam_thread.start(); @@ -272,6 +273,10 @@ void AudioVideoCallController::startVideoPipeline() bool preferCompressed = st.loadValue("video.prefer_compressed", 0).toBool(); bool vaapiEncoding = st.loadValue("video.vaapi_encoding", 0).toBool(); + // Kept so that video_capture_started() can tell whether the camera + // honoured it, which is not something the camera reports. + m_requestedFrameRate = cs.captureFrameRate; + // The peer is told what we are sending only once the camera is open and // the format is settled - with a compressed camera stream being forwarded // as-is, the codec is the camera's choice, not ours (see @@ -502,11 +507,21 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 output->enqueuePacket(seq_num, data); } -void AudioVideoCallController::video_capture_started(QString codec, int width, int height) +void AudioVideoCallController::video_capture_started(QString codec, int width, int height, + double frameRate) { if (!is_active) return; + // Logged rather than announced: the 0x74 message has no field for it, and + // the peer does not need one - every frame carries its own timestamp. It + // is worth a line in the log all the same, since a camera that quietly + // substituted a lower rate than was asked for is otherwise invisible from + // the other end of a complaint about choppy video. + if (frameRate > 0.0 && frameRate < m_requestedFrameRate - 0.5) + qWarning() << QString("Camera delivering %1 fps, not the %2 that was requested") + .arg(frameRate, 0, 'f', 1).arg(m_requestedFrameRate); + // Announced only now, because what the camera turned out to deliver // decides it: a compressed camera stream is forwarded in the camera's own // codec and at the camera's own size, rather than in ours. -- cgit v1.2.1 From 8f87c8491ffd9567df97979e9c18d4c148357870 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 4 Oct 2026 20:27:09 +0400 Subject: pica-client: more hardware acceleration options on Windows --- pica-client/audiovideocallcontroller.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 601f3e4..5b3c05c 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -271,7 +271,6 @@ void AudioVideoCallController::startVideoPipeline() cam->setMaxFragmentSize(PICA_MEDIA_SAFE_PAYLOAD); bool preferCompressed = st.loadValue("video.prefer_compressed", 0).toBool(); - bool vaapiEncoding = st.loadValue("video.vaapi_encoding", 0).toBool(); // Kept so that video_capture_started() can tell whether the camera // honoured it, which is not something the camera reports. @@ -287,7 +286,7 @@ void AudioVideoCallController::startVideoPipeline() Q_ARG(int, cs.captureFrameRate), Q_ARG(bool, preferCompressed), Q_ARG(QString, cs.videoCodec), Q_ARG(int, cs.videoBitrateKbps * 1000), - Q_ARG(bool, vaapiEncoding)); + Q_ARG(int, cs.videoEncodingAcceleration)); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see @@ -580,7 +579,7 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString return; Settings st(config_dbname); - bool vaapiDecoding = st.loadValue("video.vaapi_decoding", 0).toBool(); + const CallSettings cs = CallSettings::load(); bool vaapiRendering = st.loadValue("video.vaapi_rendering", 0).toBool(); #ifdef HAVE_VAAPI @@ -592,7 +591,7 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), - Q_ARG(bool, vaapiDecoding), Q_ARG(bool, vaapiRendering)); + Q_ARG(int, cs.videoDecodingAcceleration), Q_ARG(bool, vaapiRendering)); QMetaObject::invokeMethod(remotevideo, "Play", Qt::QueuedConnection); } -- cgit v1.2.1 From 5ead3432dba8c0e2724f796c9765612a7bf36a31 Mon Sep 17 00:00:00 2001 From: Anton Date: Wed, 11 Nov 2026 07:22:19 +0400 Subject: pica-client: codec names from the allow list only --- pica-client/audiovideocallcontroller.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 5b3c05c..8f7c8df 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -483,6 +483,14 @@ void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString if (!is_active || peer_id != m_peer_id) return; + // The codec name is peer-supplied and would otherwise be handed straight + // to the FFmpeg decoder - accept only the ones the client itself sends. + if (!callAudioCodecAccepted(codec)) + { + qWarning() << "rejecting unsupported call audio codec from peer:" << codec; + return; + } + Settings st(config_dbname); QString playDev = st.loadValue("audio.playback_device", "default").toString(); @@ -578,6 +586,14 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString if (!is_active || peer_id != m_peer_id) return; + // As in incoming_audio_params(): the peer-supplied codec name must be one + // we actually send before it reaches avcodec_find_decoder_by_name(). + if (!callVideoCodecAccepted(codec)) + { + qWarning() << "rejecting unsupported call video codec from peer:" << codec; + return; + } + Settings st(config_dbname); const CallSettings cs = CallSettings::load(); bool vaapiRendering = st.loadValue("video.vaapi_rendering", 0).toBool(); -- cgit v1.2.1 From 6d8ece9aa9a90937434ef2a4b6917a319a325d4e Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 14 Nov 2026 00:27:08 +0400 Subject: pica-client: fix releasing call resources --- pica-client/audiovideocallcontroller.cpp | 231 ++++++++++++++++++++++++------- 1 file changed, 183 insertions(+), 48 deletions(-) (limited to 'pica-client/audiovideocallcontroller.cpp') diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 8f7c8df..62cb0e0 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -19,13 +19,15 @@ #include "skynet.h" #include "settings.h" #include "callsettings.h" +#include "accounts.h" #include #include #include AudioVideoCallController::AudioVideoCallController(QObject *parent) - : QObject(parent), callwindow(0), ringdevice(0), is_active(false), + : QObject(parent), callwindow(0), ringdevice(0), m_state(CallIdle), + m_audioPlaybackStarted(false), m_videoPlaybackStarted(false), m_audioSeq(0), m_videoSeq(0), m_videoFrameTimestamp(0), m_videoFrameStarted(false), m_requestedFrameRate(0) @@ -35,6 +37,10 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) connect(skynet, SIGNAL(CallAccepted(QByteArray)), this, SLOT(call_accepted(QByteArray))); connect(skynet, SIGNAL(CallRejected(QByteArray)), this, SLOT(call_rejected(QByteArray))); connect(skynet, SIGNAL(CallHungup(QByteArray)), this, SLOT(call_hungup(QByteArray))); + connect(skynet, SIGNAL(c2cClosed(QByteArray)), this, SLOT(peer_disconnected(QByteArray))); + + // setEchoCanceller() is invoked through the audio threads' event queues + qRegisterMetaType("EchoCancellerPtr"); connect(skynet, SIGNAL(IncomingAudioParams(QByteArray,QString,quint16)), this, SLOT(incoming_audio_params(QByteArray,QString,quint16))); connect(skynet, SIGNAL(IncomingAudioPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_audio_packet(QByteArray,quint16,quint32,QByteArray))); @@ -172,6 +178,13 @@ void AudioVideoCallController::startAudioPipeline() m_audioSeq = 0; m_callClock.start(); + m_audioPlaybackStarted = false; + + // Before anything is queued for them - see MediaCallSession. output is + // opened here as well, although it is only started once the peer's 0x74 + // arrives. + microphone->openSession(m_caller_id, m_callee_id); + output->openSession(m_caller_id, m_callee_id); // One canceller for the call, shared by both directions: the playback // side feeds it what it is about to play, the capture side subtracts the @@ -195,10 +208,13 @@ void AudioVideoCallController::startAudioPipeline() if (m_echoCanceller && !m_echoCanceller->isValid()) m_echoCanceller.clear(); - // Set before the blocking loops are started, so the queued Capture()/ - // Play() calls below are what publishes it to those threads. - microphone->setEchoCanceller(m_echoCanceller); - output->setEchoCanceller(m_echoCanceller); + // Queued like the calls that start the loops, and ahead of them: the + // loops of the previous call may still be on their way out, and they read + // the canceller they were given on their own threads. + QMetaObject::invokeMethod(microphone, "setEchoCanceller", Qt::QueuedConnection, + Q_ARG(EchoCancellerPtr, m_echoCanceller)); + QMetaObject::invokeMethod(output, "setEchoCanceller", Qt::QueuedConnection, + Q_ARG(EchoCancellerPtr, m_echoCanceller)); // Declare our outgoing codec to the peer, then start capturing and // encoding right away - the peer's decoder is only ready once it has @@ -208,7 +224,8 @@ void AudioVideoCallController::startAudioPipeline() QMetaObject::invokeMethod(microphone, "configureCapture", Qt::QueuedConnection, Q_ARG(QString, capDev), Q_ARG(QString, cs.audioCodec), - Q_ARG(int, sampleRate), Q_ARG(int, bitrate)); + Q_ARG(int, sampleRate), Q_ARG(int, bitrate), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); QMetaObject::invokeMethod(microphone, "Capture", Qt::QueuedConnection); // output is configured lazily, once the peer's own 0x74 (see @@ -241,6 +258,12 @@ void AudioVideoCallController::startVideoPipeline() QString camDev = st.loadValue("video.capture_device", QString()).toString(); const CallSettings cs = CallSettings::load(); + // Before anything is queued for them - see MediaCallSession. And before + // the check for a camera below: remotevideo does not depend on having one. + m_videoPlaybackStarted = false; + cam->openSession(m_caller_id, m_callee_id); + remotevideo->openSession(m_caller_id, m_callee_id); + // Unlike the audio devices, which fall back to the platform's "default" // device, there is no such name for cameras - so with nothing configured // yet (the setting is only written once the settings dialog has been @@ -286,7 +309,8 @@ void AudioVideoCallController::startVideoPipeline() Q_ARG(int, cs.captureFrameRate), Q_ARG(bool, preferCompressed), Q_ARG(QString, cs.videoCodec), Q_ARG(int, cs.videoBitrateKbps * 1000), - Q_ARG(int, cs.videoEncodingAcceleration)); + Q_ARG(int, cs.videoEncodingAcceleration), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see @@ -302,14 +326,43 @@ void AudioVideoCallController::stopVideoPipeline() m_videoAssembler.reset(); } +void AudioVideoCallController::finishCall(bool notify_peer) +{ + const CallState state = m_state; + + m_state = CallIdle; + + stopTones(); + stopAudioPipeline(); + stopVideoPipeline(); + + if (!notify_peer) + return; + + if (state == CallDialing || state == CallActive) + skynet->HangupCall(m_peer_id); + else if (state == CallRinging) + skynet->RejectCall(m_peer_id); +} + void AudioVideoCallController::call_failed(QByteArray peer_id, QString reason) { qDebug() << "Call failed: " << reason << "\n"; - if (peer_id != m_peer_id) + /* Only starting a call and answering one can fail in a way that matters + here; anything else arrives when the call is already over. */ + if (peer_id != m_peer_id || (m_state != CallDialing && m_state != CallActive)) return; - is_active = false; + const bool was_active = (m_state == CallActive); + + finishCall(false); + + /* After a failed attempt to call the window is left as it is, so that + "Call" can be pressed again. */ + if (was_active && callwindow) + callwindow->call_ended(); + /* play unreachable */ playEarpieceTone(&TonePlayer::playUnreachable); } @@ -320,11 +373,11 @@ void AudioVideoCallController::call_accepted(QByteArray peer_id) it is delivered the local side may have already hung up and closed the call window, or moved on to a different peer entirely. Either way the call it refers to is gone - do not bring the audio pipeline up for it. */ - if (peer_id != m_peer_id || !callwindow) + if (peer_id != m_peer_id || m_state != CallDialing || !callwindow) return; stopTones(); - is_active = true; + m_state = CallActive; callwindow->call_started(); startAudioPipeline(); startVideoPipeline(); @@ -332,28 +385,57 @@ void AudioVideoCallController::call_accepted(QByteArray peer_id) void AudioVideoCallController::call_rejected(QByteArray peer_id) { - if (peer_id != m_peer_id) + if (peer_id != m_peer_id || m_state != CallDialing) return; + finishCall(false); + /* play busy tone */ playEarpieceTone(&TonePlayer::playBusy); } void AudioVideoCallController::call_hungup(QByteArray peer_id) { - if (peer_id != m_peer_id) + /* queued from the SkyNet thread - the call may already be over here */ + if (peer_id != m_peer_id || m_state == CallIdle) return; - stopAudioPipeline(); - stopVideoPipeline(); + const bool was_ringing = (m_state == CallRinging); + + finishCall(false); + + if (was_ringing) + { + /* The caller gave up before the call was answered. Nothing is left + for the window to offer. */ + if (callwindow) + callwindow->close(); + + return; + } - /* queued from the SkyNet thread as well - the window may already be closed */ if (callwindow) callwindow->call_ended(); /* play busy tone */ playEarpieceTone(&TonePlayer::playBusy); - is_active = false; +} + +void AudioVideoCallController::peer_disconnected(QByteArray peer_id) +{ + if (peer_id != m_peer_id || m_state == CallIdle) + return; + + if (m_state == CallDialing) + { + finishCall(false); + playEarpieceTone(&TonePlayer::playUnreachable); + return; + } + + /* No hangup message is going to come over a connection that is gone, and + for the call it amounts to the same thing. */ + call_hungup(peer_id); } void AudioVideoCallController::start_call(QByteArray peer_id) @@ -362,15 +444,20 @@ void AudioVideoCallController::start_call(QByteArray peer_id) { callwindow->show(); - - /* call is already in progress */ - if (is_active) + /* one call at a time, and this one is not over yet */ + if (m_state != CallIdle) + { + callwindow->raise(); return; + } + /* re-create callwindow for a new call */ callwindow->close(); } m_peer_id = peer_id; + m_caller_id = Accounts::GetCurrentAccount().id; + m_callee_id = peer_id; callwindow = new CallWindow(peer_id, false); connect(callwindow, SIGNAL(start_call_pressed()), this, SLOT(initiate_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); @@ -388,14 +475,23 @@ void AudioVideoCallController::start_call(QByteArray peer_id) void AudioVideoCallController::call_from(QByteArray peer_id) { - if (callwindow) + /* One call at a time: busy. The peer hears the busy tone and our own call + is not disturbed. */ + if (m_state != CallIdle) { - /* HANDLE BUSY CASE!!! */ - /* call is already in progress */ + skynet->RejectCall(peer_id); return; } + /* A window left open with no call in it - one where "Call" has not been + pressed, or whose call is over - gives way to the incoming call. */ + if (callwindow) + callwindow->close(); + + m_state = CallRinging; m_peer_id = peer_id; + m_caller_id = peer_id; + m_callee_id = Accounts::GetCurrentAccount().id; callwindow = new CallWindow(peer_id, true); connect(callwindow, SIGNAL(accept_call_pressed()), this, SLOT(accept_call())); connect(callwindow, SIGNAL(hang_call_pressed()), this, SLOT(end_call())); @@ -415,6 +511,11 @@ void AudioVideoCallController::call_from(QByteArray peer_id) void AudioVideoCallController::initiate_call() { + /* "Call" pressed again while the first press is still ringing */ + if (m_state != CallIdle) + return; + + m_state = CallDialing; skynet->StartCall(m_peer_id); /* play ringing tone */ playEarpieceTone(&TonePlayer::playCallInProgress); @@ -422,9 +523,12 @@ void AudioVideoCallController::initiate_call() void AudioVideoCallController::accept_call() { + if (m_state != CallRinging) + return; + stopTones(); skynet->AcceptCall(m_peer_id); - is_active = true; + m_state = CallActive; callwindow->call_started(); startAudioPipeline(); startVideoPipeline(); @@ -432,28 +536,25 @@ void AudioVideoCallController::accept_call() void AudioVideoCallController::end_call() { - stopTones(); - stopAudioPipeline(); - stopVideoPipeline(); - - if (is_active) - skynet->HangupCall(m_peer_id); - else - skynet->RejectCall(m_peer_id); - - is_active = false; - callwindow->close(); + /* the call ends with its window, see callwindow_closed() */ + if (callwindow) + callwindow->close(); } void AudioVideoCallController::callwindow_closed(CallWindow *sender_window) { + if (sender_window != callwindow) + return; + + /* However the window got closed - "Hang Up", its close button, or being + replaced for a new call - whatever call was in it goes with it. */ + finishCall(true); callwindow = 0; - is_active = false; } void AudioVideoCallController::send_audio_packet(QByteArray data) { - if (!is_active) + if (m_state != CallActive) return; quint16 seq = m_audioSeq++; @@ -480,7 +581,7 @@ void AudioVideoCallController::capture_clipping(double pinnedPercent, double pea void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString codec, quint16 sample_rate) { - if (!is_active || peer_id != m_peer_id) + if (m_state != CallActive || peer_id != m_peer_id) return; // The codec name is peer-supplied and would otherwise be handed straight @@ -494,8 +595,26 @@ void AudioVideoCallController::incoming_audio_params(QByteArray peer_id, QString Settings st(config_dbname); QString playDev = st.loadValue("audio.playback_device", "default").toString(); - QMetaObject::invokeMethod(output, "configurePlayback", Qt::QueuedConnection, - Q_ARG(QString, playDev), Q_ARG(QString, codec), Q_ARG(int, (int)sample_rate)); + if (!m_audioPlaybackStarted) + { + m_audioPlaybackStarted = true; + QMetaObject::invokeMethod(output, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, playDev), Q_ARG(QString, codec), Q_ARG(int, (int)sample_rate), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); + } + else + { + // The peer changed what it is sending in the middle of the call. + // Direct call, not invokeMethod()/QueuedConnection - see the comment + // in stopAudioPipeline(): output's thread is blocked inside Play(), + // which starts over with the new parameters. + output->changePlayback(playDev, codec, (int)sample_rate); + } + + // Queued in both cases. If Play() is running, this one only gets its turn + // when the call is over and returns at once; but if Play() has given up - + // on a codec that would not open, say - this is what starts it again for + // the new parameters. QMetaObject::invokeMethod(output, "Play", Qt::QueuedConnection); } @@ -503,7 +622,7 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 { Q_UNUSED(timestamp); - if (!is_active || peer_id != m_peer_id) + if (m_state != CallActive || peer_id != m_peer_id) return; // Direct call, not invokeMethod()/QueuedConnection - see the comment in @@ -517,7 +636,7 @@ void AudioVideoCallController::incoming_audio_packet(QByteArray peer_id, quint16 void AudioVideoCallController::video_capture_started(QString codec, int width, int height, double frameRate) { - if (!is_active) + if (m_state != CallActive) return; // Logged rather than announced: the 0x74 message has no field for it, and @@ -537,7 +656,7 @@ void AudioVideoCallController::video_capture_started(QString codec, int width, i void AudioVideoCallController::send_video_packet(QByteArray data, bool is_last_fragment) { - if (!is_active) + if (m_state != CallActive) return; // Every fragment of one encoded frame carries the timestamp taken when @@ -583,7 +702,7 @@ void AudioVideoCallController::media_transport_changed(QByteArray peer_id, bool void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString codec, quint16 width, quint16 height) { - if (!is_active || peer_id != m_peer_id) + if (m_state != CallActive || peer_id != m_peer_id) return; // As in incoming_audio_params(): the peer-supplied codec name must be one @@ -605,15 +724,31 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString vaapiRendering = false; #endif - QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, - Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), - Q_ARG(int, cs.videoDecodingAcceleration), Q_ARG(bool, vaapiRendering)); + if (!m_videoPlaybackStarted) + { + m_videoPlaybackStarted = true; + QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, + Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), + Q_ARG(int, cs.videoDecodingAcceleration), Q_ARG(bool, vaapiRendering), + Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); + } + else + { + // The peer changed what it is sending in the middle of the call - as + // in incoming_audio_params(). A fragment of a frame in the old format + // that is still being put together is of no use to the new decoder. + m_videoAssembler.reset(); + remotevideo->changePlayback(codec, (int)width, (int)height, + cs.videoDecodingAcceleration, vaapiRendering); + } + + // Queued in both cases, see incoming_audio_params(). QMetaObject::invokeMethod(remotevideo, "Play", Qt::QueuedConnection); } void AudioVideoCallController::incoming_video_packet(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data) { - if (!is_active || peer_id != m_peer_id) + if (m_state != CallActive || peer_id != m_peer_id) return; QByteArray frame = m_videoAssembler.addFragment(seq_num, timestamp, data); -- cgit v1.2.1