diff options
| author | Anton <anton@picapica.im> | 2026-11-14 00:27:08 +0400 |
|---|---|---|
| committer | Anton <anton@picapica.im> | 2026-11-14 00:27:08 +0400 |
| commit | 6d8ece9aa9a90937434ef2a4b6917a319a325d4e (patch) | |
| tree | 632f92290d841861c6b1234fc56954c0358ebbaa | |
| parent | c4ca50c617f2b158a4448b68dd7c7a289c1ff0d9 (diff) | |
| download | pica-pica-6d8ece9aa9a90937434ef2a4b6917a319a325d4e.tar.gz pica-pica-6d8ece9aa9a90937434ef2a4b6917a319a325d4e.zip | |
pica-client: fix releasing call resources
| -rw-r--r-- | pica-client/audiodevice.cpp | 84 | ||||
| -rw-r--r-- | pica-client/audiodevice.h | 55 | ||||
| -rw-r--r-- | pica-client/audiovideocallcontroller.cpp | 231 | ||||
| -rw-r--r-- | pica-client/audiovideocallcontroller.h | 40 | ||||
| -rw-r--r-- | pica-client/dialogs/settingsdialog.cpp | 24 | ||||
| -rw-r--r-- | pica-client/echocanceller.h | 4 | ||||
| -rw-r--r-- | pica-client/mediadevice.h | 45 | ||||
| -rw-r--r-- | pica-client/skynet.cpp | 23 | ||||
| -rw-r--r-- | pica-client/videodevice.cpp | 85 | ||||
| -rw-r--r-- | pica-client/videodevice.h | 49 |
10 files changed, 544 insertions, 96 deletions
diff --git a/pica-client/audiodevice.cpp b/pica-client/audiodevice.cpp index fdfd449..19ce04e 100644 --- a/pica-client/audiodevice.cpp +++ b/pica-client/audiodevice.cpp @@ -243,7 +243,8 @@ static AVSampleFormat chooseEncoderSampleFmt(const AVCodec *enc) } AudioDevice::AudioDevice(QObject *parent) - : QObject(parent), m_sampleRate(48000), m_bitrate(kOpusBitrate), m_abort(0), + : QObject(parent), m_sampleRate(48000), m_bitrate(kOpusBitrate), m_reconfigure(0), + m_pendingSampleRate(48000), m_clipCount(0), m_levelCount(0), m_levelPeak(0), m_lastPlayedSeq(0), m_havePlayedSeq(false) { @@ -290,21 +291,46 @@ AudioDevice::~AudioDevice() Close(); } -void AudioDevice::configureCapture(QString deviceName, QString codec, int sampleRate, int bitrate) +void AudioDevice::configureCapture(QString deviceName, QString codec, int sampleRate, int bitrate, + QByteArray caller_id, QByteArray callee_id) { + m_caller_id = caller_id; + m_callee_id = callee_id; m_deviceName = deviceName; m_codec = codec; m_sampleRate = sampleRate; m_bitrate = bitrate > 0 ? bitrate : kOpusBitrate; } -void AudioDevice::configurePlayback(QString deviceName, QString codec, int sampleRate) +void AudioDevice::configurePlayback(QString deviceName, QString codec, int sampleRate, + QByteArray caller_id, QByteArray callee_id) { + m_caller_id = caller_id; + m_callee_id = callee_id; m_deviceName = deviceName; m_codec = codec; m_sampleRate = sampleRate; } +void AudioDevice::openSession(QByteArray caller_id, QByteArray callee_id) +{ + m_openSession.open(caller_id, callee_id); +} + +void AudioDevice::changePlayback(QString deviceName, QString codec, int sampleRate) +{ + { + QMutexLocker locker(&m_queueMutex); + m_pendingDeviceName = deviceName; + m_pendingCodec = codec; + m_pendingSampleRate = sampleRate; + m_reconfigure.storeRelaxed(1); + /* encoded with the parameters being replaced */ + m_playQueue.clear(); + } + m_queueCond.wakeAll(); +} + void AudioDevice::setEchoCanceller(EchoCancellerPtr ec) { m_echoCanceller = ec; @@ -357,10 +383,11 @@ void AudioDevice::enqueuePacket(quint16 seq_num, QByteArray data) void AudioDevice::Close() { - m_abort.storeRelaxed(1); + m_openSession.close(); { QMutexLocker locker(&m_queueMutex); + m_reconfigure.storeRelaxed(0); m_playQueue.clear(); /* the next call starts its own numbering */ m_havePlayedSeq = false; @@ -375,7 +402,7 @@ void AudioDevice::waitForPreroll() // the queue and starve the device buffer (heard as crackling/xruns). QMutexLocker locker(&m_queueMutex); - while (m_playQueue.size() < kPrerollDepth && !m_abort.loadRelaxed()) + while (m_playQueue.size() < kPrerollDepth && !stopRequested()) m_queueCond.wait(&m_queueMutex, 100); } @@ -383,11 +410,14 @@ bool AudioDevice::nextPacket(QByteArray *out) { QMutexLocker locker(&m_queueMutex); - while (m_playQueue.isEmpty() && !m_abort.loadRelaxed()) + while (m_playQueue.isEmpty() && !stopRequested()) m_queueCond.wait(&m_queueMutex, 100); + if (stopRequested()) + return false; + if (m_playQueue.isEmpty()) - return !m_abort.loadRelaxed(); + return true; PlaybackPacket p = m_playQueue.takeFirst(); @@ -400,7 +430,10 @@ bool AudioDevice::nextPacket(QByteArray *out) void AudioDevice::Capture() { - m_abort.storeRelaxed(0); + /* closed before it got to start */ + if (sessionClosed()) + return; + resetCaptureLevel(); const QString driver = AudioDevice::PlatformDriverName(CAPTURE); @@ -413,14 +446,33 @@ void AudioDevice::Capture() void AudioDevice::Play() { - m_abort.storeRelaxed(0); - const QString driver = AudioDevice::PlatformDriverName(PLAYBACK); - if (AudioDevice::IsPlatformDriver(driver)) - playNative(AudioDevice::PlatformApiName(driver)); - else - playFFmpeg(driver); + // More than one pass only when changePlayback() interrupts the one that is + // running. Also covers being closed before getting to start. + while (!sessionClosed()) + { + { + QMutexLocker locker(&m_queueMutex); + + if (m_reconfigure.loadRelaxed()) + { + m_deviceName = m_pendingDeviceName; + m_codec = m_pendingCodec; + m_sampleRate = m_pendingSampleRate; + m_reconfigure.storeRelaxed(0); + } + } + + if (AudioDevice::IsPlatformDriver(driver)) + playNative(AudioDevice::PlatformApiName(driver)); + else + playFFmpeg(driver); + + /* closed, or gave up on an error */ + if (!m_reconfigure.loadRelaxed()) + break; + } } void AudioDevice::captureFFmpeg(const QString &driver) @@ -571,7 +623,7 @@ void AudioDevice::captureFFmpeg(const QString &driver) bool loggedDecodeError = false; bool loggedEncodeError = false; - while (!m_abort.loadRelaxed()) + while (!stopRequested()) { ret = av_read_frame(ifmt_ctx, in_pkt); if (ret < 0) @@ -785,7 +837,7 @@ void AudioDevice::captureNative(const QString &api) int64_t pts = 0; bool loggedEncodeError = false; - while (!m_abort.loadRelaxed()) + while (!stopRequested()) { int got = backend->read(scratch.data(), scratch.size(), 100); if (got < 0) diff --git a/pica-client/audiodevice.h b/pica-client/audiodevice.h index c1feb8a..fde45db 100644 --- a/pica-client/audiodevice.h +++ b/pica-client/audiodevice.h @@ -52,8 +52,30 @@ public: // message carries - "opus", "adpcm_g722" or "pcm_alaw". bitrate is in bits // per second and only reaches an encoder with a rate to control: G.722 and // A-law code a fixed number of bits per sample and simply ignore it. - Q_INVOKABLE void configureCapture(QString deviceName, QString codec, int sampleRate, int bitrate); - Q_INVOKABLE void configurePlayback(QString deviceName, QString codec, int sampleRate); + // + // caller_id and callee_id name the call the loop is going to run for, and + // have to be the pair openSession() was given - see there. + Q_INVOKABLE void configureCapture(QString deviceName, QString codec, int sampleRate, int bitrate, + QByteArray caller_id, QByteArray callee_id); + Q_INVOKABLE void configurePlayback(QString deviceName, QString codec, int sampleRate, + QByteArray caller_id, QByteArray callee_id); + + // Allows Capture()/Play() to run for this call, until Close(). To be + // called directly, before the calls that configure and start the device + // are queued: a Capture()/Play() configured for a call that is no longer + // the open one returns at once, so a Close() that lands before a queued + // start has begun is not lost. Safe to call from any thread. + void openSession(QByteArray caller_id, QByteArray callee_id); + + // New playback parameters for a Play() that is already running: the peer + // may change what it sends in the middle of a call, by sending another + // 0x74. The loop closes its decoder and output device and opens them + // again for these. Safe to call from any thread, and has to be called + // directly - the device's own thread is busy inside Play(). + // + // Whatever is still waiting in the jitter buffer is dropped, since it was + // encoded with the previous parameters. + void changePlayback(QString deviceName, QString codec, int sampleRate); // Give this device the call's echo canceller. The capture direction runs // the microphone signal through it, the playback direction feeds it the @@ -63,7 +85,11 @@ public: // Null unless EchoCancellation() is EchoCancellationOwn - see // AudioVideoCallController::startAudioPipeline(), which is where that is // decided. - void setEchoCanceller(EchoCancellerPtr ec); + // + // To be invoked through the device's own thread, like configureCapture(): + // the loop of the previous call may still be on its way out and reading + // the canceller it was given. + Q_INVOKABLE void setEchoCanceller(EchoCancellerPtr ec); // Push a codec packet received from the network into the playback // jitter buffer. Safe to call from any thread. Drops the oldest queued @@ -181,7 +207,24 @@ private: // Capture direction only; see configureCapture(). int m_bitrate; - QAtomicInt m_abort; + // The call that is allowed to run, set by openSession() and Close(), and + // the one this thread's loop was configured for. + MediaCallSession m_openSession; + QByteArray m_caller_id; + QByteArray m_callee_id; + + // Set by changePlayback(), with the parameters it was given kept under + // m_queueMutex until Play() picks them up. + QAtomicInt m_reconfigure; + QString m_pendingDeviceName; + QString m_pendingCodec; + int m_pendingSampleRate; + + // The call this loop belongs to is over. + bool sessionClosed() const { return !m_openSession.isOpenFor(m_caller_id, m_callee_id); } + // What the loops check: either that, or Play() has to start over with new + // parameters. + bool stopRequested() const { return m_reconfigure.loadRelaxed() || sessionClosed(); } // Shared with the other direction of the same call, and held by shared // pointer because AudioVideoCallController tears a call down without @@ -244,8 +287,8 @@ private: // Shared by both playback paths. waitForPreroll() blocks until the jitter // buffer has a cushion or the call ends; nextPacket() pops the next - // packet, returning false once Close() has been called and nothing is - // left. A true return with an empty *out is a spurious wakeup - carry on. + // packet, returning false once the loop has to stop. A true return with an + // empty *out is a spurious wakeup - carry on. void waitForPreroll(); bool nextPacket(QByteArray *out); 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 <QByteArray> #include <QDebug> #include <QMetaObject> 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>("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); diff --git a/pica-client/audiovideocallcontroller.h b/pica-client/audiovideocallcontroller.h index 59d130b..ae1d422 100644 --- a/pica-client/audiovideocallcontroller.h +++ b/pica-client/audiovideocallcontroller.h @@ -32,7 +32,7 @@ public: explicit AudioVideoCallController(QObject *parent = nullptr); ~AudioVideoCallController(); // is call active (i.e. are voice/video packets exchanged now) - bool const isActive() {return is_active;} + bool const isActive() {return m_state == CallActive;} void processCall(); public slots: void start_call(QByteArray peer_id); @@ -41,8 +41,26 @@ public slots: void call_accepted(QByteArray peer_id); void call_rejected(QByteArray peer_id); void call_hungup(QByteArray peer_id); + // the connection to the peer is gone, and whatever call it carried with it + void peer_disconnected(QByteArray peer_id); signals: private: + // There is one call at a time. While it is anything but CallIdle, calls + // coming in from other peers are rejected and the user cannot start + // another one. + enum CallState + { + // No call. The window may still be open: before "Call" is pressed, and + // after a call that failed, was rejected or was ended by the peer. + CallIdle, + // We are calling, the peer has not answered yet. + CallDialing, + // The peer is calling, we have not answered yet. + CallRinging, + // Answered - audio/video packets are being exchanged. + CallActive + }; + CallWindow *callwindow; AudioDevice *ringdevice; AudioDevice *microphone; @@ -51,8 +69,19 @@ private: VideoDevice *cam; // Decoding of the video stream received from the peer. VideoDevice *remotevideo; - bool is_active; + CallState m_state; QByteArray m_peer_id; + // What identifies the call: who started it and who was called, one of them + // being m_peer_id and the other this account. The media devices only run + // for the call they were started for - see MediaCallSession. + QByteArray m_caller_id; + QByteArray m_callee_id; + + // Whether output/remotevideo have been started for the peer's first + // 0x74/0x75 of this call. The ones after it change the parameters of a + // decoder that is already running. + bool m_audioPlaybackStarted; + bool m_videoPlaybackStarted; // Earpiece tones (ringback, busy, special information/unreachable), // played through the "audio.playback_device" setting. @@ -110,6 +139,13 @@ private: void startVideoPipeline(); void stopVideoPipeline(); + // The one way out of a call, whichever state it is in and whoever ends it: + // stops the tones and the media devices and leaves the state CallIdle. + // With notify_peer the peer is told as well, in the way the state calls + // for - a hangup for a call we started or answered, a reject for one that + // is still ringing here. + void finishCall(bool notify_peer); + private slots: // button handlers void initiate_call(); diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp index 8462a5b..fca9794 100644 --- a/pica-client/dialogs/settingsdialog.cpp +++ b/pica-client/dialogs/settingsdialog.cpp @@ -39,6 +39,14 @@ #include <QTabWidget> #include <QTimer> +// The device tests are not part of any call, but the devices only run for an +// open call session (see MediaCallSession) - so each test is one, under a name +// no account id can take, with the dialog on both ends of it. +static QByteArray testSessionId() +{ + return QByteArrayLiteral("settings dialog device test"); +} + // Audio pipeline test: how long the microphone is recorded for. The codec and // the rate come from the "Call Settings" tab, so the test runs the same path a // call would - see toggleAudioTest(). @@ -733,9 +741,11 @@ void SettingsDialog::toggleAudioTest() const int rate = callAudioSampleRate(codec); const int bitrate = callAudioBitrateAdjustable(codec) ? callAudioBitrate->value() * 1000 : 0; + testMic->openSession(testSessionId(), testSessionId()); QMetaObject::invokeMethod(testMic, "configureCapture", Qt::QueuedConnection, Q_ARG(QString, dev), Q_ARG(QString, codec), - Q_ARG(int, rate), Q_ARG(int, bitrate)); + Q_ARG(int, rate), Q_ARG(int, bitrate), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); QMetaObject::invokeMethod(testMic, "Capture", Qt::QueuedConnection); // Only a watchdog for the device failing to open at all. The recording @@ -815,9 +825,11 @@ void SettingsDialog::startAudioTestPlayback() // call decodes with whatever the peer announced. const QString codec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); + testSpeaker->openSession(testSessionId(), testSessionId()); QMetaObject::invokeMethod(testSpeaker, "configurePlayback", Qt::QueuedConnection, Q_ARG(QString, dev), Q_ARG(QString, codec), - Q_ARG(int, callAudioSampleRate(codec))); + Q_ARG(int, callAudioSampleRate(codec)), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); QMetaObject::invokeMethod(testSpeaker, "Play", Qt::QueuedConnection); // The recording has to be handed over at the rate it plays at, not all at @@ -951,6 +963,7 @@ void SettingsDialog::toggleVideoTest() // The settings as they stand in the dialog, not as they were last stored: // the point of the test is to see what the current selections do before // committing to them. + testCam->openSession(testSessionId(), testSessionId()); QMetaObject::invokeMethod(testCam, "configureCapture", Qt::QueuedConnection, Q_ARG(QString, dev), Q_ARG(int, selectedVideoWidth()), Q_ARG(int, selectedVideoHeight()), @@ -958,7 +971,8 @@ void SettingsDialog::toggleVideoTest() Q_ARG(bool, cbPreferCompressed->isChecked()), Q_ARG(QString, callVideoCodec->itemData(callVideoCodec->currentIndex()).toString()), Q_ARG(int, callVideoBitrate->value() * 1000), - Q_ARG(int, selectedVideoEncodingAcceleration())); + Q_ARG(int, selectedVideoEncodingAcceleration()), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); QMetaObject::invokeMethod(testCam, "Capture", Qt::QueuedConnection); // The decoder is only started once the camera has settled on a format, @@ -995,11 +1009,13 @@ void SettingsDialog::videoTestCaptureStarted(QString codec, int width, int heigh vaapiRendering = cbVaapiRendering->isChecked() && !VaapiRenderWidget::renderingKnownBroken(); #endif + testDecoder->openSession(testSessionId(), testSessionId()); QMetaObject::invokeMethod(testDecoder, "configurePlayback", Qt::QueuedConnection, Q_ARG(QString, codec), Q_ARG(int, width), Q_ARG(int, height), Q_ARG(int, selectedVideoDecodingAcceleration()), - Q_ARG(bool, vaapiRendering)); + Q_ARG(bool, vaapiRendering), + Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); QMetaObject::invokeMethod(testDecoder, "Play", Qt::QueuedConnection); } diff --git a/pica-client/echocanceller.h b/pica-client/echocanceller.h index faf50dd..33e1584 100644 --- a/pica-client/echocanceller.h +++ b/pica-client/echocanceller.h @@ -21,6 +21,7 @@ #include <QMutex> #include <QVector> #include <QSharedPointer> +#include <QMetaType> struct EchoCancellerPrivate; struct SwrContext; @@ -188,5 +189,8 @@ private: }; typedef QSharedPointer<EchoCanceller> EchoCancellerPtr; +// Handed to the audio threads through their event queues, see +// AudioDevice::setEchoCanceller(). +Q_DECLARE_METATYPE(EchoCancellerPtr) #endif // ECHOCANCELLER_H diff --git a/pica-client/mediadevice.h b/pica-client/mediadevice.h index 932c8e8..432d457 100644 --- a/pica-client/mediadevice.h +++ b/pica-client/mediadevice.h @@ -4,6 +4,9 @@ #include <QString> #include <QStringList> #include <QList> +#include <QByteArray> +#include <QMutex> +#include <QMutexLocker> enum MediaDeviceStreamDirection { @@ -18,6 +21,48 @@ struct MediaDeviceInfo int index; }; +// Which call a device is currently allowed to work for. A call is identified +// by the pair of its caller's and its callee's id. +// +// The loops of AudioDevice and VideoDevice are started through their thread's +// event queue and stopped by a direct call from another thread, so the two can +// arrive in either order. A plain stop flag that the loop clears on entry +// loses a stop that came first, and the loop then runs with nobody left to +// stop it. Instead the owner opens the session before it queues the start and +// closes it to stop, and a loop only runs while the session that is open is +// the one it was configured for. All of it is safe to call from any thread. +class MediaCallSession +{ +public: + MediaCallSession() : m_open(false) {} + + void open(const QByteArray &caller_id, const QByteArray &callee_id) + { + QMutexLocker locker(&m_mutex); + m_caller_id = caller_id; + m_callee_id = callee_id; + m_open = true; + } + + void close() + { + QMutexLocker locker(&m_mutex); + m_open = false; + } + + bool isOpenFor(const QByteArray &caller_id, const QByteArray &callee_id) const + { + QMutexLocker locker(&m_mutex); + return m_open && m_caller_id == caller_id && m_callee_id == callee_id; + } + +private: + mutable QMutex m_mutex; + bool m_open; + QByteArray m_caller_id; + QByteArray m_callee_id; +}; + class MediaDevice { public: diff --git a/pica-client/skynet.cpp b/pica-client/skynet.cpp index d0a3647..9fe2ed2 100644 --- a/pica-client/skynet.cpp +++ b/pica-client/skynet.cpp @@ -882,6 +882,8 @@ void SkyNet::do_AcceptCall(QByteArray from) return; } + /* the connection the call came in on is gone */ + emit CallFailed(from, QString(tr("Failed to pickup the call: not connected"))); } void SkyNet::RejectCall(QByteArray from) @@ -899,7 +901,8 @@ void SkyNet::do_RejectCall(QByteArray from) { ret = PICA_reject_call(iptr); - if (ret != PICA_OK) + /* the caller gave up first - nothing left to reject */ + if (ret != PICA_OK && ret != PICA_ERRCALLNOTINPROGRESS) emit CallFailed(from, QString(tr("Failed to reject the call: %1")).arg(ret)); call_active_set(false, from); @@ -920,11 +923,17 @@ void SkyNet::do_HangupCall(QByteArray with) int ret = PICA_OK; struct PICA_c2c *iptr; + /* hung up while still connecting to the peer - do not start the call + once the connection is there */ + if (is_call_waiting_for(with)) + call_waiting_c2c_connect = false; + if ((iptr = find_active_chan(with))) { ret = PICA_hangup_call(iptr); - if (ret != PICA_OK) + /* the other side ended the call first - nothing left to hang up */ + if (ret != PICA_OK && ret != PICA_ERRCALLNOTINPROGRESS) emit CallFailed(with, QString(tr("Failed to hang up the call: %1")).arg(ret)); call_active_set(false, with); @@ -1033,7 +1042,10 @@ void SkyNet::do_StartCall(QByteArray to) ret = PICA_new_c2c(active_nodelink, (const unsigned char*)to.constData(), NULL, &chan); if (ret != PICA_OK) + { + call_waiting_c2c_connect = false; emit CallFailed(to, QString(tr("Failed to create the C2C connection for the call: %1")).arg(ret)); + } } bool SkyNet::is_call_waiting_for(const QByteArray &peer_id) @@ -1049,16 +1061,17 @@ void SkyNet::continue_start_call() int ret = PICA_ERRCALLNOTINPROGRESS; struct PICA_c2c *iptr; + /* The wait is over whichever way this goes. Left set, it would start a + call again every time a connection to this peer is established. */ + call_waiting_c2c_connect = false; + if ((iptr = find_active_chan(call_waiting_to))) { ret = PICA_start_call(iptr); } if (ret != PICA_OK) - { emit CallFailed(call_waiting_to, QString(tr("Failed to initiate the call: %1")).arg(ret)); - call_waiting_c2c_connect = false; - } } void SkyNet::flush_queues(QByteArray to) diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp index ac9a861..2ece29c 100644 --- a/pica-client/videodevice.cpp +++ b/pica-client/videodevice.cpp @@ -731,7 +731,9 @@ VideoDevice::VideoDevice(QObject *parent) : QObject(parent), m_width(kDefaultCaptureWidth), m_height(kDefaultCaptureHeight), m_frameRate(kDefaultCaptureFrameRate), m_bitrate(kDefaultVideoBitrateKbps * 1000), m_preferCompressed(false), - m_acceleration(0), m_useVaapiRender(false), m_abort(0), + m_acceleration(0), m_useVaapiRender(false), m_reconfigure(0), + m_pendingWidth(0), m_pendingHeight(0), m_pendingAcceleration(0), + m_pendingUseVaapiRender(false), m_maxFragmentSize(kMaxFragmentSize), m_displaySize(0), m_decoderStarted(0) { } @@ -780,8 +782,11 @@ VideoDevice::~VideoDevice() void VideoDevice::configureCapture(QString deviceName, int width, int height, int frameRate, bool preferCompressed, QString codec, int bitrate, - int acceleration) + int acceleration, + QByteArray caller_id, QByteArray callee_id) { + m_caller_id = caller_id; + m_callee_id = callee_id; m_deviceName = deviceName; m_width = width; m_height = height; @@ -793,6 +798,18 @@ void VideoDevice::configureCapture(QString deviceName, int width, int height, in } void VideoDevice::configurePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender, + QByteArray caller_id, QByteArray callee_id) +{ + m_caller_id = caller_id; + m_callee_id = callee_id; + setPlaybackParams(codec, width, height, acceleration, useVaapiRender); + // A renderer that failed during an earlier call says nothing about this + // one - it may well be a different window. + m_hwRenderDisabled.storeRelaxed(0); +} + +void VideoDevice::setPlaybackParams(const QString &codec, int width, int height, int acceleration, bool useVaapiRender) { m_codec = codec; @@ -802,14 +819,32 @@ void VideoDevice::configurePlayback(QString codec, int width, int height, // place, so asking for GPU rendering turns on VAAPI decoding regardless. m_acceleration = acceleration | (useVaapiRender ? VideoAccelerationVaapi : 0); m_useVaapiRender = useVaapiRender; - // A renderer that failed during an earlier call says nothing about this - // one - it may well be a different window. - m_hwRenderDisabled.storeRelaxed(0); // A fresh decode session, so the startup queue depth applies again until // this one's loop is consuming - see enqueueFrame(). m_decoderStarted.storeRelaxed(0); } +void VideoDevice::openSession(QByteArray caller_id, QByteArray callee_id) +{ + m_openSession.open(caller_id, callee_id); +} + +void VideoDevice::changePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender) +{ + QMutexLocker locker(&m_queueMutex); + + m_pendingCodec = codec; + m_pendingWidth = width; + m_pendingHeight = height; + m_pendingAcceleration = acceleration; + m_pendingUseVaapiRender = useVaapiRender; + m_reconfigure.storeRelaxed(1); + /* encoded with the parameters being replaced */ + m_frameQueue.clear(); + m_queueCond.wakeAll(); +} + void VideoDevice::disableHardwareRendering() { m_hwRenderDisabled.storeRelaxed(1); @@ -831,10 +866,11 @@ void VideoDevice::enqueueFrame(QByteArray encodedFrame) void VideoDevice::Close() { - m_abort.storeRelaxed(1); + m_openSession.close(); { QMutexLocker locker(&m_queueMutex); + m_reconfigure.storeRelaxed(0); m_frameQueue.clear(); } m_queueCond.wakeAll(); @@ -1150,7 +1186,9 @@ private: void VideoDevice::Capture() { - m_abort.storeRelaxed(0); + /* closed before it got to start */ + if (sessionClosed()) + return; #ifdef Q_OS_WIN // Before the camera is opened - see ComMultithreadedScope - and for the @@ -1342,7 +1380,7 @@ void VideoDevice::runPassthroughLoop(AVFormatContext *ifmt_ctx, AVStream *in_st, AVPacket *pkt = av_packet_alloc(); bool loggedReadError = false; - while (!m_abort.loadRelaxed()) + while (!stopRequested()) { int ret = av_read_frame(ifmt_ctx, pkt); if (ret < 0) @@ -1881,7 +1919,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) bool loggedScaleError = false; bool loggedEncodeError = false; - while (!m_abort.loadRelaxed()) + while (!stopRequested()) { ret = av_read_frame(ifmt_ctx, in_pkt); if (ret < 0) @@ -2028,8 +2066,31 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) void VideoDevice::Play() { - m_abort.storeRelaxed(0); + // More than one pass only when changePlayback() interrupts the one that is + // running. Also covers being closed before getting to start. + while (!sessionClosed()) + { + { + QMutexLocker locker(&m_queueMutex); + + if (m_reconfigure.loadRelaxed()) + { + setPlaybackParams(m_pendingCodec, m_pendingWidth, m_pendingHeight, + m_pendingAcceleration, m_pendingUseVaapiRender); + m_reconfigure.storeRelaxed(0); + } + } + + decode(); + + /* closed, or gave up on an error */ + if (!m_reconfigure.loadRelaxed()) + break; + } +} +void VideoDevice::decode() +{ #if LIBAVFORMAT_VERSION_MAJOR < 58 avcodec_register_all(); #endif @@ -2132,10 +2193,10 @@ void VideoDevice::Play() QByteArray frameData; { QMutexLocker locker(&m_queueMutex); - while (m_frameQueue.isEmpty() && !m_abort.loadRelaxed()) + while (m_frameQueue.isEmpty() && !stopRequested()) m_queueCond.wait(&m_queueMutex, 100); - if (m_abort.loadRelaxed()) + if (stopRequested()) break; if (m_frameQueue.isEmpty()) diff --git a/pica-client/videodevice.h b/pica-client/videodevice.h index 3119652..3193701 100644 --- a/pica-client/videodevice.h +++ b/pica-client/videodevice.h @@ -182,7 +182,24 @@ public: // decoding-only paths are ignored. Q_INVOKABLE void configureCapture(QString deviceName, int width, int height, int frameRate, bool preferCompressed, QString codec, int bitrate, - int acceleration); + int acceleration, + QByteArray caller_id, QByteArray callee_id); + + // Allows Capture()/Play() to run for the call this pair of ids names, + // until Close() - the same arrangement as AudioDevice::openSession(). To + // be called directly, before the calls that configure and start the + // device are queued; configureCapture()/configurePlayback() are then given + // the same pair. + void openSession(QByteArray caller_id, QByteArray callee_id); + + // New parameters for a Play() that is already running: the peer may change + // what it sends in the middle of a call, by sending another 0x75. The loop + // closes its decoder and opens one for these. Safe to call from any + // thread, and has to be called directly - the device's own thread is busy + // inside Play(). Frames still waiting to be decoded are dropped, since + // they were encoded with the previous parameters. + void changePlayback(QString codec, int width, int height, + int acceleration, bool useVaapiRender); // acceleration is the decoding counterpart of configureCapture()'s: the // VideoAcceleration flags for the GPU decoders that may be tried, in this @@ -198,7 +215,8 @@ public: // frames back to system memory - nothing in the client can draw a Direct3D // surface yet. Q_INVOKABLE void configurePlayback(QString codec, int width, int height, - int acceleration, bool useVaapiRender); + int acceleration, bool useVaapiRender, + QByteArray caller_id, QByteArray callee_id); // Push one complete encoded frame (already reassembled from 0x77 // fragments by the caller) into the decode queue. Safe to call from any @@ -343,7 +361,32 @@ private: int m_acceleration; bool m_useVaapiRender; - QAtomicInt m_abort; + // The call that is allowed to run, set by openSession() and Close(), and + // the one this thread's loop was configured for. + MediaCallSession m_openSession; + QByteArray m_caller_id; + QByteArray m_callee_id; + + // Set by changePlayback(), with the parameters it was given kept under + // m_queueMutex until Play() picks them up. + QAtomicInt m_reconfigure; + QString m_pendingCodec; + int m_pendingWidth; + int m_pendingHeight; + int m_pendingAcceleration; + bool m_pendingUseVaapiRender; + + // The call this loop belongs to is over. + bool sessionClosed() const { return !m_openSession.isOpenFor(m_caller_id, m_callee_id); } + // What the loops check: either that, or Play() has to start over with new + // parameters. + bool stopRequested() const { return m_reconfigure.loadRelaxed() || sessionClosed(); } + + void setPlaybackParams(const QString &codec, int width, int height, + int acceleration, bool useVaapiRender); + // One pass of Play(): opens a decoder for the current parameters and + // decodes until stopRequested(). + void decode(); // Set from another thread by disableHardwareRendering() while the decode // loop is running, so it has to be read atomically rather than as a plain // bool like the settings above, which are fixed before the loop starts. |
