JackClient.cpp 29.1 KB
Newer Older
sletz's avatar
sletz committed
1
/*
sletz's avatar
sletz committed
2
Copyright (C) 2001 Paul Davis
sletz's avatar
sletz committed
3
Copyright (C) 2004-2008 Grame
sletz's avatar
sletz committed
4
5

This program is free software; you can redistribute it and/or modify
sletz's avatar
sletz committed
6
7
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
sletz's avatar
sletz committed
8
9
10
11
12
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
sletz's avatar
sletz committed
13
GNU Lesser General Public License for more details.
sletz's avatar
sletz committed
14

sletz's avatar
sletz committed
15
16
17
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
sletz's avatar
sletz committed
18
19
20
21
22
23
24
25
26

*/

#include "JackClient.h"
#include "JackGraphManager.h"
#include "JackClientControl.h"
#include "JackEngineControl.h"
#include "JackGlobals.h"
#include "JackChannel.h"
sletz's avatar
sletz committed
27
#include "JackTransportEngine.h"
sletz's avatar
sletz committed
28
#include "driver_interface.h"
29
30
#include "JackLibGlobals.h"

sletz's avatar
sletz committed
31
32
#include <math.h>
#include <string>
sletz's avatar
sletz committed
33
#include <algorithm>
sletz's avatar
sletz committed
34
35
36
37
38
39

using namespace std;

namespace Jack
{

40
#define IsRealTime() ((fProcess != NULL) | (fThreadFun != NULL) | (fSync != NULL) | (fTimebase != NULL))
41

42
JackClient::JackClient():fThread(this)
sletz's avatar
sletz committed
43
44
{}

45
JackClient::JackClient(JackSynchro* table):fThread(this)
sletz's avatar
sletz committed
46
47
48
49
50
51
52
53
{
    fSynchroTable = table;
    fProcess = NULL;
    fGraphOrder = NULL;
    fXrun = NULL;
    fShutdown = NULL;
    fInit = NULL;
    fBufferSize = NULL;
sletz's avatar
sletz committed
54
    fClientRegistration = NULL;
sletz's avatar
sletz committed
55
56
    fFreewheel = NULL;
    fPortRegistration = NULL;
sletz's avatar
sletz committed
57
    fPortConnect = NULL;
58
    fPortRename = NULL;
59
    fTimebase = NULL;
sletz's avatar
sletz committed
60
    fSync = NULL;
61
    fThreadFun = NULL;
sletz's avatar
sletz committed
62
63
64
65
66
67
68
    fProcessArg = NULL;
    fGraphOrderArg = NULL;
    fXrunArg = NULL;
    fShutdownArg = NULL;
    fInitArg = NULL;
    fBufferSizeArg = NULL;
    fFreewheelArg = NULL;
sletz's avatar
sletz committed
69
    fClientRegistrationArg = NULL;
sletz's avatar
sletz committed
70
    fPortRegistrationArg = NULL;
sletz's avatar
sletz committed
71
    fPortConnectArg = NULL;
72
    fPortRenameArg = NULL;
sletz's avatar
sletz committed
73
    fSyncArg = NULL;
74
    fTimebaseArg = NULL;
sletz's avatar
sletz committed
75
    fThreadFunArg = NULL;
sletz's avatar
sletz committed
76
77
78
}

JackClient::~JackClient()
79
{}
sletz's avatar
sletz committed
80
81
82

int JackClient::Close()
{
sletz's avatar
sletz committed
83
    jack_log("JackClient::Close ref = %ld", GetClientControl()->fRefNum);
84
    int result = 0;
85
    
sletz's avatar
sletz committed
86
    Deactivate();
87
    fChannel->Stop();  // Channels is stopped first to avoid receiving notifications while closing
88
    
89
90
    // Request close only if server is still running
    if (JackGlobals::fServerRunning) {
91
92
93
94
        fChannel->ClientClose(GetClientControl()->fRefNum, &result);
    } else {
        jack_log("JackClient::Close server is shutdown"); 
    }
95
    
sletz's avatar
sletz committed
96
    fChannel->Close();
97
    fSynchroTable[GetClientControl()->fRefNum].Disconnect();
98
    JackGlobals::fClientTable[GetClientControl()->fRefNum] = NULL;
sletz's avatar
sletz committed
99
100
101
102
103
104
105
106
107
108
    return result;
}

bool JackClient::IsActive()
{
    return (GetClientControl()) ? GetClientControl()->fActive : false;
}

pthread_t JackClient::GetThreadID()
{
109
    return fThread.GetThreadID();
sletz's avatar
sletz committed
110
111
112
}

/*!
113
	In "async" mode, the server does not synchronize itself on the output drivers, thus it would never "consume" the activations.
sletz's avatar
sletz committed
114
	The synchronization primitives for drivers are setup in "flush" mode that to not keep unneeded activations.
115
	Drivers synchro are setup in "flush" mode if server is "async" and NOT freewheel.
sletz's avatar
sletz committed
116
117
118
119
*/
void JackClient::SetupDriverSync(bool freewheel)
{
    if (!freewheel && !GetEngineControl()->fSyncMode) {
sletz's avatar
sletz committed
120
        jack_log("JackClient::SetupDriverSync driver sem in flush mode");
121
122
        fSynchroTable[AUDIO_DRIVER_REFNUM].SetFlush(true);
        fSynchroTable[FREEWHEEL_DRIVER_REFNUM].SetFlush(true);
sletz's avatar
sletz committed
123
        fSynchroTable[MIDI_DRIVER_REFNUM].SetFlush(true);
sletz's avatar
sletz committed
124
    } else {
sletz's avatar
sletz committed
125
        jack_log("JackClient::SetupDriverSync driver sem in normal mode");
126
127
        fSynchroTable[AUDIO_DRIVER_REFNUM].SetFlush(false);
        fSynchroTable[FREEWHEEL_DRIVER_REFNUM].SetFlush(false);
sletz's avatar
sletz committed
128
        fSynchroTable[MIDI_DRIVER_REFNUM].SetFlush(false);
sletz's avatar
sletz committed
129
130
131
132
133
134
135
    }
}

/*!
\brief Notification received from the server.
*/

sletz's avatar
sletz committed
136
int JackClient::ClientNotifyImp(int refnum, const char* name, int notify, int sync, int value1, int value2)
sletz's avatar
sletz committed
137
{
sletz's avatar
sletz committed
138
    return 0;
sletz's avatar
sletz committed
139
140
}

sletz's avatar
sletz committed
141
int JackClient::ClientNotify(int refnum, const char* name, int notify, int sync, int value1, int value2)
sletz's avatar
sletz committed
142
143
144
145
146
147
{
    int res = 0;

    // Done all time: redirected on subclass implementation JackLibClient and JackInternalClient
    switch (notify) {

148
        case kAddClient:
sletz's avatar
sletz committed
149
            res = ClientNotifyImp(refnum, name, notify, sync, value1, value2);
sletz's avatar
sletz committed
150
151
152
            break;

        case kRemoveClient:
sletz's avatar
sletz committed
153
            res = ClientNotifyImp(refnum, name, notify, sync, value1, value2);
sletz's avatar
sletz committed
154
155
156
            break;

        case kActivateClient:
sletz's avatar
sletz committed
157
            jack_log("JackClient::kActivateClient name = %s ref = %ld ", name, refnum);
sletz's avatar
sletz committed
158
159
160
            Init();
            break;
    }
sletz's avatar
sletz committed
161
162
163
164
165
166
167
168

    /*
    The current semantic is that notifications can only be received when the client has been activated,
    although is this implementation, one could imagine calling notifications as soon as the client has be opened.
    */
    if (IsActive()) {

        switch (notify) {
sletz's avatar
sletz committed
169
170

            case kAddClient:
sletz's avatar
sletz committed
171
                jack_log("JackClient::kAddClient fName = %s name = %s", GetClientControl()->fName, name);
sletz's avatar
sletz committed
172
173
174
175
176
                if (fClientRegistration && strcmp(GetClientControl()->fName, name) != 0)	// Don't call the callback for the registering client itself
                    fClientRegistration(name, 1, fClientRegistrationArg);
                break;

            case kRemoveClient:
sletz's avatar
sletz committed
177
                jack_log("JackClient::kRemoveClient fName = %s name = %s", GetClientControl()->fName, name);
sletz's avatar
sletz committed
178
179
180
                if (fClientRegistration && strcmp(GetClientControl()->fName, name) != 0)	// Don't call the callback for the registering client itself
                    fClientRegistration(name, 0, fClientRegistrationArg);
                break;
sletz's avatar
sletz committed
181

182
            case kBufferSizeCallback:
sletz's avatar
sletz committed
183
                jack_log("JackClient::kBufferSizeCallback buffer_size = %ld", value1);
sletz's avatar
sletz committed
184
                if (fBufferSize)
sletz's avatar
sletz committed
185
                    res = fBufferSize(value1, fBufferSizeArg);
sletz's avatar
sletz committed
186
                break;
187
188
189
190
191
192
                
            case kSampleRateCallback:
                jack_log("JackClient::kSampleRateCallback sample_rate = %ld", value1);
                if (fSampleRate)
                    res = fSampleRate(value1, fSampleRateArg);
                break;
sletz's avatar
sletz committed
193

194
            case kGraphOrderCallback:
sletz's avatar
sletz committed
195
                jack_log("JackClient::kGraphOrderCallback");
sletz's avatar
sletz committed
196
197
198
199
                if (fGraphOrder)
                    res = fGraphOrder(fGraphOrderArg);
                break;

200
            case kStartFreewheelCallback:
sletz's avatar
sletz committed
201
                jack_log("JackClient::kStartFreewheel");
sletz's avatar
sletz committed
202
                SetupDriverSync(true);
203
                fThread.DropRealTime();
sletz's avatar
sletz committed
204
205
206
207
                if (fFreewheel)
                    fFreewheel(1, fFreewheelArg);
                break;

208
            case kStopFreewheelCallback:
sletz's avatar
sletz committed
209
                jack_log("JackClient::kStopFreewheel");
sletz's avatar
sletz committed
210
211
212
                SetupDriverSync(false);
                if (fFreewheel)
                    fFreewheel(0, fFreewheelArg);
213
                fThread.AcquireRealTime();
sletz's avatar
sletz committed
214
215
                break;

216
            case kPortRegistrationOnCallback:
sletz's avatar
sletz committed
217
                jack_log("JackClient::kPortRegistrationOn port_index = %ld", value1);
sletz's avatar
sletz committed
218
                if (fPortRegistration)
sletz's avatar
sletz committed
219
                    fPortRegistration(value1, 1, fPortRegistrationArg);
sletz's avatar
sletz committed
220
221
                break;

222
            case kPortRegistrationOffCallback:
sletz's avatar
sletz committed
223
                jack_log("JackClient::kPortRegistrationOff port_index = %ld ", value1);
sletz's avatar
sletz committed
224
                if (fPortRegistration)
sletz's avatar
sletz committed
225
                    fPortRegistration(value1, 0, fPortRegistrationArg);
sletz's avatar
sletz committed
226
                break;
sletz's avatar
sletz committed
227
228

            case kPortConnectCallback:
sletz's avatar
sletz committed
229
                jack_log("JackClient::kPortConnectCallback src = %ld dst = %ld", value1, value2);
sletz's avatar
sletz committed
230
231
232
                if (fPortConnect)
                    fPortConnect(value1, value2, 1, fPortConnectArg);
                break;
sletz's avatar
sletz committed
233
234

            case kPortDisconnectCallback:
sletz's avatar
sletz committed
235
                jack_log("JackClient::kPortDisconnectCallback src = %ld dst = %ld", value1, value2);
sletz's avatar
sletz committed
236
237
238
                if (fPortConnect)
                    fPortConnect(value1, value2, 0, fPortConnectArg);
                break;
239
240
                
             case kPortRenameCallback:
241
                jack_log("JackClient::kPortRenameCallback port = %ld");
242
243
244
                if (fPortRename)
                    fPortRename(value1, GetGraphManager()->GetPort(value1)->GetName(), fPortRenameArg);
                break;
sletz's avatar
sletz committed
245

246
            case kXRunCallback:
sletz's avatar
sletz committed
247
                jack_log("JackClient::kXRunCallback");
sletz's avatar
sletz committed
248
249
250
                if (fXrun)
                    res = fXrun(fXrunArg);
                break;
sletz's avatar
sletz committed
251
        }
sletz's avatar
sletz committed
252
253
254
255
256
257
    }

    return res;
}

/*!
sletz's avatar
sletz committed
258
\brief We need to start thread before activating in the server, otherwise the FW driver
sletz's avatar
sletz committed
259
260
261
262
	   connected to the client may not be activated.
*/
int JackClient::Activate()
{
263
    jack_log("JackClient::Activate");
sletz's avatar
sletz committed
264
    if (IsActive())
265
266
        return 0;

267
268
269
    // RT thread is started only when needed...
    if (IsRealTime()) {
        if (StartThread() < 0)
sletz's avatar
sletz committed
270
            return -1;
271
    }
272
273
274
275
276
    
    /*
    Insertion of client in the graph will cause a kGraphOrderCallback notification 
    to be delivered by the server, the client wants to receive it.
    */
sletz's avatar
sletz committed
277
    GetClientControl()->fActive = true;
sletz's avatar
sletz committed
278
279
280
281
    
    // Transport related callback become "active"
    GetClientControl()->fTransportSync = true;
    GetClientControl()->fTransportTimebase = true;
282
283

    int result = -1;
284
285
    GetClientControl()->fCallback[kRealTimeCallback] = IsRealTime();
    fChannel->ClientActivate(GetClientControl()->fRefNum, IsRealTime(), &result);
286
    return result;
sletz's avatar
sletz committed
287
288
289
290
291
292
293
}

/*!
\brief Need to stop thread after deactivating in the server.
*/
int JackClient::Deactivate()
{
294
    jack_log("JackClient::Deactivate");
sletz's avatar
sletz committed
295
296
297
298
    if (!IsActive())
        return 0;

    GetClientControl()->fActive = false;
sletz's avatar
sletz committed
299
300
301
302
303
    
    // Transport related callback become "unactive"
    GetClientControl()->fTransportSync = false;
    GetClientControl()->fTransportTimebase = false;
    
304
    // We need to wait for the new engine cycle before stopping the RT thread, but this is done by ClientDeactivate
sletz's avatar
sletz committed
305
306
    int result = -1;
    fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
307
308
    jack_log("JackClient::Deactivate res = %ld", result);
  
309
    // RT thread is stopped only when needed...
310
    if (IsRealTime()) 
311
        fThread.Kill();
sletz's avatar
sletz committed
312
313
314
315
316
317
318
319
320
321
322
323
324
    return result;
}

//----------------------
// RT thread management
//----------------------

/*!
\brief Called once when the thread starts.
*/
bool JackClient::Init()
{
    if (fInit) {
sletz's avatar
sletz committed
325
        jack_log("JackClient::Init calling client thread init callback");
sletz's avatar
sletz committed
326
        fInit(fInitArg);
sletz's avatar
sletz committed
327
328
329
330
331
332
    }
    return true;
}

int JackClient::StartThread()
{
sletz's avatar
sletz committed
333
    jack_log("JackClient::StartThread : period = %ld computation = %ld constraint = %ld",
334
335
336
             long(int64_t(GetEngineControl()->fPeriod) / 1000.0f),
             long(int64_t(GetEngineControl()->fComputation) / 1000.0f),
             long(int64_t(GetEngineControl()->fConstraint) / 1000.0f));
sletz's avatar
sletz committed
337
338

    // Will do "something" on OSX only...
339
    fThread.SetParams(GetEngineControl()->fPeriod, GetEngineControl()->fComputation, GetEngineControl()->fConstraint);
sletz's avatar
sletz committed
340

341
    if (fThread.Start() < 0) {
sletz's avatar
sletz committed
342
343
344
345
346
        jack_error("Start thread error");
        return -1;
    }

    if (GetEngineControl()->fRealTime) {
347
        if (fThread.AcquireRealTime(GetEngineControl()->fClientPriority) < 0) {
sletz's avatar
sletz committed
348
349
350
351
352
353
354
355
356
357
            jack_error("AcquireRealTime error");
        }
    }

    return 0;
}

/*!
\brief RT thread.
*/
sletz's avatar
sletz committed
358

359
360
bool JackClient::Execute()
{
361
    if (!jack_tls_set(JackGlobals::fRealTime, this)) 
362
        jack_error("failed to set thread realtime key");
363
364
365
        
    if (GetEngineControl()->fRealTime) 
        set_threaded_log_function(); 
sletz's avatar
sletz committed
366
367
368
369
        
    // Execute a dummy cycle to be sure thread has the correct properties
    DummyCycle();
      
sletz's avatar
sletz committed
370
371
372
    if (fThreadFun) {
        fThreadFun(fThreadFunArg);
    } else {
sletz's avatar
sletz committed
373
        ExecuteThread();
sletz's avatar
sletz committed
374
    }
375
    return false; 
376
377
}

sletz's avatar
sletz committed
378
void JackClient::DummyCycle()
379
{
sletz's avatar
sletz committed
380
381
    WaitSync();
    SignalSync();
382
383
384
385
}

inline void JackClient::ExecuteThread()
{
sletz's avatar
sletz committed
386
387
388
389
    while (true) { 
        CycleWaitAux();
        CycleSignalAux(CallProcessCallback());  
	}
390
391
}

sletz's avatar
sletz committed
392
inline jack_nframes_t JackClient::CycleWaitAux()
sletz's avatar
sletz committed
393
{
394
395
    if (!WaitSync()) 
        Error();   // Terminates the thread
sletz's avatar
sletz committed
396
    CallSyncCallbackAux();
sletz's avatar
sletz committed
397
    return GetEngineControl()->fBufferSize;
sletz's avatar
sletz committed
398
399
}

sletz's avatar
sletz committed
400
inline void JackClient::CycleSignalAux(int status)
sletz's avatar
sletz committed
401
{
sletz's avatar
sletz committed
402
    if (status == 0)
sletz's avatar
sletz committed
403
        CallTimebaseCallbackAux();
sletz's avatar
sletz committed
404
    SignalSync();
405
406
    if (status != 0) 
        End();     // Terminates the thread
sletz's avatar
sletz committed
407
408
}

sletz's avatar
sletz committed
409
410
411
412
413
414
415
416
417
418
jack_nframes_t JackClient::CycleWait()
{
    return CycleWaitAux();
}

void JackClient::CycleSignal(int status)
{
    CycleSignalAux(status);
}

419
420
inline int JackClient::CallProcessCallback()
{
sletz's avatar
sletz committed
421
    return (fProcess != NULL) ? fProcess(GetEngineControl()->fBufferSize, fProcessArg) : 0;
422
423
424
425
}

inline bool JackClient::WaitSync()
{
sletz's avatar
sletz committed
426
    // Suspend itself: wait on the input synchro
427
    if (GetGraphManager()->SuspendRefNum(GetClientControl(), fSynchroTable, 0x7FFFFFFF) < 0) {
sletz's avatar
sletz committed
428
429
430
431
432
        jack_error("SuspendRefNum error");
        return false;
    } else {
        return true;
    }
433
434
435
436
}

inline void JackClient::SignalSync()
{
sletz's avatar
sletz committed
437
    // Resume: signal output clients connected to the running client
438
439
440
441
    if (GetGraphManager()->ResumeRefNum(GetClientControl(), fSynchroTable) < 0) {
        jack_error("ResumeRefNum error");
    }
}
sletz's avatar
sletz committed
442

443
inline void JackClient::End()
sletz's avatar
Cleanup    
sletz committed
444
{
sletz's avatar
sletz committed
445
    jack_log("JackClient::Execute end name = %s", GetClientControl()->fName);
sletz's avatar
sletz committed
446
447
    // Hum... not sure about this, the following "close" code is called in the RT thread...
    int result;
448
    fThread.DropRealTime();
sletz's avatar
sletz committed
449
450
    GetClientControl()->fActive = false;
    fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
451
    fThread.Terminate();
sletz's avatar
Cleanup    
sletz committed
452
453
}

454
inline void JackClient::Error()
sletz's avatar
Cleanup    
sletz committed
455
{
sletz's avatar
sletz committed
456
457
458
    jack_error("JackClient::Execute error name = %s", GetClientControl()->fName);
    // Hum... not sure about this, the following "close" code is called in the RT thread...
    int result;
459
    fThread.DropRealTime();
sletz's avatar
sletz committed
460
461
    GetClientControl()->fActive = false;
    fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
sletz's avatar
Cleanup    
sletz committed
462
    ShutDown();
463
    fThread.Terminate();
sletz's avatar
Cleanup    
sletz committed
464
465
}

sletz's avatar
sletz committed
466
467
468
469
470
471
//-----------------
// Port management
//-----------------

int JackClient::PortRegister(const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size)
{
472
    // Check if port name is empty
sletz's avatar
sletz committed
473
474
    string port_name_str = string(port_name);
    if (port_name_str.size() == 0) {
475
        jack_error("port_name is empty");
sletz's avatar
sletz committed
476
477
478
        return 0; // Means failure here...
    }

479
    // Check port name length
sletz's avatar
sletz committed
480
481
482
    string name = string(GetClientControl()->fName) + string(":") + port_name_str;
    if (name.size() >= JACK_PORT_NAME_SIZE) {
        jack_error("\"%s:%s\" is too long to be used as a JACK port name.\n"
483
                   "Please use %lu characters or less",
sletz's avatar
sletz committed
484
485
486
487
488
489
490
                   GetClientControl()->fName,
                   port_name,
                   JACK_PORT_NAME_SIZE - 1);
        return 0; // Means failure here...
    }

    int result = -1;
491
    jack_port_id_t port_index = NO_PORT;
sletz's avatar
sletz committed
492
    fChannel->PortRegister(GetClientControl()->fRefNum, name.c_str(), port_type, flags, buffer_size, &port_index, &result);
493
  
sletz's avatar
sletz committed
494
    if (result == 0) {
495
        jack_log("JackClient::PortRegister ref = %ld name = %s type = %s port_index = %ld", GetClientControl()->fRefNum, name.c_str(), port_type, port_index);
sletz's avatar
sletz committed
496
497
498
499
500
501
502
503
504
        fPortList.push_back(port_index);
        return port_index;
    } else {
        return 0;
    }
}

int JackClient::PortUnRegister(jack_port_id_t port_index)
{
sletz's avatar
sletz committed
505
    jack_log("JackClient::PortUnRegister port_index = %ld", port_index);
sletz's avatar
sletz committed
506
    list<jack_port_id_t>::iterator it = find(fPortList.begin(), fPortList.end(), port_index);
sletz's avatar
sletz committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520

    if (it != fPortList.end()) {
        fPortList.erase(it);
        int result = -1;
        fChannel->PortUnRegister(GetClientControl()->fRefNum, port_index, &result);
        return result;
    } else {
        jack_error("unregistering a port %ld that is not own by the client", port_index);
        return -1;
    }
}

int JackClient::PortConnect(const char* src, const char* dst)
{
sletz's avatar
sletz committed
521
    jack_log("JackClient::Connect src = %s dst = %s", src, dst);
sletz's avatar
sletz committed
522
523
524
525
526
527
528
    int result = -1;
    fChannel->PortConnect(GetClientControl()->fRefNum, src, dst, &result);
    return result;
}

int JackClient::PortDisconnect(const char* src, const char* dst)
{
sletz's avatar
sletz committed
529
    jack_log("JackClient::Disconnect src = %s dst = %s", src, dst);
sletz's avatar
sletz committed
530
531
532
533
534
535
536
    int result = -1;
    fChannel->PortDisconnect(GetClientControl()->fRefNum, src, dst, &result);
    return result;
}

int JackClient::PortDisconnect(jack_port_id_t src)
{
sletz's avatar
sletz committed
537
    jack_log("JackClient::PortDisconnect src = %ld", src);
sletz's avatar
sletz committed
538
539
540
541
542
543
544
545
546
547
548
    int result = -1;
    fChannel->PortDisconnect(GetClientControl()->fRefNum, src, ALL_PORTS, &result);
    return result;
}

int JackClient::PortIsMine(jack_port_id_t port_index)
{
    JackPort* port = GetGraphManager()->GetPort(port_index);
    return GetClientControl()->fRefNum == port->GetRefNum();
}

549
550
551
552
553
554
555
int JackClient::PortRename(jack_port_id_t port_index, const char* name)
{
    int result = -1;
    fChannel->PortRename(GetClientControl()->fRefNum, port_index, name, &result);
    return result;
}

sletz's avatar
sletz committed
556
557
558
559
//--------------------
// Context management
//--------------------

560
int JackClient::SetBufferSize(jack_nframes_t buffer_size)
sletz's avatar
sletz committed
561
562
{
    int result = -1;
563
    fChannel->SetBufferSize(buffer_size, &result);
sletz's avatar
sletz committed
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
    return result;
}

int JackClient::SetFreeWheel(int onoff)
{
    int result = -1;
    fChannel->SetFreewheel(onoff, &result);
    return result;
}

/*
ShutDown is called:
- from the RT thread when Execute method fails
- possibly from a "closed" notification channel
(Not needed since the synch object used (Sema of Fifo will fails when server quits... see ShutDown))
*/

void JackClient::ShutDown()
{
sletz's avatar
sletz committed
583
    jack_log("ShutDown");
584
    JackGlobals::fServerRunning = false;
585
    
sletz's avatar
sletz committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
    if (fShutdown) {
        fShutdown(fShutdownArg);
        fShutdown = NULL;
    }
}

//----------------------
// Transport management
//----------------------

int JackClient::ReleaseTimebase()
{
    int result = -1;
    fChannel->ReleaseTimebase(GetClientControl()->fRefNum, &result);
    if (result == 0) {
sletz's avatar
sletz committed
601
        GetClientControl()->fTransportTimebase = false;
sletz's avatar
sletz committed
602
603
604
605
606
607
608
609
610
        fTimebase = NULL;
        fTimebaseArg = NULL;
    }
    return result;
}

/* Call the server if the client is active, otherwise keeps the arguments */
int JackClient::SetSyncCallback(JackSyncCallback sync_callback, void* arg)
{
sletz's avatar
sletz committed
611
    GetClientControl()->fTransportSync = (fSync != NULL);
sletz's avatar
sletz committed
612
    fSyncArg = arg;
sletz's avatar
sletz committed
613
    fSync = sync_callback;
sletz's avatar
sletz committed
614
615
616
617
618
619
620
621
622
    return 0;
}

int JackClient::SetSyncTimeout(jack_time_t timeout)
{
    GetEngineControl()->fTransport.SetSyncTimeout(timeout);
    return 0;
}

sletz's avatar
sletz committed
623
624
625
626
627
628
int JackClient::SetTimebaseCallback(int conditional, JackTimebaseCallback timebase_callback, void* arg)
{
    int result = -1;
    fChannel->SetTimebaseCallback(GetClientControl()->fRefNum, conditional, &result);
    jack_log("SetTimebaseCallback result = %ld", result);
    if (result == 0) {
sletz's avatar
sletz committed
629
        GetClientControl()->fTransportTimebase = true;
sletz's avatar
sletz committed
630
631
632
633
634
635
636
637
        fTimebase = timebase_callback;
        fTimebaseArg = arg;
    } else {
        fTimebase = NULL;
        fTimebaseArg = NULL;
    }
    return result;
}
sletz's avatar
sletz committed
638
639
640

// Must be RT safe

641
void JackClient::TransportLocate(jack_nframes_t frame)
sletz's avatar
sletz committed
642
643
644
645
{
    jack_position_t pos;
    pos.frame = frame;
    pos.valid = (jack_position_bits_t)0;
sletz's avatar
sletz committed
646
    jack_log("TransportLocate pos = %ld", pos.frame);
647
    GetEngineControl()->fTransport.RequestNewPos(&pos);
sletz's avatar
sletz committed
648
649
650
651
652
}

int JackClient::TransportReposition(jack_position_t* pos)
{
    jack_position_t tmp = *pos;
sletz's avatar
sletz committed
653
    jack_log("TransportReposition pos = %ld", pos->frame);
654
655
656
657
658
659
    if (tmp.valid & ~JACK_POSITION_MASK) {
        return EINVAL;
    } else {
        GetEngineControl()->fTransport.RequestNewPos(pos);
        return 0;
    }
sletz's avatar
sletz committed
660
661
662
663
}

jack_transport_state_t JackClient::TransportQuery(jack_position_t* pos)
{
664
    return GetEngineControl()->fTransport.Query(pos);
sletz's avatar
sletz committed
665
666
667
668
}

jack_nframes_t JackClient::GetCurrentTransportFrame()
{
669
    return GetEngineControl()->fTransport.GetCurrentFrame();
sletz's avatar
sletz committed
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
}

// Must be RT safe: directly write in the transport shared mem
void JackClient::TransportStart()
{
    GetEngineControl()->fTransport.SetCommand(TransportCommandStart);
}

// Must be RT safe: directly write in the transport shared mem
void JackClient::TransportStop()
{
    GetEngineControl()->fTransport.SetCommand(TransportCommandStop);
}

// Never called concurently with the server
sletz's avatar
sletz committed
685
// TODO check concurrency with SetSyncCallback
sletz's avatar
sletz committed
686

sletz's avatar
sletz committed
687
void JackClient::CallSyncCallback()
sletz's avatar
sletz committed
688
689
690
691
692
{
    CallSyncCallbackAux();
}

inline void JackClient::CallSyncCallbackAux()
sletz's avatar
sletz committed
693
{
sletz's avatar
sletz committed
694
695
696
697
698
699
700
701
    if (GetClientControl()->fTransportSync) {
    
        JackTransportEngine& transport = GetEngineControl()->fTransport;
        jack_position_t* cur_pos = transport.ReadCurrentState();
        jack_transport_state_t transport_state = transport.GetState();
    
        if (fSync != NULL) {
            if (fSync(transport_state, cur_pos, fSyncArg)) {
sletz's avatar
sletz committed
702
                GetClientControl()->fTransportState = JackTransportRolling;
sletz's avatar
sletz committed
703
                GetClientControl()->fTransportSync = false;
sletz's avatar
sletz committed
704
            }
sletz's avatar
sletz committed
705
706
707
708
        } else {
            GetClientControl()->fTransportState = JackTransportRolling;
            GetClientControl()->fTransportSync = false;
        }
sletz's avatar
sletz committed
709
710
711
712
    }
}

void JackClient::CallTimebaseCallback()
sletz's avatar
sletz committed
713
714
715
716
717
{
    CallTimebaseCallbackAux();
}

inline void JackClient::CallTimebaseCallbackAux()
sletz's avatar
sletz committed
718
719
{
    JackTransportEngine& transport = GetEngineControl()->fTransport;
720
721
    int master;
    bool unused;
sletz's avatar
sletz committed
722
    
723
724
725
    transport.GetTimebaseMaster(master, unused);
    
    if (GetClientControl()->fRefNum == master && fTimebase) { // Client *is* timebase...
sletz's avatar
sletz committed
726
    
sletz's avatar
sletz committed
727
728
        jack_transport_state_t transport_state = transport.GetState();
        jack_position_t* cur_pos = transport.WriteNextStateStart(1);
sletz's avatar
sletz committed
729
        
sletz's avatar
sletz committed
730
        if (GetClientControl()->fTransportTimebase) {
sletz's avatar
sletz committed
731
            fTimebase(transport_state, GetEngineControl()->fBufferSize, cur_pos, true, fTimebaseArg); 
sletz's avatar
sletz committed
732
            GetClientControl()->fTransportTimebase = false; // Callback is called only once with "new_pos" = true 
sletz's avatar
sletz committed
733
        } else if (transport_state == JackTransportRolling) {
sletz's avatar
sletz committed
734
            fTimebase(transport_state, GetEngineControl()->fBufferSize, cur_pos, false, fTimebaseArg);
sletz's avatar
sletz committed
735
        } 
sletz's avatar
sletz committed
736
        
sletz's avatar
sletz committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
        transport.WriteNextStateStop(1);
    }
}

//---------------------
// Callback management
//---------------------

void JackClient::OnShutdown(JackShutdownCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
    } else {
        fShutdownArg = arg;
        fShutdown = callback;
    }
}

int JackClient::SetProcessCallback(JackProcessCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
760
    } else if (fThreadFun) {
761
762
763
        jack_error ("A thread callback has already been setup, both models cannot be used at the same time!");
        return -1;
    } else {
sletz's avatar
sletz committed
764
765
766
767
768
769
770
771
772
773
774
775
        fProcessArg = arg;
        fProcess = callback;
        return 0;
    }
}

int JackClient::SetXRunCallback(JackXRunCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
776
        GetClientControl()->fCallback[kXRunCallback] = (callback != NULL);
sletz's avatar
sletz committed
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
        fXrunArg = arg;
        fXrun = callback;
        return 0;
    }
}

int JackClient::SetInitCallback(JackThreadInitCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
        fInitArg = arg;
        fInit = callback;
        return 0;
    }
}

int JackClient::SetGraphOrderCallback(JackGraphOrderCallback callback, void *arg)
{
sletz's avatar
sletz committed
797
    jack_log("SetGraphOrderCallback ");
sletz's avatar
sletz committed
798
799
800
801
802

    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
803
        GetClientControl()->fCallback[kGraphOrderCallback] = (callback != NULL);
sletz's avatar
sletz committed
804
805
806
807
808
809
810
811
812
813
814
815
        fGraphOrder = callback;
        fGraphOrderArg = arg;
        return 0;
    }
}

int JackClient::SetBufferSizeCallback(JackBufferSizeCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
816
        GetClientControl()->fCallback[kBufferSizeCallback] = (callback != NULL);
sletz's avatar
sletz committed
817
818
819
820
821
822
        fBufferSizeArg = arg;
        fBufferSize = callback;
        return 0;
    }
}

823
824
825
826
827
828
829
830
831
832
833
834
835
int JackClient::SetSampleRateCallback(JackSampleRateCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
        GetClientControl()->fCallback[kSampleRateCallback] = (callback != NULL);
        fSampleRateArg = arg;
        fSampleRate = callback;
        return 0;
    }
}

836
837
838
839
840
841
int JackClient::SetClientRegistrationCallback(JackClientRegistrationCallback callback, void* arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
842
843
        // kAddClient and kRemoveClient notifications must be delivered by the server in any case
        fClientRegistrationArg = arg;
844
845
846
847
848
        fClientRegistration = callback;
        return 0;
    }
}

sletz's avatar
sletz committed
849
850
851
852
853
854
int JackClient::SetFreewheelCallback(JackFreewheelCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
855
856
        GetClientControl()->fCallback[kStartFreewheelCallback] = (callback != NULL);
        GetClientControl()->fCallback[kStopFreewheelCallback] = (callback != NULL);
sletz's avatar
sletz committed
857
858
859
860
861
862
863
864
865
866
867
868
        fFreewheelArg = arg;
        fFreewheel = callback;
        return 0;
    }
}

int JackClient::SetPortRegistrationCallback(JackPortRegistrationCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
869
870
        GetClientControl()->fCallback[kPortRegistrationOnCallback] = (callback != NULL);
        GetClientControl()->fCallback[kPortRegistrationOffCallback] = (callback != NULL);
sletz's avatar
sletz committed
871
872
873
874
875
876
        fPortRegistrationArg = arg;
        fPortRegistration = callback;
        return 0;
    }
}

sletz's avatar
sletz committed
877
878
879
880
881
882
int JackClient::SetPortConnectCallback(JackPortConnectCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
sletz's avatar
sletz committed
883
884
        GetClientControl()->fCallback[kPortConnectCallback] = (callback != NULL);
        GetClientControl()->fCallback[kPortDisconnectCallback] = (callback != NULL);
sletz's avatar
sletz committed
885
886
887
888
889
890
        fPortConnectArg = arg;
        fPortConnect = callback;
        return 0;
    }
}

891
892
893
894
895
896
897
898
899
900
901
902
903
int JackClient::SetPortRenameCallback(JackPortRenameCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
        GetClientControl()->fCallback[kPortRenameCallback] = (callback != NULL);
        fPortRenameArg = arg;
        fPortRename = callback;
        return 0;
    }
}

904
905
906
907
908
909
int JackClient::SetProcessThread(JackThreadCallback fun, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else if (fProcess) {
910
911
912
        jack_error ("A process callback has already been setup, both models cannot be used at the same time!");
        return -1;
    } else {
913
914
915
916
917
918
        fThreadFun = fun;
        fThreadFunArg = arg;
        return 0;
    }
}

919
920
921
922
923
924
//------------------
// Internal clients
//------------------

char* JackClient::GetInternalClientName(int ref)
{
925
    char name_res[JACK_CLIENT_NAME_SIZE + 1];
sletz's avatar
sletz committed
926
927
928
929
930
931
932
933
934
935
    int result = -1;
    fChannel->GetInternalClientName(GetClientControl()->fRefNum, ref, name_res, &result);

    if (result < 0) {
        return NULL;
    } else {
        char* name = (char*)malloc(strlen(name_res));
        strcpy(name, name_res);
        return name;
    }
936
937
938
939
}

int JackClient::InternalClientHandle(const char* client_name, jack_status_t* status)
{
sletz's avatar
sletz committed
940
941
942
    int int_ref, result = -1;
    fChannel->InternalClientHandle(GetClientControl()->fRefNum, client_name, (int*)status, &int_ref, &result);
    return int_ref;
943
944
945
946
}

int JackClient::InternalClientLoad(const char* client_name, jack_options_t options, jack_status_t* status, jack_varargs_t* va)
{
sletz's avatar
sletz committed
947
948
949
950
951
952
953
    if (strlen(client_name) >= JACK_CLIENT_NAME_SIZE) {
        jack_error ("\"%s\" is too long for a JACK client name.\n"
                    "Please use %lu characters or less.",
                    client_name, JACK_CLIENT_NAME_SIZE);
        return 0;
    }

954
    if (va->load_name && (strlen(va->load_name) >= JACK_PATH_MAX)) {
sletz's avatar
sletz committed
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
        jack_error("\"%s\" is too long for a shared object name.\n"
                   "Please use %lu characters or less.",
                   va->load_name, PATH_MAX);
        int my_status1 = *status | (JackFailure | JackInvalidOption);
        *status = (jack_status_t)my_status1;
        return 0;
    }

    if (va->load_init && (strlen(va->load_init) >= JACK_LOAD_INIT_LIMIT)) {
        jack_error ("\"%s\" is too long for internal client init "
                    "string.\nPlease use %lu characters or less.",
                    va->load_init, JACK_LOAD_INIT_LIMIT);
        int my_status1 = *status | (JackFailure | JackInvalidOption);
        *status = (jack_status_t)my_status1;
        return 0;
    }

    int int_ref, result = -1;
    fChannel->InternalClientLoad(GetClientControl()->fRefNum, client_name, va->load_name, va->load_init, options, (int*)status, &int_ref, &result);
    return int_ref;
975
976
977
978
}

void JackClient::InternalClientUnload(int ref, jack_status_t* status)
{
sletz's avatar
sletz committed
979
980
    int result = -1;
    fChannel->InternalClientUnload(GetClientControl()->fRefNum, ref, (int*)status, &result);
981
982
983
}


sletz's avatar
sletz committed
984
985
} // end of namespace