JackClient.cpp 26.2 KB
Newer Older
sletz's avatar
sletz committed
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
/*
Copyright (C) 2001 Paul Davis 
Copyright (C) 2004-2006 Grame

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(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
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/


#include "JackClient.h"
#include "JackGraphManager.h"
#include "JackClientControl.h"
#include "JackEngineControl.h"
#include "JackGlobals.h"
#include "JackChannel.h"
sletz's avatar
sletz committed
28
29
#include "JackTransportEngine.h"
#include "driver_interface.h"
sletz's avatar
sletz committed
30
31
#include <math.h>
#include <string>
sletz's avatar
sletz committed
32
#include <algorithm>
sletz's avatar
sletz committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

using namespace std;

namespace Jack
{

JackClient::JackClient()
{}

JackClient::JackClient(JackSynchro** table)
{
    fThread = JackGlobals::MakeThread(this);
    fSynchroTable = table;
    fProcess = NULL;
    fGraphOrder = NULL;
    fXrun = NULL;
    fShutdown = NULL;
    fInit = NULL;
    fBufferSize = NULL;
sletz's avatar
sletz committed
52
	fClientRegistration = NULL;
sletz's avatar
sletz committed
53
54
55
56
57
58
59
60
61
62
    fFreewheel = NULL;
    fPortRegistration = NULL;
    fSync = NULL;
    fProcessArg = NULL;
    fGraphOrderArg = NULL;
    fXrunArg = NULL;
    fShutdownArg = NULL;
    fInitArg = NULL;
    fBufferSizeArg = NULL;
    fFreewheelArg = NULL;
sletz's avatar
sletz committed
63
    fClientRegistrationArg = NULL;
sletz's avatar
sletz committed
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
    fPortRegistrationArg = NULL;
    fSyncArg = NULL;
    fConditionnal = 0; // Temporary??
}

JackClient::~JackClient()
{
    delete fThread;
}

int JackClient::Close()
{
    JackLog("JackClient::Close ref = %ld\n", GetClientControl()->fRefNum);
    Deactivate();
    int result = -1;
    fChannel->ClientClose(GetClientControl()->fRefNum, &result);
    fChannel->Stop();
    fChannel->Close();
    fSynchroTable[GetClientControl()->fRefNum]->Disconnect();
    return result;
}

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

pthread_t JackClient::GetThreadID()
{
    return fThread->GetThreadID();
}

/*!
\brief
	In ASYNC mode, the server does not synchronize itself on the output drivers, thus it would never "consume" the activations.
	The synchronization primitives for drivers are setup in "flush" mode that to not keep unneeded activations.
	Drivers synchro are setup in "flush" mode if server is ASYNC and NOT freewheel.
*/
void JackClient::SetupDriverSync(bool freewheel)
{
    if (!freewheel && !GetEngineControl()->fSyncMode) {
        JackLog("JackClient::SetupDriverSync driver sem in flush mode\n");
        fSynchroTable[AUDIO_DRIVER_REFNUM]->SetFlush(true);
        fSynchroTable[FREEWHEEL_DRIVER_REFNUM]->SetFlush(true);
        fSynchroTable[LOOPBACK_DRIVER_REFNUM]->SetFlush(true);
    } else {
        JackLog("JackClient::SetupDriverSync driver sem in normal mode\n");
        fSynchroTable[AUDIO_DRIVER_REFNUM]->SetFlush(false);
        fSynchroTable[FREEWHEEL_DRIVER_REFNUM]->SetFlush(false);
        fSynchroTable[LOOPBACK_DRIVER_REFNUM]->SetFlush(false);
    }
}

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

int JackClient::ClientNotifyImp(int refnum, const char* name, int notify, int sync, int value)
{
123
 	return 0;
sletz's avatar
sletz committed
124
125
126
127
128
129
130
131
132
}

int JackClient::ClientNotify(int refnum, const char* name, int notify, int sync, int value)
{
    int res = 0;

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

133
        case kAddClient:
sletz's avatar
sletz committed
134
            res = ClientNotifyImp(refnum, name, notify, sync, value);
135
136
			break;
			
137
	   case kRemoveClient:
138
139
            res = ClientNotifyImp(refnum, name, notify, sync, value);
			break;
140
			
141
		case kActivateClient:
142
143
144
145
			JackLog("JackClient::kActivateClient name = %s ref = %ld \n", name, refnum);
			Init();
			break;
	}
sletz's avatar
sletz committed
146
147
148
149
150
151
152
153

    /*
    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) {
154
		
155
			case kAddClient:
sletz's avatar
sletz committed
156
				JackLog("JackClient::kAddClient fName = %s name = %s\n", GetClientControl()->fName, name);
157
158
159
160
				if (fClientRegistration && strcmp(GetClientControl()->fName, name) != 0)	// Don't call the callback for the registering client itself
					fClientRegistration(name, 1, fClientRegistrationArg);
				break;
			
161
			case kRemoveClient:
sletz's avatar
sletz committed
162
				JackLog("JackClient::kRemoveClient fName = %s name = %s\n", GetClientControl()->fName, name);
163
164
165
				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
166

167
            case kBufferSizeCallback:
sletz's avatar
sletz committed
168
169
170
171
172
                JackLog("JackClient::kBufferSizeCallback buffer_size = %ld\n", value);
                if (fBufferSize)
                    res = fBufferSize(value, fBufferSizeArg);
                break;

173
            case kGraphOrderCallback:
sletz's avatar
sletz committed
174
175
176
177
178
                JackLog("JackClient::kGraphOrderCallback\n");
                if (fGraphOrder)
                    res = fGraphOrder(fGraphOrderArg);
                break;

179
            case kStartFreewheelCallback:
sletz's avatar
sletz committed
180
181
182
183
184
185
186
                JackLog("JackClient::kStartFreewheel\n");
                SetupDriverSync(true);
                fThread->DropRealTime();
                if (fFreewheel)
                    fFreewheel(1, fFreewheelArg);
                break;

187
            case kStopFreewheelCallback:
sletz's avatar
sletz committed
188
189
190
191
192
193
194
                JackLog("JackClient::kStopFreewheel\n");
                SetupDriverSync(false);
                if (fFreewheel)
                    fFreewheel(0, fFreewheelArg);
                fThread->AcquireRealTime();
                break;

195
            case kPortRegistrationOnCallback:
sletz's avatar
sletz committed
196
197
198
199
200
                JackLog("JackClient::kPortRegistrationOn port_index = %ld\n", value);
                if (fPortRegistration)
                    fPortRegistration(value, 1, fPortRegistrationArg);
                break;

201
            case kPortRegistrationOffCallback:
sletz's avatar
sletz committed
202
203
204
205
206
                JackLog("JackClient::kPortRegistrationOff port_index = %ld \n", value);
                if (fPortRegistration)
                    fPortRegistration(value, 0, fPortRegistrationArg);
                break;

207
            case kXRunCallback:
sletz's avatar
sletz committed
208
209
210
211
212
                JackLog("JackClient::kXRunCallback\n");
                if (fXrun)
                    res = fXrun(fXrunArg);
                break;

213
            case kZombifyClient:
214
	            JackLog("JackClient::kZombifyClient name = %s ref = %ld \n", name, refnum);
sletz's avatar
sletz committed
215
216
                ShutDown();
                break;
217
		}
sletz's avatar
sletz committed
218
219
220
221
222
223
224
225
226
227
228
229
230
    }

    return res;
}

/*!
\brief We need to start thread before activating in the server, otherwise the FW driver 
	   connected to the client may not be activated.
*/
int JackClient::Activate()
{
    JackLog("JackClient::Activate \n");
    if (IsActive())
231
232
        return 0;

233
/* TODO : solve WIN32 thread Kill issue
234
235
236
237
238
239
240
#ifdef WIN32
	// Done first so that the RT thread then access an allocated synchro
	if (!fSynchroTable[GetClientControl()->fRefNum]->Connect(GetClientControl()->fName)) {
        jack_error("Cannot ConnectSemaphore %s client", GetClientControl()->fName);
        return -1;
    }
#endif
241
*/
242
243
244

	if (StartThread() < 0)
        return -1;
sletz's avatar
sletz committed
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

    int result = -1;
    fChannel->ClientActivate(GetClientControl()->fRefNum, &result);
    if (result < 0)
        return result;

    if (fSync != NULL)		/* If a SyncCallback is pending... */
        SetSyncCallback(fSync, fSyncArg);

    if (fTimebase != NULL)	/* If a TimebaseCallback is pending... */
        SetTimebaseCallback(fConditionnal, fTimebase, fTimebaseArg);

    GetClientControl()->fActive = true;
    return 0;
}

/*!
\brief Need to stop thread after deactivating in the server.
*/
int JackClient::Deactivate()
{
    JackLog("JackClient::Deactivate \n");
    if (!IsActive())
        return 0;

    GetClientControl()->fActive = false;
    int result = -1;
    fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);

    JackLog("JackClient::Deactivate res = %ld \n", result);
    // We need to wait for the new engine cycle before stopping the RT thread, but this is done by ClientDeactivate
276
277

/* TODO : solve WIN32 thread Kill issue    
278
279
280
281
282
283
#ifdef WIN32
	fSynchroTable[GetClientControl()->fRefNum]->Disconnect();
	fThread->Stop();
#else
	fThread->Kill();
#endif
284
285
*/
	fThread->Kill();
sletz's avatar
sletz committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    return result;
}

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

bool JackClient::CallProcessCallback()
{
    return (fProcess == NULL) ? true : (fProcess(GetEngineControl()->fBufferSize, fProcessArg) == 0);
}

/*!
\brief Called once when the thread starts.
*/
bool JackClient::Init()
{
    if (fInit) {
        JackLog("JackClient::Init calling client thread init callback\n");
305
		fInit(fInitArg);
sletz's avatar
sletz committed
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
    }
    return true;
}

int JackClient::StartThread()
{
    JackLog("JackClient::StartThread : period = %ld computation = %ld constraint = %ld\n",
            long(int64_t(GetEngineControl()->fPeriod) / 1000.0f),
            long(int64_t(GetEngineControl()->fComputation) / 1000.0f),
            long(int64_t(GetEngineControl()->fConstraint) / 1000.0f));

    // Will do "something" on OSX only...
    fThread->SetParams(GetEngineControl()->fPeriod, GetEngineControl()->fComputation, GetEngineControl()->fConstraint);

    if (fThread->Start() < 0) {
        jack_error("Start thread error");
        return -1;
    }

    if (GetEngineControl()->fRealTime) {
        if (fThread->AcquireRealTime(GetEngineControl()->fPriority - 1) < 0) {
            jack_error("AcquireRealTime error");
        }
    }

    return 0;
}

/*!
\brief RT thread.
*/
bool JackClient::Execute()
{
    // Suspend itself: wait on the input synchro
    if (GetGraphManager()->SuspendRefNum(GetClientControl(), fSynchroTable, 0x7FFFFFFF) < 0) {
        jack_error("SuspendRefNum error");
        goto error;
    }

    // Process call
    if (IsActive()) {
        CallSyncCallback();
sletz's avatar
sletz committed
348
        bool res = CallProcessCallback();  
sletz's avatar
sletz committed
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
        CallTimebaseCallback();
        if (!res)
            goto end;
    } else {
        JackLog("Process called for an inactive client\n");
        // Happens if client is still not activated (connected to the FW)
        // or still runs while being desactivated by the server
    }

    // Resume: signal output clients connected to the running client
    if (GetGraphManager()->ResumeRefNum(GetClientControl(), fSynchroTable) < 0) {
        jack_error("ResumeRefNum error");
    }

    return true;

end:
    JackLog("JackClient::Execute end name = %s\n", GetClientControl()->fName);

    // Continue graph execution for this cycle
    if (GetGraphManager()->ResumeRefNum(GetClientControl(), fSynchroTable) < 0) {
        jack_error("ResumeRefNum error");
    }

    // Hum... not sure about this, the following "close" code is called in the RT thread...
    int result;
    fThread->DropRealTime();
376
	GetClientControl()->fActive = false;
sletz's avatar
sletz committed
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
411
412
413
414
415
416
    fChannel->ClientDeactivate(GetClientControl()->fRefNum, &result);
    return false;

error:
    jack_error("JackClient::Execute error name = %s", GetClientControl()->fName);
    // Hum... not sure about this, the following "close" code is called in the RT thread...
    fThread->DropRealTime();
    ShutDown();
    return false;
}

//-----------------
// Port management
//-----------------

int JackClient::PortRegister(const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size)
{
    // Check port name length
    string port_name_str = string(port_name);
    if (port_name_str.size() == 0) {
        jack_error("port_name is empty.");
        return 0; // Means failure here...
    }

    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"
                   "Please use %lu characters or less.",
                   GetClientControl()->fName,
                   port_name,
                   JACK_PORT_NAME_SIZE - 1);
        return 0; // Means failure here...
    }

    // Check if port name already exists
    if (GetGraphManager()->GetPort(name.c_str()) != NO_PORT) {
        jack_error("port_name \"%s\" already exists.", port_name);
        return 0; // Means failure here...
    }

sletz's avatar
sletz committed
417
    JackLog("JackClient::PortRegister ref = %ld  name = %s type = %s\n", GetClientControl()->fRefNum, name.c_str(), port_type);
sletz's avatar
sletz committed
418
419
420

    int result = -1;
    jack_port_id_t port_index = NO_PORT;
sletz's avatar
sletz committed
421
    fChannel->PortRegister(GetClientControl()->fRefNum, name.c_str(), port_type, flags, buffer_size, &port_index, &result);
sletz's avatar
sletz committed
422
423
424
425
426
427
428
429
430
431
432
433
434
    JackLog("JackClient::PortRegister port_index = %ld \n", port_index);

    if (result == 0) {
        fPortList.push_back(port_index);
        return port_index;
    } else {
        return 0;
    }
}

int JackClient::PortUnRegister(jack_port_id_t port_index)
{
    JackLog("JackClient::PortUnRegister port_index = %ld\n", port_index);
sletz's avatar
sletz committed
435
  	list<jack_port_id_t>::iterator it = find(fPortList.begin(), fPortList.end(), port_index);
sletz's avatar
sletz committed
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489

    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)
{
    JackLog("JackClient::Connect src = %s dst = %s\n", src, dst);
    int result = -1;
    fChannel->PortConnect(GetClientControl()->fRefNum, src, dst, &result);
    return result;
}

int JackClient::PortDisconnect(const char* src, const char* dst)
{
    JackLog("JackClient::Disconnect src = %s dst = %s\n", src, dst);
    int result = -1;
    fChannel->PortDisconnect(GetClientControl()->fRefNum, src, dst, &result);
    return result;
}

int JackClient::PortConnect(jack_port_id_t src, jack_port_id_t dst)
{
    JackLog("JackClient::PortConnect src = %ld dst = %ld\n", src, dst);
    int result = -1;
    fChannel->PortConnect(GetClientControl()->fRefNum, src, dst, &result);
    return result;
}

int JackClient::PortDisconnect(jack_port_id_t src)
{
    JackLog("JackClient::PortDisconnect src = %ld\n", src);
    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();
}

//--------------------
// Context management
//--------------------

490
int JackClient::SetBufferSize(jack_nframes_t buffer_size)
sletz's avatar
sletz committed
491
492
{
    int result = -1;
493
    fChannel->SetBufferSize(buffer_size, &result);
sletz's avatar
sletz committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
    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()
{
    JackLog("ShutDown\n");
    if (fShutdown) {
        GetClientControl()->fActive = false;
        fShutdown(fShutdownArg);
        fShutdown = NULL;
    }
}

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

int JackClient::ReleaseTimebase()
{
    int result = -1;
    fChannel->ReleaseTimebase(GetClientControl()->fRefNum, &result);
    if (result == 0) {
        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)
{
    if (IsActive())
        GetClientControl()->fTransportState = (sync_callback == NULL) ? JackTransportStopped : JackTransportSynching;
    fSync = sync_callback;
    fSyncArg = arg;
    return 0;
}

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

/* Call the server if the client is active, otherwise keeps the arguments */
int JackClient::SetTimebaseCallback(int conditional, JackTimebaseCallback timebase_callback, void* arg)
{
    if (IsActive()) {
        int result = -1;
        fChannel->SetTimebaseCallback(GetClientControl()->fRefNum, conditional, &result);
        JackLog("SetTimebaseCallback result = %ld\n", result);
        if (result == 0) {
            fTimebase = timebase_callback;
            fTimebaseArg = arg;
        } else {
            fTimebase = NULL;
            fTimebaseArg = NULL;
        }
        JackLog("SetTimebaseCallback OK result = %ld\n", result);
        return result;
    } else {
        fTimebase = timebase_callback;
        fTimebaseArg = arg;
        fConditionnal = conditional;
        return 0;
    }
}

// Must be RT safe
int JackClient::RequestNewPos(jack_position_t* pos)
{
    JackTransportEngine& transport = GetEngineControl()->fTransport;
    jack_position_t* request = transport.WriteNextStateStart(2);
    pos->unique_1 = pos->unique_2 = transport.GenerateUniqueID();
    JackTransportEngine::TransportCopyPosition(pos, request);
    JackLog("RequestNewPos pos = %ld\n", pos->frame);
    transport.WriteNextStateStop(2);
    return 0;
}

int JackClient::TransportLocate(jack_nframes_t frame)
{
    jack_position_t pos;
    pos.frame = frame;
    pos.valid = (jack_position_bits_t)0;
    JackLog("TransportLocate pos = %ld\n", pos.frame);
    return RequestNewPos(&pos);
}

int JackClient::TransportReposition(jack_position_t* pos)
{
    jack_position_t tmp = *pos;
    JackLog("TransportReposition pos = %ld\n", pos->frame);
    return (tmp.valid & ~JACK_POSITION_MASK) ? EINVAL : RequestNewPos(&tmp);
}

jack_transport_state_t JackClient::TransportQuery(jack_position_t* pos)
{
    if (pos)
        GetEngineControl()->fTransport.ReadCurrentPos(pos);
    return GetEngineControl()->fTransport.GetState();
}

jack_nframes_t JackClient::GetCurrentTransportFrame()
{
    jack_position_t pos;
    jack_transport_state_t state = TransportQuery(&pos);

    if (state == JackTransportRolling) {
        float usecs = GetMicroSeconds() - pos.usecs;
        jack_nframes_t elapsed = (jack_nframes_t)floor((((float) pos.frame_rate) / 1000000.0f) * usecs);
        return pos.frame + elapsed;
    } else {
        return pos.frame;
    }
}

// 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
// TODO check concurency with SetSyncCallback

void JackClient::CallSyncCallback()
{
    JackTransportEngine& transport = GetEngineControl()->fTransport;
    jack_position_t* cur_pos = transport.ReadCurrentState();
    jack_transport_state_t transport_state = transport.GetState();

    switch (transport_state) {

        case JackTransportStarting:  // Starting...
            if (fSync == NULL) {
                GetClientControl()->fTransportState = JackTransportRolling;
            } else if (GetClientControl()->fTransportState == JackTransportStarting) {
                if (fSync(transport_state, cur_pos, fSyncArg))
                    GetClientControl()->fTransportState = JackTransportRolling;
            }
            break;

        case JackTransportRolling:
            if (fSync != NULL && GetClientControl()->fTransportState == JackTransportStarting) { // Client still not ready
                if (fSync(transport_state, cur_pos, fSyncArg))
                    GetClientControl()->fTransportState = JackTransportRolling;
            }
            break;

        case JackTransportSynching:
            // New pos when transport engine is stopped...
            if (fSync != NULL) {
                fSync(JackTransportStopped, cur_pos, fSyncArg);
                GetClientControl()->fTransportState = JackTransportStopped;
            }
            break;

        default:
            break;
    }
}

void JackClient::CallTimebaseCallback()
{
    JackTransportEngine& transport = GetEngineControl()->fTransport;

    if (fTimebase != NULL && fTimebaseArg != NULL && GetClientControl()->fRefNum == transport.GetTimebaseMaster()) {

        jack_transport_state_t transport_state = transport.GetState();
        jack_position_t* cur_pos = transport.WriteNextStateStart(1);

        switch (transport_state) {

            case JackTransportRolling:
                fTimebase(transport_state, GetEngineControl()->fBufferSize, cur_pos, false, fTimebaseArg);
                break;

            case JackTransportSynching:
                fTimebase(JackTransportStopped, GetEngineControl()->fBufferSize, cur_pos, true, fTimebaseArg);
                break;

            default:
                break;
        }

        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;
    } else {
        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 {
736
		GetClientControl()->fCallback[kXRunCallback] = (callback != NULL);
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
760
761
762
        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)
{
    JackLog("SetGraphOrderCallback \n");

    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
763
		GetClientControl()->fCallback[kGraphOrderCallback] = (callback != NULL);
sletz's avatar
sletz committed
764
765
766
767
768
769
770
771
772
773
774
775
        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 {
776
		GetClientControl()->fCallback[kBufferSizeCallback] = (callback != NULL);
sletz's avatar
sletz committed
777
778
779
780
781
782
        fBufferSizeArg = arg;
        fBufferSize = callback;
        return 0;
    }
}

783
784
785
786
787
788
int JackClient::SetClientRegistrationCallback(JackClientRegistrationCallback callback, void* arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
789
790
		// kAddClient and kRemoveClient notifications must be delivered by the server in any case
		fClientRegistrationArg = arg;
791
792
793
794
795
        fClientRegistration = callback;
        return 0;
    }
}

sletz's avatar
sletz committed
796
797
798
799
800
801
int JackClient::SetFreewheelCallback(JackFreewheelCallback callback, void *arg)
{
    if (IsActive()) {
        jack_error("You cannot set callbacks on an active client");
        return -1;
    } else {
802
803
		GetClientControl()->fCallback[kStartFreewheelCallback] = (callback != NULL);
		GetClientControl()->fCallback[kStopFreewheelCallback] = (callback != NULL);
sletz's avatar
sletz committed
804
805
806
807
808
809
810
811
812
813
814
815
        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 {
816
817
		GetClientControl()->fCallback[kPortRegistrationOnCallback] = (callback != NULL);
		GetClientControl()->fCallback[kPortRegistrationOffCallback] = (callback != NULL);
sletz's avatar
sletz committed
818
819
820
821
822
823
        fPortRegistrationArg = arg;
        fPortRegistration = callback;
        return 0;
    }
}

824
825
826
827
828
829
//------------------
// Internal clients
//------------------

char* JackClient::GetInternalClientName(int ref)
{
830
831
832
833
834
835
836
837
838
839
840
	char name_res[JACK_CLIENT_NAME_SIZE]; 
	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;
	}
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
}

int JackClient::InternalClientHandle(const char* client_name, jack_status_t* status)
{
	int int_ref, result = -1;
	fChannel->InternalClientHandle(GetClientControl()->fRefNum, client_name, (int*)status, &int_ref, &result);
	return int_ref;
}

int JackClient::InternalClientLoad(const char* client_name, jack_options_t options, jack_status_t* status, jack_varargs_t* va)
{
	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;
	}

	if (va->load_name && (strlen(va->load_name) >= PATH_MAX)) {
		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;
}

void JackClient::InternalClientUnload(int ref, jack_status_t* status)
{
	int result = -1;
	fChannel->InternalClientUnload(GetClientControl()->fRefNum, ref, (int*)status, &result);
}


sletz's avatar
sletz committed
889
890
} // end of namespace