summaryrefslogtreecommitdiff
path: root/src/UdpHubListener.h
blob: 58f07372abba9df330066503919b5de86f9ed5ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//*****************************************************************
/*
  JackTrip: A System for High-Quality Audio Network Performance
  over the Internet

  Copyright (c) 2008-2021 Juan-Pablo Caceres, Chris Chafe.
  SoundWIRE group at CCRMA, Stanford University.

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*/
//*****************************************************************

/**
 * \file UdpHubListener.h
 * \author Juan-Pablo Caceres and Chris Chafe
 * \date September 2008
 */

#ifndef __UDPHUBLISTENER_H__
#define __UDPHUBLISTENER_H__

#include <QHostAddress>
#include <QMutex>
#include <QThread>
#include <QThreadPool>
#include <QUdpSocket>
#include <fstream>
#include <iostream>
#include <stdexcept>

#include "JackTrip.h"
#include "jacktrip_globals.h"
#include "jacktrip_types.h"
#ifndef NO_JACK
#include "Patcher.h"
#endif
#include "Auth.h"
#include "SslServer.h"

class JackTripWorker;  // forward declaration
class Settings;

/** \brief Hub UDP listener on the Server.
 *
 * This creates a server that will listen on the well know port (the server port) and will
 * spawn JackTrip threads into the Thread pool. Clients request a connection.
 */
class UdpHubListener : public QObject
{
    Q_OBJECT;

   public:
    UdpHubListener(int server_port = gServerUdpPort, int server_udp_port = 0,
                   QObject* parent = nullptr);
    virtual ~UdpHubListener();

    /// \brief Starts the TCP server
    void start();

    /// \brief Stops the execution of the Thread
    void stop() { mStopped = true; }

#ifndef NO_JACK
    void registerClientWithPatcher(QString& clientName);
    void unregisterClientWithPatcher(QString& clientName);
#endif
    int releaseThread(int id);
    void releaseDuplicateThreads(JackTripWorker* worker, uint16_t actual_peer_port);

    void setConnectDefaultAudioPorts(bool connectDefaultAudioPorts)
    {
        // Only allow us to override this in the default patching mode. (Or TUB mode.)
        //(Allows -D to continue to function as a synonym for -p5.)
        if (mHubPatch == JackTrip::SERVERTOCLIENT
            || mHubPatch == JackTrip::RESERVEDMATRIX) {
            m_connectDefaultAudioPorts = connectDefaultAudioPorts;
        }
    }

    static void sigIntHandler([[maybe_unused]] int unused)
    {
        std::cout << std::endl << "Shutting Down..." << std::endl;
        sSigInt = true;
    }

   private slots:
    void testReceive()
    {
        std::cout << "========= TEST RECEIVE SLOT ===========" << std::endl;
    }
    void receivedNewConnection();
    void stopCheck();

   signals:
    void Listening();
    void ClientAddressSet();
    void signalRemoveThread(int id);
    void signalStopped();
    void signalError(const QString& errorMessage);

   private:
    /** \brief Binds a QUdpSocket. It chooses the available (active) interface.
     * \param udpsocket a QUdpSocket
     * \param port Port number
     */
    void receivedClientInfo(QSslSocket* clientConnection);

    static void bindUdpSocket(QUdpSocket& udpsocket, int port);

    int readClientUdpPort(QSslSocket* clientConnection, QString& clientName);
    int checkAuthAndReadPort(QSslSocket* clientConnection, QString& clientName);
    int sendUdpPort(QSslSocket* clientConnection, qint32 udp_port);

    /**
     * \brief Send the JackTripWorker to the thread pool. This will run
     * until it's done. We still have control over the prototype class.
     * \param id Identification Number
     */
    // void sendToPoolPrototype(int id);

    /**
     * \brief Check if address is already handled and reuse or create
     * a JackTripWorker as appropriate
     * \param address as string (IPv4 or IPv6)
     * \return id number of JackTripWorker
     */
    int getJackTripWorker(const QString& address, uint16_t port, QString& clientName);

    /** \brief Returns the ID of the client in the pool. If the client
     * is not in the pool yet, returns -1.
     */
    int getPoolID(const QString& address, uint16_t port);

    void stopAllThreads();

    // QUdpSocket mUdpHubSocket; ///< The UDP socket
    // QHostAddress mPeerAddress; ///< The Peer Address

    // JackTripWorker* mJTWorker; ///< Class that will be used as prototype
    QVector<JackTripWorker*>* mJTWorkers;  ///< Vector of JackTripWorkers

    SslServer mTcpServer;
    int mServerPort;     //< Server known port number
    int mServerUdpPort;  //< Server udp base port number
    int mBasePort;
    // addressPortNameTriple mActiveAddress[gMaxThreads]; ///< Active address pool
    // addresses QHash<QString, uint16_t> mActiveAddressPortPair;

    bool mRequireAuth;
    QString mCertFile;
    QString mKeyFile;
    QString mCredsFile;
    QScopedPointer<Auth> mAuth;

    /// Boolean stop the execution of the thread
    volatile bool mStopped;
    static bool sSigInt;
    QTimer mStopCheckTimer;
    int mTotalRunningThreads;  ///< Number of Threads running in the pool
    QMutex mMutex;
    JackTrip::underrunModeT mUnderRunMode;
    AudioInterface::audioBitResolutionT mAudioBitResolution;
    int mBufferQueueLength;

    QStringList mHubPatchDescriptions;
    bool m_connectDefaultAudioPorts;
#ifndef NO_JACK
    Patcher mPatcher;
#endif
    bool mStereoUpmix;

    int mIOStatTimeout;
    QSharedPointer<std::ostream> mIOStatStream;

    int mBufferStrategy;
    int mBroadcastQueue;
    double mSimulatedLossRate;
    double mSimulatedJitterRate;
    double mSimulatedDelayRel;
    bool mUseRtUdpPriority;

#ifdef WAIR  // wair
    bool mWAIR;
    void connectMesh(bool spawn);
    void enumerateRunningThreadIDs();

   public:
    void setWAIR(int b) { mWAIR = b; }
    bool isWAIR() { return mWAIR; }
#endif  // endwhere
#ifndef NO_JACK
    void connectPatch(bool spawn, const QString& clientName);
#endif

   public:
    void setRequireAuth(bool requireAuth) { mRequireAuth = requireAuth; }
    void setCertFile(const QString& certFile) { mCertFile = certFile; }
    void setKeyFile(const QString& keyFile) { mKeyFile = keyFile; }
    void setCredsFile(const QString& credsFile) { mCredsFile = credsFile; }

    unsigned int mHubPatch;
    void setHubPatch(unsigned int p)
    {
        mHubPatch = p;
#ifndef NO_JACK
        mPatcher.setPatchMode(static_cast<JackTrip::hubConnectionModeT>(p));
#endif
        // Set the correct audio port connection setting for our chosen patch mode.
        if (mHubPatch == JackTrip::SERVERTOCLIENT || mHubPatch == JackTrip::SERVFOFI
            || mHubPatch == JackTrip::SERVFULLMIX) {
            m_connectDefaultAudioPorts = true;
        } else {
            m_connectDefaultAudioPorts = false;
        }
    }
    unsigned int getHubPatch() { return mHubPatch; }

    void setStereoUpmix([[maybe_unused]] bool upmix)
    {
#ifndef NO_JACK
        mPatcher.setStereoUpmix(upmix);
#endif
    }

    void setUnderRunMode(JackTrip::underrunModeT UnderRunMode)
    {
        mUnderRunMode = UnderRunMode;
    }
    void setAudioBitResolution(AudioInterface::audioBitResolutionT AudioBitResolution)
    {
        mAudioBitResolution = AudioBitResolution;
    }
    void setBufferQueueLength(int BufferQueueLength)
    {
        mBufferQueueLength = BufferQueueLength;
    }

    void setIOStatTimeout(int timeout) { mIOStatTimeout = timeout; }
    void setIOStatStream(QSharedPointer<std::ostream> statStream)
    {
        mIOStatStream = statStream;
    }

    void setBufferStrategy(int BufferStrategy) { mBufferStrategy = BufferStrategy; }
    void setNetIssuesSimulation(double loss, double jitter, double delay_rel)
    {
        mSimulatedLossRate   = loss;
        mSimulatedJitterRate = jitter;
        mSimulatedDelayRel   = delay_rel;
    }
    void setBroadcast(int broadcast_queue) { mBroadcastQueue = broadcast_queue; }
    void setUseRtUdpPriority(bool use) { mUseRtUdpPriority = use; }
    bool mAppendThreadID = false;
};

#endif  //__UDPHUBLISTENER_H__