1 //*****************************************************************
2 /*
3   JackTrip: A System for High-Quality Audio Network Performance
4   over the Internet
5 
6   Copyright (c) 2008 Juan-Pablo Caceres, Chris Chafe.
7   SoundWIRE group at CCRMA, Stanford University.
8 
9   Permission is hereby granted, free of charge, to any person
10   obtaining a copy of this software and associated documentation
11   files (the "Software"), to deal in the Software without
12   restriction, including without limitation the rights to use,
13   copy, modify, merge, publish, distribute, sublicense, and/or sell
14   copies of the Software, and to permit persons to whom the
15   Software is furnished to do so, subject to the following
16   conditions:
17 
18   The above copyright notice and this permission notice shall be
19   included in all copies or substantial portions of the Software.
20 
21   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
23   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
25   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
26   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
28   OTHER DEALINGS IN THE SOFTWARE.
29 */
30 //*****************************************************************
31 
32 /**
33  * \file JackTrip.h
34  * \author Juan-Pablo Caceres
35  * \date July 2008
36  */
37 
38 #ifndef __JACKTRIP_H__
39 #define __JACKTRIP_H__
40 
41 //#include <tr1/memory> //for shared_ptr
42 #include <stdexcept>
43 
44 #include <QObject>
45 #include <QString>
46 #include <QUdpSocket>
47 #include <QTcpSocket>
48 #include <QTimer>
49 #include <QSharedPointer>
50 
51 #include "DataProtocol.h"
52 #include "AudioInterface.h"
53 
54 #ifndef __NO_JACK__
55 #include "JackAudioInterface.h"
56 #endif //__NO_JACK__
57 
58 #include "PacketHeader.h"
59 #include "RingBuffer.h"
60 #include "AudioTester.h"
61 
62 //#include <signal.h>
63 /** \brief Main class to creates a SERVER (to listen) or a CLIENT (to connect
64  * to a listening server) to send audio streams in the network.
65  *
66  * All audio and network settings can be set in this class.
67  * This class also acts as a Mediator between all the other class.
68  * Classes that uses JackTrip methods need to register with it.
69  */
70 
71 class JackTrip : public QObject
72 {
73     Q_OBJECT;
74 
75 public:
76 
77     //----------ENUMS------------------------------------------
78     /// \brief Enum for the data Protocol. At this time only UDP is implemented
79     enum dataProtocolT {
80         UDP, ///< Use UDP (User Datagram Protocol)
81         TCP, ///< <B>NOT IMPLEMENTED</B>: Use TCP (Transmission Control Protocol)
82         SCTP ///< <B>NOT IMPLEMENTED</B>: Use SCTP (Stream Control Transmission Protocol)
83     };
84 
85     /// \brief Enum for the JackTrip mode
86     enum jacktripModeT {
87         SERVER, ///< Run in P2P Server Mode
88         CLIENT,  ///< Run in P2P Client Mode
89         CLIENTTOPINGSERVER, ///< Client of the Ping Server Mode
90         SERVERPINGSERVER ///< Server of the MultiThreaded JackTrip
91     };
92 
93     /// \brief Enum for the JackTrip Underrun Mode, when packets
94     enum underrunModeT {
95         WAVETABLE, ///< Loops on the last received packet
96         ZEROS  ///< Set new buffers to zero if there are no new ones
97     };
98 
99     /// \brief Enum for Audio Interface Mode
100     enum audiointerfaceModeT {
101         JACK, ///< Jack Mode
102         RTAUDIO  ///< RtAudio Mode
103     };
104 
105     /// \brief Enum for Connection Mode (in packet header)
106     enum connectionModeT {
107         NORMAL, ///< Normal Mode
108         KSTRONG,  ///< Karplus Strong
109         JAMTEST  ///< Karplus Strong
110     };
111 
112     /// \brief Enum for Hub Server Audio Connection Mode (connections to hub server are automatically patched in Jack)
113     enum hubConnectionModeT {
114         SERVERTOCLIENT, ///< Normal Mode, Sever to All Clients (but not client to any client)
115         CLIENTECHO,  ///< Client Echo (client self-to-self)
116         CLIENTFOFI,  ///< Client Fan Out to Clients and Fan In from Clients (but not self-to-self)
117         RESERVEDMATRIX,  ///< Reserved for custom patch matrix (for TUB ensemble)
118         FULLMIX,  ///< Client Fan Out to Clients and Fan In from Clients (including self-to-self)
119         NOAUTO  ///< No automatic patching
120     };
121     //---------------------------------------------------------
122 
123 
124     /** \brief The class Constructor with Default Parameters
125    * \param JacktripMode JackTrip::CLIENT or JackTrip::SERVER
126    * \param DataProtocolType JackTrip::dataProtocolT
127    * \param NumChans Number of Audio Channels (same for inputs and outputs)
128    * \param BufferQueueLength Audio Buffer for receiving packets
129    * \param AudioBitResolution Audio Sample Resolutions in bits
130    * \param redundancy redundancy factor for network data
131    */
132     JackTrip(jacktripModeT JacktripMode = CLIENT,
133              dataProtocolT DataProtocolType = UDP,
134              int NumChans = gDefaultNumInChannels,
135          #ifdef WAIR // wair
136              int NumNetRevChans = 0,
137          #endif // endwhere
138              int BufferQueueLength = gDefaultQueueLength,
139              unsigned int redundancy = gDefaultRedundancy,
140              AudioInterface::audioBitResolutionT AudioBitResolution =
141              AudioInterface::BIT16,
142              DataProtocol::packetHeaderTypeT PacketHeaderType =
143              DataProtocol::DEFAULT,
144              underrunModeT UnderRunMode = WAVETABLE,
145              int receiver_bind_port = gDefaultPort,
146              int sender_bind_port = gDefaultPort,
147              int receiver_peer_port = gDefaultPort,
148              int sender_peer_port = gDefaultPort,
149              int tcp_peer_port = gDefaultPort);
150 
151     /// \brief The class destructor
152     virtual ~JackTrip();
153 
sigIntHandler(int unused)154     static void sigIntHandler(__attribute__((unused)) int unused)
155     { std::cout << std::endl << "Shutting Down..." << std::endl; sSigInt = true; }
156     static bool sSigInt;
157     static bool sJackStopped;
158 
159     /// \brief Starting point for the thread
160     /*virtual void run() {
161         if (gVerboseFlag) std::cout << "Settings:startJackTrip before mJackTrip->run" << std::endl;
162     }*/
163 
164     /// \brief Set the Peer Address for jacktripModeT::CLIENT mode only
165     virtual void setPeerAddress(QString PeerHostOrIP);
166 
167     /** \brief Append a process plugin. Processes will be appended in order
168    * \param plugin Pointer to ProcessPlugin Class
169    */
170     //void appendProcessPlugin(const std::tr1::shared_ptr<ProcessPlugin> plugin);
171     virtual void appendProcessPluginToNetwork(ProcessPlugin* plugin);
172     virtual void appendProcessPluginFromNetwork(ProcessPlugin* plugin);
173 
174     /// \brief Start the processing threads
175     virtual void startProcess(
176         #ifdef WAIRTOHUB // wair
177             int ID
178         #endif // endwhere
179             );
180     virtual void completeConnection();
181 
182     /// \brief Stop the processing threads
183     virtual void stop(QString errorMessage = "");
184 
185     /// \brief Wait for all the threads to finish. This functions is used when JackTrip is
186     /// run as a thread
187     virtual void waitThreads();
188 
189     /// \brief Check if UDP port is already binded
190     /// \param port Port number
191     virtual void checkIfPortIsBinded(int port);
192 
193     //------------------------------------------------------------------------------------
194     /// \name Getters and Setters Methods to change parameters after construction
195     //@{
196     //
197     /// \brief Sets (override) JackTrip Mode after construction
setJackTripMode(jacktripModeT JacktripMode)198     virtual void setJackTripMode(jacktripModeT JacktripMode)
199     { mJackTripMode = JacktripMode; }
200     /// \brief Sets (override) DataProtocol Type after construction
setDataProtocoType(dataProtocolT DataProtocolType)201     virtual void setDataProtocoType(dataProtocolT DataProtocolType)
202     { mDataProtocol = DataProtocolType; }
203     /// \brief Sets the Packet header type
setPacketHeaderType(DataProtocol::packetHeaderTypeT PacketHeaderType)204     virtual void setPacketHeaderType(DataProtocol::packetHeaderTypeT PacketHeaderType)
205     {
206         mPacketHeaderType = PacketHeaderType;
207         delete mPacketHeader;
208         mPacketHeader = NULL;
209         createHeader(mPacketHeaderType);
210     }
211     /// \brief Sets (override) Buffer Queue Length Mode after construction
setBufferQueueLength(int BufferQueueLength)212     virtual void setBufferQueueLength(int BufferQueueLength)
213     { mBufferQueueLength = BufferQueueLength; }
setBufferStrategy(int BufferStrategy)214     virtual void setBufferStrategy(int BufferStrategy)
215     { mBufferStrategy = BufferStrategy; }
216     /// \brief Sets (override) Audio Bit Resolution after construction
setAudioBitResolution(AudioInterface::audioBitResolutionT AudioBitResolution)217     virtual void setAudioBitResolution(AudioInterface::audioBitResolutionT AudioBitResolution)
218     { mAudioBitResolution = AudioBitResolution; }
219     /// \brief Sets (override) Underrun Mode
setUnderRunMode(underrunModeT UnderRunMode)220     virtual void setUnderRunMode(underrunModeT UnderRunMode)
221     { mUnderRunMode = UnderRunMode; }
222     /// \brief Sets whether to quit on timeout.
setStopOnTimeout(bool stopOnTimeout)223     virtual void setStopOnTimeout(bool stopOnTimeout)
224     { mStopOnTimeout = stopOnTimeout; }
225     /// \brief Sets port numbers for the local and peer machine.
226     /// Receive port is <tt>port</tt>
setAllPorts(int port)227     virtual void setAllPorts(int port)
228     {
229         mReceiverBindPort = port;
230         mSenderPeerPort = port;
231         mSenderBindPort = port;
232         mReceiverPeerPort = port;
233     }
234     /// \brief Sets port numbers to bind in RECEIVER and SENDER sockets.
setBindPorts(int port)235     void setBindPorts(int port)
236     {
237         mReceiverBindPort = port;
238         mSenderBindPort = port;
239     }
240     /// \brief Sets port numbers for the peer (remote) machine.
setPeerPorts(int port)241     void setPeerPorts(int port)
242     {
243         mSenderPeerPort = port;
244         mReceiverPeerPort = port;
245     }
246     /// \brief Set Client Name to something different that the default (JackTrip)
setClientName(QString clientName)247     virtual void setClientName(QString clientName)
248     { mJackClientName = clientName; }
setRemoteClientName(QString remoteClientName)249     virtual void setRemoteClientName(QString remoteClientName)
250     { mRemoteClientName = remoteClientName; }
251     /// \brief Set the number of audio channels
setNumChannels(int num_chans)252     virtual void setNumChannels(int num_chans)
253     { mNumChans = num_chans; }
254 
setIOStatTimeout(int timeout)255     virtual void setIOStatTimeout(int timeout) { mIOStatTimeout = timeout; }
setIOStatStream(QSharedPointer<std::ofstream> statStream)256     virtual void setIOStatStream(QSharedPointer<std::ofstream> statStream) { mIOStatStream = statStream; }
257 
258     /// Set to connect or not default audio ports (only implemented in Jack)
setConnectDefaultAudioPorts(bool connect)259     virtual void setConnectDefaultAudioPorts(bool connect)
260     {mConnectDefaultAudioPorts = connect;}
261 
getReceiverBindPort()262     virtual int getReceiverBindPort() const
263     { return mReceiverBindPort; }
getSenderPeerPort()264     virtual int getSenderPeerPort() const
265     { return mSenderPeerPort; }
getSenderBindPort()266     virtual int getSenderBindPort() const
267     { return mSenderBindPort; }
getReceiverPeerPort()268     virtual int getReceiverPeerPort() const
269     { return mReceiverPeerPort; }
270 
getDataProtocolSender()271     virtual DataProtocol* getDataProtocolSender() const
272     { return mDataProtocolSender; }
getDataProtocolReceiver()273     virtual DataProtocol* getDataProtocolReceiver() const
274     { return mDataProtocolReceiver; }
setDataProtocolSender(DataProtocol * const DataProtocolSender)275     virtual void setDataProtocolSender(DataProtocol* const DataProtocolSender)
276     { mDataProtocolSender = DataProtocolSender; }
setDataProtocolReceiver(DataProtocol * const DataProtocolReceiver)277     virtual void setDataProtocolReceiver(DataProtocol* const DataProtocolReceiver)
278     { mDataProtocolReceiver = DataProtocolReceiver; }
279 
getSendRingBuffer()280     virtual RingBuffer* getSendRingBuffer() const
281     { return mSendRingBuffer; }
getReceiveRingBuffer()282     virtual RingBuffer* getReceiveRingBuffer() const
283     { return mReceiveRingBuffer; }
setSendRingBuffer(RingBuffer * const SendRingBuffer)284     virtual void setSendRingBuffer(RingBuffer* const SendRingBuffer)
285     { mSendRingBuffer = SendRingBuffer; }
setReceiveRingBuffer(RingBuffer * const ReceiveRingBuffer)286     virtual void setReceiveRingBuffer(RingBuffer* const ReceiveRingBuffer)
287     { mReceiveRingBuffer = ReceiveRingBuffer; }
288 
setPacketHeader(PacketHeader * const PacketHeader)289     virtual void setPacketHeader(PacketHeader* const PacketHeader)
290     { mPacketHeader = PacketHeader; }
291 
getRingBuffersSlotSize()292     virtual int getRingBuffersSlotSize()
293     { return getTotalAudioPacketSizeInBytes(); }
294 
setAudiointerfaceMode(JackTrip::audiointerfaceModeT audiointerface_mode)295     virtual void setAudiointerfaceMode(JackTrip::audiointerfaceModeT audiointerface_mode)
296     { mAudiointerfaceMode = audiointerface_mode; }
setAudioInterface(AudioInterface * const AudioInterface)297     virtual void setAudioInterface(AudioInterface* const AudioInterface)
298     { mAudioInterface = AudioInterface; }
setLoopBack(bool b)299     virtual void setLoopBack(bool b)
300     { mLoopBack = b; }
setAudioTesterP(AudioTester * atp)301     virtual void setAudioTesterP(AudioTester* atp) { mAudioTesterP = atp; }
302 
setSampleRate(uint32_t sample_rate)303     void setSampleRate(uint32_t sample_rate)
304     { mSampleRate = sample_rate; }
setDeviceID(uint32_t device_id)305     void setDeviceID(uint32_t device_id)
306     { mDeviceID = device_id; }
setAudioBufferSizeInSamples(uint32_t buf_size)307     void setAudioBufferSizeInSamples(uint32_t buf_size)
308     { mAudioBufferSize = buf_size; }
309 
310 
getConnectionMode()311     JackTrip::connectionModeT getConnectionMode() const
312     { return mConnectionMode; }
setConnectionMode(JackTrip::connectionModeT connection_mode)313     void setConnectionMode(JackTrip::connectionModeT connection_mode)
314     { mConnectionMode = connection_mode; }
315 
getHubConnectionModeT()316     JackTrip::hubConnectionModeT getHubConnectionModeT() const
317     { return mHubConnectionModeT; }
setHubConnectionModeT(JackTrip::hubConnectionModeT connection_mode)318     void setHubConnectionModeT(JackTrip::hubConnectionModeT connection_mode)
319     { mHubConnectionModeT = connection_mode; }
320 
getJackTripMode()321     JackTrip::jacktripModeT getJackTripMode() const
322     { return mJackTripMode; }
323 
getPeerAddress()324     QString getPeerAddress() const
325     { return mPeerAddress; }
326 
receivedConnectionFromPeer()327     bool receivedConnectionFromPeer()
328     { return mReceivedConnection; }
329 
tcpConnectionError()330     bool tcpConnectionError()
331     { return mTcpConnectionError; }
332 
333     //@}
334     //------------------------------------------------------------------------------------
335 
336 
337     //------------------------------------------------------------------------------------
338     /// \name Mediator Functions
339     //@{
340     /// \todo Document all these functions
341     virtual void createHeader(const DataProtocol::packetHeaderTypeT headertype);
342     void putHeaderInPacket(int8_t* full_packet, int8_t* audio_packet);
343     virtual int getPacketSizeInBytes();
344     void parseAudioPacket(int8_t* full_packet, int8_t* audio_packet);
sendNetworkPacket(const int8_t * ptrToSlot)345     virtual void sendNetworkPacket(const int8_t* ptrToSlot)
346     { mSendRingBuffer->insertSlotNonBlocking(ptrToSlot, 0, 0); }
receiveBroadcastPacket(int8_t * ptrToReadSlot)347     virtual void receiveBroadcastPacket(int8_t* ptrToReadSlot)
348     { mReceiveRingBuffer->readBroadcastSlot(ptrToReadSlot); }
receiveNetworkPacket(int8_t * ptrToReadSlot)349     virtual void receiveNetworkPacket(int8_t* ptrToReadSlot)
350     { mReceiveRingBuffer->readSlotNonBlocking(ptrToReadSlot); }
readAudioBuffer(int8_t * ptrToReadSlot)351     virtual void readAudioBuffer(int8_t* ptrToReadSlot)
352     { mSendRingBuffer->readSlotBlocking(ptrToReadSlot); }
writeAudioBuffer(const int8_t * ptrToSlot,int len,int lostLen)353     virtual bool writeAudioBuffer(const int8_t* ptrToSlot, int len, int lostLen)
354     { return mReceiveRingBuffer->insertSlotNonBlocking(ptrToSlot, len, lostLen); }
getBufferSizeInSamples()355     uint32_t getBufferSizeInSamples() const
356     { return mAudioBufferSize; /*return mAudioInterface->getBufferSizeInSamples();*/ }
getDeviceID()357     uint32_t getDeviceID() const
358     { return mDeviceID; /*return mAudioInterface->mDeviceID();*/ }
359 
getSampleRateType()360     AudioInterface::samplingRateT getSampleRateType() const
361     { return mAudioInterface->getSampleRateType(); }
getSampleRate()362     int getSampleRate() const
363     { return mSampleRate; /*return mAudioInterface->getSampleRate();*/ }
364 
getAudioBitResolution()365     uint8_t getAudioBitResolution() const
366     { return mAudioBitResolution*8; /*return mAudioInterface->getAudioBitResolution();*/ }
getNumInputChannels()367     unsigned int getNumInputChannels() const
368     { return mNumChans; /*return mAudioInterface->getNumInputChannels();*/ }
getNumOutputChannels()369     unsigned int getNumOutputChannels() const
370     { return mNumChans; /*return mAudioInterface->getNumOutputChannels();*/ }
getNumChannels()371     unsigned int getNumChannels() const
372     {
373         if (getNumInputChannels() == getNumOutputChannels())
374         { return getNumInputChannels(); }
375         else { return 0; }
376     }
377     virtual void checkPeerSettings(int8_t* full_packet);
increaseSequenceNumber()378     void increaseSequenceNumber()
379     { mPacketHeader->increaseSequenceNumber(); }
getSequenceNumber()380     int getSequenceNumber() const
381     { return mPacketHeader->getSequenceNumber(); }
382 
getPeerTimeStamp(int8_t * full_packet)383     uint64_t getPeerTimeStamp(int8_t* full_packet) const
384     { return mPacketHeader->getPeerTimeStamp(full_packet); }
385 
getPeerSequenceNumber(int8_t * full_packet)386     uint16_t getPeerSequenceNumber(int8_t* full_packet) const
387     { return mPacketHeader->getPeerSequenceNumber(full_packet); }
388 
getPeerBufferSize(int8_t * full_packet)389     uint16_t getPeerBufferSize(int8_t* full_packet) const
390     { return mPacketHeader->getPeerBufferSize(full_packet); }
391 
getPeerSamplingRate(int8_t * full_packet)392     uint8_t getPeerSamplingRate(int8_t* full_packet) const
393     { return mPacketHeader->getPeerSamplingRate(full_packet); }
394 
getPeerBitResolution(int8_t * full_packet)395     uint8_t getPeerBitResolution(int8_t* full_packet) const
396     { return mPacketHeader->getPeerBitResolution(full_packet); }
397 
getPeerNumChannels(int8_t * full_packet)398     uint8_t  getPeerNumChannels(int8_t* full_packet) const
399     { return mPacketHeader->getPeerNumChannels(full_packet); }
400 
getPeerConnectionMode(int8_t * full_packet)401     uint8_t  getPeerConnectionMode(int8_t* full_packet) const
402     { return mPacketHeader->getPeerConnectionMode(full_packet); }
403 
getSizeInBytesPerChannel()404     size_t getSizeInBytesPerChannel() const
405     { return mAudioInterface->getSizeInBytesPerChannel(); }
getHeaderSizeInBytes()406     int getHeaderSizeInBytes() const
407     { return mPacketHeader->getHeaderSizeInBytes(); }
getTotalAudioPacketSizeInBytes()408     virtual int getTotalAudioPacketSizeInBytes() const
409     {
410 #ifdef WAIR // WAIR
411         if (mNumNetRevChans)
412             return mAudioInterface->getSizeInBytesPerChannel() * mNumNetRevChans;
413         else // not wair
414 #endif // endwhere
415             return mAudioInterface->getSizeInBytesPerChannel() * mNumChans;
416     }
417     //@}
418     //------------------------------------------------------------------------------------
419 
printTextTest()420     void printTextTest() {std::cout << "=== JackTrip PRINT ===" << std::endl;}
printTextTest2()421     void printTextTest2() {std::cout << "=== JackTrip PRINT2 ===" << std::endl;}
422 
setNetIssuesSimulation(double loss,double jitter,double delay_rel)423     void setNetIssuesSimulation(double loss, double jitter, double delay_rel)
424     {
425         mSimulatedLossRate = loss;
426         mSimulatedJitterRate = jitter;
427         mSimulatedDelayRel = delay_rel;
428     }
setBroadcast(int broadcast_queue)429     void setBroadcast(int broadcast_queue) {mBroadcastQueueLength = broadcast_queue;}
setUseRtUdpPriority(bool use)430     void setUseRtUdpPriority(bool use) {mUseRtUdpPriority = use;}
431 
432 public slots:
433     /// \brief Slot to stop all the processes and threads
slotStopProcesses()434     virtual void slotStopProcesses()
435     { this->stop(); }
slotStopProcessesDueToError(const QString & errorMessage)436     virtual void slotStopProcessesDueToError(const QString &errorMessage)
437     { this->stop(errorMessage); }
438 
439     /** \brief This slot emits in turn the signal signalNoUdpPacketsForSeconds
440    * when UDP has waited for more than 30 seconds.
441    *
442    * It is used to remove the thread from the server.
443    */
slotUdpWaitingTooLongClientGoneProbably(int wait_msec)444     void slotUdpWaitingTooLongClientGoneProbably(int wait_msec)
445     {
446         int wait_time = 10000; // msec
447         if ( !(wait_msec%wait_time) ) {
448             std::cerr << "UDP WAITED MORE THAN 10 seconds." << std::endl;
449             if (mStopOnTimeout) {
450                 stop("No network data received for 10 seconds");
451             }
452             emit signalNoUdpPacketsForSeconds();
453         }
454     }
slotUdpWaitingTooLong()455     void slotUdpWaitingTooLong()
456     { emit signalUdpWaitingTooLong(); }
slotPrintTest()457     void slotPrintTest()
458     { std::cout << "=== TESTING ===" << std::endl; }
slotReceivedConnectionFromPeer()459     void slotReceivedConnectionFromPeer()
460     { mReceivedConnection = true; emit signalReceivedConnectionFromPeer(); }
461     void onStatTimer();
462 
463 private slots:
464     void receivedConnectionTCP();
465     void receivedDataTCP();
466     void receivedDataUDP();
467     void udpTimerTick();
468     void tcpTimerTick();
469 
470 signals:
471     //void signalUdpTimeOut();
472     /// \brief Signal emitted when all the processes and threads are stopped
473     void signalProcessesStopped();
474     /// \brief Signal emitted when no UDP Packets have been received for a while
475     void signalNoUdpPacketsForSeconds();
476     void signalTcpClientConnected();
477     void signalError(const QString &errorMessage);
478     void signalReceivedConnectionFromPeer();
479     void signalUdpWaitingTooLong();
480 
481 public:
482 
483     /// \brief Set the AudioInteface object
484     virtual void setupAudio(
485         #ifdef WAIRTOHUB // WAIR
486             int ID
487         #endif // endwhere
488             );
489     /// \brief Close the JackAudioInteface and disconnects it from JACK
490     void closeAudio();
491     /// \brief Set the DataProtocol objects
492     virtual void setupDataProtocol();
493     /// \brief Set the RingBuffer objects
494     void setupRingBuffers();
495     /// \brief Starts for the CLIENT mode
496     void clientStart();
497     /// \brief Starts for the SERVER mode
498     /// \param timout Set the server to timeout after 2 seconds if no client connections are received.
499     /// Usefull for the multithreaded server
500     /// \return 0 on success, -1 on error
501     int serverStart(bool timeout = false, int udpTimeout = gTimeOutMultiThreadedServer);
502     /// \brief Stats for the Client to Ping Server
503     /// \return -1 on error, 0 on success
504     virtual int clientPingToServerStart();
505 
506 private:
507     //void bindReceiveSocket(QUdpSocket& UdpSocket, int bind_port,
508     //                       QHostAddress PeerHostAddress, int peer_port)
509     //throw(std::runtime_error);
510 
511 
512     jacktripModeT mJackTripMode; ///< JackTrip::jacktripModeT
513     dataProtocolT mDataProtocol; ///< Data Protocol Tipe
514     DataProtocol::packetHeaderTypeT mPacketHeaderType; ///< Packet Header Type
515     JackTrip::audiointerfaceModeT mAudiointerfaceMode;
516 
517     int mNumChans; ///< Number of Channels (inputs = outputs)
518 #ifdef WAIR // WAIR
519     int mNumNetRevChans; ///< Number of Network Audio Channels (net comb filters)
520 #endif // endwhere
521     int mBufferQueueLength; ///< Audio Buffer from network queue length
522     int mBufferStrategy;
523     int mBroadcastQueueLength;
524     uint32_t mSampleRate; ///< Sample Rate
525     uint32_t mDeviceID; ///< RTAudio DeviceID
526     uint32_t mAudioBufferSize; ///< Audio buffer size to process on each callback
527     AudioInterface::audioBitResolutionT mAudioBitResolution; ///< Audio Bit Resolutions
528     bool mLoopBack;
529     QString mPeerAddress; ///< Peer Address to use in jacktripModeT::CLIENT Mode
530 
531     /// Pointer to Abstract Type DataProtocol that sends packets
532     DataProtocol* mDataProtocolSender;
533     /// Pointer to Abstract Type DataProtocol that receives packets
534     DataProtocol* mDataProtocolReceiver;
535     AudioInterface* mAudioInterface; ///< Interface to Jack Client
536     PacketHeader* mPacketHeader; ///< Pointer to Packet Header
537     underrunModeT mUnderRunMode; ///< underrunModeT Mode
538     bool mStopOnTimeout; ///< Stop on 10 second timeout
539 
540     /// Pointer for the Send RingBuffer
541     RingBuffer* mSendRingBuffer;
542     /// Pointer for the Receive RingBuffer
543     RingBuffer* mReceiveRingBuffer;
544 
545     int mReceiverBindPort; ///< Incoming (receiving) port for local machine
546     int mSenderPeerPort; ///< Incoming (receiving) port for peer machine
547     int mSenderBindPort; ///< Outgoing (sending) port for local machine
548     int mReceiverPeerPort; ///< Outgoing (sending) port for peer machine
549     int mTcpServerPort;
550 
551     unsigned int mRedundancy; ///< Redundancy factor in network data
552     QString mJackClientName; ///< JackAudio Client Name
553     QString mRemoteClientName; ///< Remote JackAudio Client Name for hub client mode
554 
555     JackTrip::connectionModeT mConnectionMode; ///< Connection Mode
556     JackTrip::hubConnectionModeT mHubConnectionModeT; ///< Hub Server Jack Audio Patch Connection Mode
557 
558     QVector<ProcessPlugin*> mProcessPluginsFromNetwork; ///< Vector of ProcessPlugin<EM>s</EM>
559     QVector<ProcessPlugin*> mProcessPluginsToNetwork; ///< Vector of ProcessPlugin<EM>s</EM>
560 
561     QTimer mTimeoutTimer;
562     int mSleepTime;
563     int mElapsedTime;
564     int mEndTime;
565     QTcpSocket mTcpClient;
566     QUdpSocket mUdpSockTemp;
567 
568     volatile bool mReceivedConnection; ///< Bool of received connection from peer
569     volatile bool mTcpConnectionError;
570     volatile bool mStopped;
571     volatile bool mHasShutdown;
572 
573     bool mConnectDefaultAudioPorts; ///< Connect or not default audio ports
574     QSharedPointer<std::ofstream> mIOStatStream;
575     int mIOStatTimeout;
576     std::ostream mIOStatLogStream;
577     double mSimulatedLossRate;
578     double mSimulatedJitterRate;
579     double mSimulatedDelayRel;
580     bool mUseRtUdpPriority;
581 
582     AudioTester* mAudioTesterP;
583 };
584 
585 #endif
586