Codebase list jacktrip / debian/1.1_repack-7 src / UdpMasterListener.cpp
debian/1.1_repack-7

Tree @debian/1.1_repack-7 (Download .tar.gz)

UdpMasterListener.cpp @debian/1.1_repack-7raw · history · blame

  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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//*****************************************************************
/*
  JackTrip: A System for High-Quality Audio Network Performance
  over the Internet

  Copyright (c) 2008 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 UdpMasterListener.cpp
 * \author Juan-Pablo Caceres and Chris Chafe
 * \date September 2008
 */

#include <iostream>
#include <cstdlib>
#include <stdexcept>
#include <cstring>

#include <QTcpServer>
#include <QTcpSocket>
#include <QStringList>
#include <QMutexLocker>

#include "UdpMasterListener.h"
#include "JackTripWorker.h"
#include "jacktrip_globals.h"

using std::cout; using std::endl;


//*******************************************************************************
UdpMasterListener::UdpMasterListener(int server_port) :
    //mJTWorker(NULL),
    mServerPort(server_port),
    mStopped(false),
    mTotalRunningThreads(0)
{
  // Register JackTripWorker with the master listener
  //mJTWorker = new JackTripWorker(this);
  mJTWorkers = new QVector<JackTripWorker*>;
  for (int i = 0; i<gMaxThreads; i++) {
    mJTWorkers->insert(i, NULL);
  }


  //mJTWorkers = new JackTripWorker(this);
  mThreadPool.setExpiryTimeout(3000); // msec (-1) = forever
  // Inizialize IP addresses
  for (int i = 0; i<gMaxThreads; i++) { 
    mActiveAddress[i][0] = 0; // 32-bit ints
    mActiveAddress[i][1] = 0; // 32-bit ints
  }
  // Set the base dynamic port
  // The Dynamic and/or Private Ports are those from 49152 through 65535
  // mBasePort = ( rand() % ( (65535 - gMaxThreads) - 49152 ) ) + 49152;

  // SoundWIRE ports open are UDP 61000-62000
  mBasePort = 61000;
}


//*******************************************************************************
UdpMasterListener::~UdpMasterListener()
{
  QMutexLocker lock(&mMutex);
  mThreadPool.waitForDone();
  //delete mJTWorker;
  for (int i = 0; i<gMaxThreads; i++) {
    delete mJTWorkers->at(i);
  }
  delete mJTWorkers;
}


//*******************************************************************************
// Now that the first handshake is with TCP server, if the addreess/peer port of
// the client is already on the thread pool, it means that a new connection is
// requested (the old was desconnected). So we have to remove that thread from
// the pool and then connect again.
void UdpMasterListener::run()
{
  mStopped = false;

  QHostAddress PeerAddress; // Object to store peer address
  int peer_udp_port; // Peer listening port
  int server_udp_port; // Server assigned udp port

  // Create and bind the TCP server
  // ------------------------------
  QTcpServer TcpServer;
  if ( !TcpServer.listen(QHostAddress::Any, mServerPort) ) {
    std::cerr << "TCP Socket Server ERROR: " << TcpServer.errorString().toStdString() <<  endl;
    std::exit(1);
  }

  const int tcpTimeout = 5*1000;


  cout << "JackTrip MULTI-THREADED SERVER: TCP Server Listening in Port = " << TcpServer.serverPort() << endl;
  while ( !mStopped )
  {
    cout << "JackTrip MULTI-THREADED SERVER: Waiting for client connections..." << endl;
    cout << "=======================================================" << endl;
    while ( !TcpServer.waitForNewConnection(1000) )
    { if (mStopped) { return; } } // block until a new connection is received
    cout << "JackTrip MULTI-THREADED SERVER: Client Connection Received!" << endl;

    // Control loop to be able to exit if UDPs or TCPs error ocurr
    for (int dum = 0; dum<1; dum++) {
      QTcpSocket *clientConnection = TcpServer.nextPendingConnection();
      if ( !clientConnection->waitForConnected(tcpTimeout) ) {
        std::cerr << clientConnection->errorString().toStdString() << endl;
        break;
      }
      PeerAddress = clientConnection->peerAddress();
      cout << "JackTrip MULTI-THREADED SERVER: Client Connect Received from Address : "
          << PeerAddress.toString().toStdString() << endl;

      // Get UDP port from client
      // ------------------------
      peer_udp_port = readClientUdpPort(clientConnection);
      if ( peer_udp_port == 0 ) { break; }
      cout << "JackTrip MULTI-THREADED SERVER: Client UDP Port is = " << peer_udp_port << endl;

      // Check is client is new or not
      // -----------------------------
      // Check if Address is not already in the thread pool
      // check by comparing 32-bit addresses
      int id = isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port);
      // If the address is not new, we need to remove the client from the pool
      // before re-starting the connection
      if (id == -1) {
        int id_remove;
        id_remove = getPoolID(PeerAddress.toIPv4Address(), peer_udp_port);
        // stop the thread
        mJTWorkers->at(id_remove)->stopThread();
        // block until the thread has been removed from the pool
        while ( isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port) == -1 ) {
          cout << "JackTrip MULTI-THREADED SERVER: Removing JackTripWorker from pool..." << endl;
          QThread::msleep(10);
        }
        // Get a new ID for this client
        //id = isNewAddress(PeerAddress.toIPv4Address(), peer_udp_port);
        id = getPoolID(PeerAddress.toIPv4Address(), peer_udp_port);
      }
      // Assign server port and send it to Client
      server_udp_port = mBasePort+id;
      if ( sendUdpPort(clientConnection, server_udp_port) == 0 ) {
        clientConnection->close();
        delete clientConnection;
        releaseThread(id);
        break;
      }

      // Close and Delete the socket
      // ---------------------------
      clientConnection->close();
      delete clientConnection;
      cout << "JackTrip MULTI-THREADED SERVER: Client TCP Socket Closed!" << endl;

      // Spawn Thread to Pool
      // --------------------
      // Register JackTripWorker with the master listener
      delete mJTWorkers->at(id); // just in case the Worker was previously created
      mJTWorkers->replace(id, new JackTripWorker(this));
      // redirect port and spawn listener
      cout << "---> JackTrip MULTI-THREADED SERVER: Spawning Listener..." << endl;
      {
        QMutexLocker lock(&mMutex);
        mJTWorkers->at(id)->setJackTrip(id, mActiveAddress[id][0],
                                        server_udp_port, mActiveAddress[id][1],
                                        1); /// \todo temp default to 1 channel
      }
      //send one thread to the pool
      cout << "---> JackTrip MULTI-THREADED SERVER: Starting Thread..." << endl;
      mThreadPool.start(mJTWorkers->at(id), QThread::TimeCriticalPriority);
      // wait until one is complete before another spawns
      while (mJTWorkers->at(id)->isSpawning()) { QThread::msleep(10); }
      //mTotalRunningThreads++;
      cout << "JackTrip MULTI-THREADED SERVER: Total Running Threads:  " << mTotalRunningThreads << endl;
      cout << "===============================================================" << endl;
      QThread::msleep(100);
    }
  }

  /*
  // Create objects on the stack
  QUdpSocket MasterUdpSocket;
  QHostAddress PeerAddress;
  uint16_t peer_port; // Ougoing Peer port, in case they're not using the default

  // Bind the socket to the well known port
  bindUdpSocket(MasterUdpSocket, mServerPort);

  char buf[1];
  cout << "Server Listening in UDP Port: " << mServerPort << endl;
  cout << "Waiting for client..." << endl;
  cout << "=======================================================" << endl;
  while ( !mStopped )
  {
    //cout << "WAITING........................." << endl;
    while ( MasterUdpSocket.hasPendingDatagrams() )
    {
      cout << "Received request from Client!" << endl;
      // Get Client IP Address and outgoing port from packet
      int rv = MasterUdpSocket.readDatagram(buf, 1, &PeerAddress, &peer_port);
      cout << "Peer Port in Server ==== " << peer_port << endl;
      if (rv < 0) { std::cerr << "ERROR: Bad UDP packet read..." << endl; }

      /// \todo Get number of channels in the client from header

      // check by comparing 32-bit addresses
      /// \todo Add the port number in the comparison
      cout << "peer_portpeer_portpeer_port === " << peer_port << endl;
      int id = isNewAddress(PeerAddress.toIPv4Address(), peer_port);

      //cout << "IDIDIDIDIDDID === " << id << endl;

      // If the address is new, create a new thread in the pool
      if (id >= 0) // old address is -1
      {
        // redirect port and spawn listener
        sendToPoolPrototype(id);
        // wait until one is complete before another spawns
        while (mJTWorker->isSpawning()) { QThread::msleep(10); }
        mTotalRunningThreads++;
        cout << "Total Running Threads:  " << mTotalRunningThreads << endl;
        cout << "=======================================================" << endl;
      }
      //cout << "ENDDDDDDDDDDDDDDDDDd === " << id << endl;
    }
    QThread::msleep(100);
  }
  */
}


//*******************************************************************************
// Returns 0 on error
int UdpMasterListener::readClientUdpPort(QTcpSocket* clientConnection)
{
  // Read the size of the package
  // ----------------------------
  //tcpClient.waitForReadyRead();
  cout << "Reading UDP port from Server..." << endl;
  while (clientConnection->bytesAvailable() < (int)sizeof(uint16_t)) {
    if (!clientConnection->waitForReadyRead()) {
      std::cerr << "TCP Socket ERROR: " << clientConnection->errorString().toStdString() <<  endl;
      return 0;
    }
  }

  cout << "Ready To Read From Socket!" << endl;
  // Read UDP Port Number from Server
  // --------------------------------
  int udp_port;
  int size = sizeof(udp_port);
  char port_buf[size];
  clientConnection->read(port_buf, size);
  std::memcpy(&udp_port, port_buf, size);
  return udp_port;
}


//*******************************************************************************
int UdpMasterListener::sendUdpPort(QTcpSocket* clientConnection, int udp_port)
{
  // Send Port Number to Client
  // --------------------------
  char port_buf[sizeof(udp_port)];
  std::memcpy(port_buf, &udp_port, sizeof(udp_port));
  clientConnection->write(port_buf, sizeof(udp_port));
  while ( clientConnection->bytesToWrite() > 0 ) {
    if ( clientConnection->state() == QAbstractSocket::ConnectedState ) {
      clientConnection->waitForBytesWritten(-1);
    }
    else {
      return 0;
    }
  }
  return 1;
  cout << "Port sent to Client" << endl;
}


//*******************************************************************************
/*
void UdpMasterListener::sendToPoolPrototype(int id)
{
  mJTWorker->setJackTrip(id, mActiveAddress[id][0],
                         mBasePort+(2*id), mActiveAddress[id][1],
                         1); /// \todo temp default to 1 channel
  mThreadPool.start(mJTWorker, QThread::TimeCriticalPriority); //send one thread to the pool
}
*/


//*******************************************************************************
void UdpMasterListener::bindUdpSocket(QUdpSocket& udpsocket, int port) throw(std::runtime_error)
{
  // QHostAddress::Any : let the kernel decide the active address
  if ( !udpsocket.bind(QHostAddress::Any,
                       port, QUdpSocket::DefaultForPlatform) ) {
    //std::cerr << "ERROR: could not bind UDP socket" << endl;
    //std::exit(1);
    throw std::runtime_error("Could not bind UDP socket. It may be already binded.");
  }
  else {
    cout << "UDP Socket Receiving in Port: " << port << endl;
  }
}


//*******************************************************************************
// check by comparing 32-bit addresses
int UdpMasterListener::isNewAddress(uint32_t address, uint16_t port)
{
  QMutexLocker lock(&mMutex);
  bool busyAddress = false;
  int id = 0;

  /*
  while ( !busyAddress && (id<mThreadPool.activeThreadCount()) )
  {
    if ( address==mActiveAddress[id][0] &&  port==mActiveAddress[id][1]) { busyAddress = true; }
    id++;
  }
  */
  for (int i = 0; i<gMaxThreads; i++) {
    if ( address==mActiveAddress[i][0] &&  port==mActiveAddress[i][1]) {
      id = i;
      busyAddress = true;
    }
  }
  if ( !busyAddress ) {
    /*
    mActiveAddress[id][0] = address;
    mActiveAddress[id][1] = port;
  } else {
  */
    id = 0;
    bool foundEmptyAddress = false;
    while ( !foundEmptyAddress && (id<gMaxThreads) ) {
      if ( (mActiveAddress[id][0] == 0) &&  (mActiveAddress[id][1] == 0) ) {
        foundEmptyAddress = true;
        mActiveAddress[id][0] = address;
        mActiveAddress[id][1] = port;
      }  else {
        id++;
      }
    }
  }
  if (!busyAddress) {
    mTotalRunningThreads++;
  }
  return ((busyAddress) ? -1 : id);
}


//*******************************************************************************
int UdpMasterListener::getPoolID(uint32_t address, uint16_t port)
{
  QMutexLocker lock(&mMutex);
  //for (int id = 0; id<mThreadPool.activeThreadCount(); id++ )
  for (int id = 0; id<gMaxThreads; id++ )
  {
    if ( address==mActiveAddress[id][0] &&  port==mActiveAddress[id][1])
    { return id; }
  }
  return -1;
}


//*******************************************************************************
int UdpMasterListener::releaseThread(int id)
{ 
  QMutexLocker lock(&mMutex);
  mActiveAddress[id][0] = 0;
  mActiveAddress[id][1] = 0;
  mTotalRunningThreads--;
  return 0; /// \todo Check if we really need to return an argument here
}


// TODO:
// USE bool QAbstractSocket::isValid () const to check if socket is connect. if not, exit loop