forked from spatialaudio/jackclient-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jack.py
2650 lines (2105 loc) · 92.6 KB
/
jack.py
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
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
490
491
492
493
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
736
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2014-2015 Matthias Geier
#
# 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.
"""JACK Client for Python.
http://jackclient-python.rtfd.org/
"""
__version__ = "0.4.1"
import errno as _errno
import platform as _platform
from cffi import FFI as _FFI
import warnings as _warnings
_ffi = _FFI()
_ffi.cdef("""
/* types.h */
typedef uint64_t jack_uuid_t;
typedef uint32_t jack_nframes_t;
typedef uint64_t jack_time_t;
typedef struct _jack_port jack_port_t;
typedef struct _jack_client jack_client_t;
typedef uint32_t jack_port_id_t;
typedef uint32_t jack_port_type_id_t;
enum JackOptions {
JackNullOption = 0x00,
JackNoStartServer = 0x01,
JackUseExactName = 0x02,
JackServerName = 0x04,
JackLoadName = 0x08,
JackLoadInit = 0x10,
JackSessionID = 0x20
};
typedef enum JackOptions jack_options_t;
enum JackStatus {
JackFailure = 0x01,
JackInvalidOption = 0x02,
JackNameNotUnique = 0x04,
JackServerStarted = 0x08,
JackServerFailed = 0x10,
JackServerError = 0x20,
JackNoSuchClient = 0x40,
JackLoadFailure = 0x80,
JackInitFailure = 0x100,
JackShmFailure = 0x200,
JackVersionError = 0x400,
JackBackendError = 0x800,
JackClientZombie = 0x1000
};
typedef enum JackStatus jack_status_t;
typedef int (*JackProcessCallback)(jack_nframes_t nframes, void* arg);
typedef int (*JackGraphOrderCallback)(void* arg);
typedef int (*JackXRunCallback)(void* arg);
typedef int (*JackBufferSizeCallback)(jack_nframes_t nframes, void* arg);
typedef int (*JackSampleRateCallback)(jack_nframes_t nframes, void* arg);
typedef void (*JackPortRegistrationCallback)(jack_port_id_t port, int /* register */, void* arg);
typedef void (*JackClientRegistrationCallback)(const char* name, int /* register */, void* arg);
typedef void (*JackPortConnectCallback)(jack_port_id_t a, jack_port_id_t b, int connect, void* arg);
typedef int (*JackPortRenameCallback)(jack_port_id_t port, const char* old_name, const char* new_name, void* arg);
typedef void (*JackFreewheelCallback)(int starting, void* arg);
/* not implemented: JackShutdownCallback (only JackInfoShutdownCallback is used) */
typedef void (*JackInfoShutdownCallback)(jack_status_t code, const char* reason, void* arg);
/* JACK_DEFAULT_AUDIO_TYPE: see _AUDIO */
/* JACK_DEFAULT_MIDI_TYPE: see _MIDI */
/* not implemented: jack_default_audio_sample_t (hard-coded as float) */
enum JackPortFlags {
JackPortIsInput = 0x1,
JackPortIsOutput = 0x2,
JackPortIsPhysical = 0x4,
JackPortCanMonitor = 0x8,
JackPortIsTerminal = 0x10,
};
typedef enum {
JackTransportStopped = 0,
JackTransportRolling = 1,
JackTransportLooping = 2, /* deprecated */
JackTransportStarting = 3,
JackTransportNetStarting = 4,
} jack_transport_state_t;
typedef uint64_t jack_unique_t;
typedef enum {
JackPositionBBT = 0x10,
JackPositionTimecode = 0x20,
JackBBTFrameOffset = 0x40,
JackAudioVideoRatio = 0x80,
JackVideoFrameOffset = 0x100,
} jack_position_bits_t;
/* _jack_position: see below in "packed" section */
typedef struct _jack_position jack_position_t;
typedef void (*JackTimebaseCallback)(jack_transport_state_t state, jack_nframes_t nframes, jack_position_t *pos, int new_pos, void *arg);
/* deprecated: jack_transport_bits_t */
/* deprecated: jack_transport_info_t */
/* jack.h */
void jack_get_version(int* major_ptr, int* minor_ptr, int* micro_ptr, int* proto_ptr);
const char* jack_get_version_string();
jack_client_t* jack_client_open(const char* client_name, jack_options_t options, jack_status_t* status, ...);
/* deprecated: jack_client_new */
int jack_client_close(jack_client_t* client);
int jack_client_name_size(void);
char* jack_get_client_name(jack_client_t* client);
char* jack_get_uuid_for_client_name(jack_client_t* client, const char* client_name);
char* jack_get_client_name_by_uuid(jack_client_t* client, const char* client_uuid);
/* deprecated: jack_internal_client_new */
/* deprecated: jack_internal_client_close */
int jack_activate(jack_client_t* client);
int jack_deactivate(jack_client_t* client);
int jack_get_client_pid(const char* name);
/* not implemented: jack_client_thread_id */
int jack_is_realtime(jack_client_t* client);
/* deprecated: jack_thread_wait */
/* not implemented: jack_cycle_wait */
/* not implemented: jack_cycle_signal */
/* not implemented: jack_set_process_thread */
/* not implemented: jack_set_thread_init_callback */
/* not implemented (jack_on_info_shutdown is used): jack_on_shutdown */
void jack_on_info_shutdown(jack_client_t* client, JackInfoShutdownCallback shutdown_callback, void* arg);
int jack_set_process_callback(jack_client_t* client, JackProcessCallback process_callback, void* arg);
int jack_set_freewheel_callback(jack_client_t* client, JackFreewheelCallback freewheel_callback, void* arg);
int jack_set_buffer_size_callback(jack_client_t* client, JackBufferSizeCallback bufsize_callback, void* arg);
int jack_set_sample_rate_callback(jack_client_t* client, JackSampleRateCallback srate_callback, void* arg);
int jack_set_client_registration_callback(jack_client_t* client, JackClientRegistrationCallback registration_callback, void* arg);
int jack_set_port_registration_callback(jack_client_t* client, JackPortRegistrationCallback registration_callback, void* arg);
int jack_set_port_connect_callback(jack_client_t* client, JackPortConnectCallback connect_callback, void* arg);
int jack_set_port_rename_callback(jack_client_t* client, JackPortRenameCallback rename_callback, void* arg);
int jack_set_graph_order_callback(jack_client_t* client, JackGraphOrderCallback graph_callback, void*);
int jack_set_xrun_callback(jack_client_t* client, JackXRunCallback xrun_callback, void* arg);
/* TODO: jack_set_latency_callback */
int jack_set_freewheel(jack_client_t* client, int onoff);
int jack_set_buffer_size(jack_client_t* client, jack_nframes_t nframes);
jack_nframes_t jack_get_sample_rate(jack_client_t*);
jack_nframes_t jack_get_buffer_size(jack_client_t*);
/* deprecated: jack_engine_takeover_timebase */
float jack_cpu_load(jack_client_t* client);
jack_port_t* jack_port_register(jack_client_t* client, const char* port_name, const char* port_type, unsigned long flags, unsigned long buffer_size);
int jack_port_unregister(jack_client_t* client, jack_port_t* port);
void* jack_port_get_buffer(jack_port_t* port, jack_nframes_t);
jack_uuid_t jack_port_uuid(const jack_port_t* port);
const char* jack_port_name(const jack_port_t* port);
const char* jack_port_short_name(const jack_port_t* port);
int jack_port_flags(const jack_port_t* port);
const char* jack_port_type(const jack_port_t* port);
/* not implemented: jack_port_type_id */
int jack_port_is_mine(const jack_client_t* client, const jack_port_t* port);
int jack_port_connected(const jack_port_t* port);
int jack_port_connected_to(const jack_port_t* port, const char* port_name);
const char** jack_port_get_connections(const jack_port_t* port);
const char** jack_port_get_all_connections(const jack_client_t* client, const jack_port_t* port);
/* deprecated: jack_port_tie */
/* deprecated: jack_port_untie */
int jack_port_set_name(jack_port_t* port, const char* port_name);
/* TODO: jack_port_set_alias */
/* TODO: jack_port_unset_alias */
/* TODO: jack_port_get_aliases */
int jack_port_request_monitor(jack_port_t *port, int onoff);
/* not implemented (use jack_port_request_monitor): jack_port_request_monitor_by_name */
/* TODO: jack_port_ensure_monitor */
/* TODO: jack_port_monitoring_input */
int jack_connect(jack_client_t* client, const char* source_port, const char* destination_port);
int jack_disconnect(jack_client_t* client, const char* source_port, const char* destination_port);
int jack_port_disconnect(jack_client_t* client, jack_port_t* port);
int jack_port_name_size(void);
/* not implemented: jack_port_type_size */
/* not implemented: jack_port_type_get_buffer_size */
/* TODO: jack_port_set_latency */
/* TODO: jack_port_get_latency_range */
/* TODO: jack_port_set_latency_range */
/* TODO: jack_recompute_total_latencies */
/* TODO: jack_port_get_latency */
/* TODO: jack_port_get_total_latency */
/* TODO: jack_recompute_total_latency */
const char** jack_get_ports(jack_client_t* client, const char* port_name_pattern, const char* type_name_pattern, unsigned long flags);
jack_port_t* jack_port_by_name(jack_client_t* client, const char* port_name);
jack_port_t* jack_port_by_id(jack_client_t* client, jack_port_id_t port_id);
jack_nframes_t jack_frames_since_cycle_start(const jack_client_t*);
jack_nframes_t jack_frame_time(const jack_client_t*);
jack_nframes_t jack_last_frame_time(const jack_client_t* client);
/* TODO: jack_get_cycle_times */
/* TODO: jack_frames_to_time */
/* TODO: jack_time_to_frames */
/* TODO: jack_get_time */
void jack_set_error_function(void (*func)(const char*));
void jack_set_info_function(void (*func)(const char*));
void jack_free(void* ptr);
/* ringbuffer.h */
typedef struct {
char* buf;
size_t len;
} jack_ringbuffer_data_t;
typedef struct {
char* buf;
volatile size_t write_ptr;
volatile size_t read_ptr;
size_t size;
size_t size_mask;
int mlocked;
} jack_ringbuffer_t;
jack_ringbuffer_t* jack_ringbuffer_create(size_t sz);
void jack_ringbuffer_free(jack_ringbuffer_t* rb);
void jack_ringbuffer_get_read_vector(const jack_ringbuffer_t* rb, jack_ringbuffer_data_t* vec);
void jack_ringbuffer_get_write_vector(const jack_ringbuffer_t* rb, jack_ringbuffer_data_t* vec);
size_t jack_ringbuffer_read(jack_ringbuffer_t* rb, char* dest, size_t cnt);
size_t jack_ringbuffer_peek(jack_ringbuffer_t* rb, char* dest, size_t cnt);
void jack_ringbuffer_read_advance(jack_ringbuffer_t* rb, size_t cnt);
size_t jack_ringbuffer_read_space(const jack_ringbuffer_t* rb);
int jack_ringbuffer_mlock(jack_ringbuffer_t* rb);
void jack_ringbuffer_reset(jack_ringbuffer_t* rb);
void jack_ringbuffer_reset_size (jack_ringbuffer_t* rb, size_t sz);
/* Note: "char*" was changed to "unsigned char*" to support iterables of int */
size_t jack_ringbuffer_write(jack_ringbuffer_t* rb, const unsigned char* src, size_t cnt);
void jack_ringbuffer_write_advance(jack_ringbuffer_t* rb, size_t cnt);
size_t jack_ringbuffer_write_space(const jack_ringbuffer_t* rb);
/* transport.h */
/* TODO: jack_release_timebase */
/* TODO: jack_set_sync_callback */
/* TODO: jack_set_sync_timeout */
int jack_set_timebase_callback(jack_client_t* client, int conditional, JackTimebaseCallback timebase_callback, void* arg);
int jack_transport_locate(jack_client_t* client, jack_nframes_t frame);
jack_transport_state_t jack_transport_query(const jack_client_t* client, jack_position_t* pos);
jack_nframes_t jack_get_current_transport_frame(const jack_client_t* client);
int jack_transport_reposition(jack_client_t* client, const jack_position_t* pos);
void jack_transport_start(jack_client_t* client);
void jack_transport_stop(jack_client_t* client);
/* deprecated: jack_get_transport_info */
/* deprecated: jack_set_transport_info */
/* statistics.h */
float jack_get_xrun_delayed_usecs(jack_client_t* client);
/* midiport.h */
typedef unsigned char jack_midi_data_t;
typedef struct _jack_midi_event {
jack_nframes_t time;
size_t size;
jack_midi_data_t* buffer;
} jack_midi_event_t;
uint32_t jack_midi_get_event_count(void* port_buffer);
int jack_midi_event_get(jack_midi_event_t* event, void* port_buffer, uint32_t event_index);
void jack_midi_clear_buffer(void* port_buffer);
/* not implemented: jack_midi_reset_buffer */
size_t jack_midi_max_event_size(void* port_buffer);
jack_midi_data_t* jack_midi_event_reserve(void* port_buffer, jack_nframes_t time, size_t data_size);
int jack_midi_event_write(void* port_buffer, jack_nframes_t time, const jack_midi_data_t* data, size_t data_size);
uint32_t jack_midi_get_lost_event_count(void* port_buffer);
""")
# Packed structure
_ffi.cdef("""
struct _jack_position {
jack_unique_t unique_1;
jack_time_t usecs;
jack_nframes_t frame_rate;
jack_nframes_t frame;
jack_position_bits_t valid;
int32_t bar;
int32_t beat;
int32_t tick;
double bar_start_tick;
float beats_per_bar;
float beat_type;
double ticks_per_beat;
double beats_per_minute;
double frame_time;
double next_time;
jack_nframes_t bbt_offset;
float audio_frames_per_video_frame;
jack_nframes_t video_offset;
int32_t padding[7];
jack_unique_t unique_2;
};
""", packed=True)
if _platform.system() == 'Windows':
if _platform.architecture()[0] == '64bit':
_lib = _ffi.dlopen("libjack64")
else:
_lib = _ffi.dlopen("libjack")
else:
_lib = _ffi.dlopen("jack")
_AUDIO = b"32 bit float mono audio"
_MIDI = b"8 bit raw midi"
STOPPED = _lib.JackTransportStopped
"""Transport halted."""
ROLLING = _lib.JackTransportRolling
"""Transport playing."""
STARTING = _lib.JackTransportStarting
"""Waiting for sync ready."""
NETSTARTING = _lib.JackTransportNetStarting
"""Waiting for sync ready on the network."""
_SUCCESS = 0
_FAILURE = 1
class Client(object):
"""A client that can connect to the JACK audio server."""
def __init__(self, name, use_exact_name=False, no_start_server=False,
servername=None, session_id=None):
"""Create a new JACK client.
A client object is a *context manager*, i.e. it can be used in a
*with statement* to automatically call :meth:`activate` in the
beginning of the statement and :meth:`deactivate` and
:meth:`close` on exit.
Parameters
----------
name : str
The desired client name of at most :func:`client_name_size`
characters. The name scope is local to each server.
Unless forbidden by the `use_exact_name` option, the server
will modify this name to create a unique variant, if needed.
Other Parameters
----------------
use_exact_name : bool
Whether an error should be raised if `name` is not unique.
See :attr:`Status.name_not_unique`.
no_start_server : bool
Do not automatically start the JACK server when it is not
already running. This option is always selected if
``JACK_NO_START_SERVER`` is defined in the calling process
environment.
servername : str
Selects from among several possible concurrent server
instances.
Server names are unique to each user. If unspecified, use
``"default"`` unless ``JACK_DEFAULT_SERVER`` is defined in
the process environment.
session_id : str
Pass a SessionID Token. This allows the sessionmanager to
identify the client again.
"""
status = _ffi.new("jack_status_t*")
options = _lib.JackNullOption
optargs = []
if use_exact_name:
options |= _lib.JackUseExactName
if no_start_server:
options |= _lib.JackNoStartServer
if servername:
options |= _lib.JackServerName
optargs.append(_ffi.new("char[]", servername.encode()))
if session_id:
options |= _lib.JackSessionID
optargs.append(_ffi.new("char[]", session_id.encode()))
self._ptr = _lib.jack_client_open(name.encode(), options, status,
*optargs)
self._status = Status(status[0])
if not self._ptr:
raise JackError(str(self.status))
self._inports = Ports(self, _AUDIO, _lib.JackPortIsInput)
self._outports = Ports(self, _AUDIO, _lib.JackPortIsOutput)
self._midi_inports = Ports(self, _MIDI, _lib.JackPortIsInput)
self._midi_outports = Ports(self, _MIDI, _lib.JackPortIsOutput)
self._keepalive = []
self._position = _ffi.new("jack_position_t*")
# Avoid confusion if something goes wrong before opening the client:
_ptr = _ffi.NULL
def __enter__(self):
self.activate()
return self
def __exit__(self, *args):
self.deactivate()
self.close()
def __del__(self):
"""Close JACK client on garbage collection."""
self.close()
@property
def name(self):
"""The name of the JACK client (read-only)."""
return _ffi.string(_lib.jack_get_client_name(self._ptr)).decode()
@property
def samplerate(self):
"""The sample rate of the JACK system (read-only)."""
return _lib.jack_get_sample_rate(self._ptr)
@property
def blocksize(self):
"""The JACK block size (must be a power of two).
The current maximum size that will ever be passed to the process
callback. It should only be queried *before* :meth:`activate`
has been called. This size may change, clients that depend on
it must register a callback with :meth:`set_blocksize_callback`
so they will be notified if it does.
Changing the blocksize stops the JACK engine process cycle, then
calls all registered callback functions (see
:meth:`set_blocksize_callback`) before restarting the process
cycle. This will cause a gap in the audio flow, so it should
only be done at appropriate stopping points.
"""
return _lib.jack_get_buffer_size(self._ptr)
@blocksize.setter
def blocksize(self, blocksize):
_check(_lib.jack_set_buffer_size(self._ptr, blocksize),
"Error setting JACK blocksize")
@property
def status(self):
"""JACK client status. See :class:`Status`."""
return self._status
@property
def realtime(self):
"""Whether JACK is running with ``-R`` (``--realtime``)."""
return bool(_lib.jack_is_realtime(self._ptr))
@property
def frames_since_cycle_start(self):
"""Time since start of audio block.
The estimated time in frames that has passed since the JACK
server began the current process cycle.
"""
return _lib.jack_frames_since_cycle_start(self._ptr)
@property
def frame_time(self):
"""The estimated current time in frames.
This is intended for use in other threads (not the process
callback). The return value can be compared with the value of
:attr:`last_frame_time` to relate time in other threads to JACK
time.
"""
return _lib.jack_frame_time(self._ptr)
@property
def last_frame_time(self):
"""The precise time at the start of the current process cycle.
This may only be used from the process callback (see
:meth:`set_process_callback`), and can be used to interpret
timestamps generated by :attr:`frame_time` in other threads with
respect to the current process cycle.
This is the only jack time function that returns exact time:
when used during the process callback it always returns the same
value (until the next process callback, where it will return
that value + :attr:`blocksize`, etc). The return value is
guaranteed to be monotonic and linear in this fashion unless an
xrun occurs (see :meth:`set_xrun_callback`). If an xrun occurs,
clients must check this value again, as time may have advanced
in a non-linear way (e.g. cycles may have been skipped).
"""
return _lib.jack_last_frame_time(self._ptr)
@property
def inports(self):
"""A list of audio input :class:`Ports`.
New ports can be created and added to this list with the
:meth:`~Ports.register` method.
When :meth:`~OwnPort.unregister` is called on one of the items
in this list, this port is removed from the list.
The :meth:`~Ports.clear` method can be used to unregister all
audio input ports at once.
See Also
--------
Ports, OwnPort
"""
return self._inports
@property
def outports(self):
"""A list of audio output :class:`Ports`.
New ports can be created and added to this list with the
:meth:`~Ports.register` method.
When :meth:`~OwnPort.unregister` is called on one of the items
in this list, this port is removed from the list.
The :meth:`~Ports.clear` method can be used to unregister all
audio output ports at once.
See Also
--------
Ports, OwnPort
"""
return self._outports
@property
def midi_inports(self):
"""A list of MIDI input :class:`Ports`.
New MIDI ports can be created and added to this list with the
:meth:`~Ports.register` method.
When :meth:`~OwnPort.unregister` is called on one of the
items in this list, this port is removed from the list.
The :meth:`~Ports.clear` method can be used to unregister all
MIDI input ports at once.
See Also
--------
Ports, OwnMidiPort
"""
return self._midi_inports
@property
def midi_outports(self):
"""A list of MIDI output :class:`Ports`.
New MIDI ports can be created and added to this list with the
:meth:`~Ports.register` method.
When :meth:`~OwnPort.unregister` is called on one of the
items in this list, this port is removed from the list.
The :meth:`~Ports.clear` method can be used to unregister all
MIDI output ports at once.
See Also
--------
Ports, OwnMidiPort
"""
return self._midi_outports
def owns(self, port):
"""Check if a given port belongs to `self`.
Parameters
----------
port : str or Port
Full port name or :class:`Port`, :class:`MidiPort`,
:class:`OwnPort` or :class:`OwnMidiPort` object.
"""
port = self._get_port_ptr(port)
return bool(_lib.jack_port_is_mine(self._ptr, port))
def activate(self):
"""Activate JACK client.
Tell the JACK server that the program is ready to start
processing audio.
"""
_check(_lib.jack_activate(self._ptr), "Error activating JACK client")
def deactivate(self, ignore_errors=True):
"""De-activate JACK client.
Tell the JACK server to remove `self` from the process graph.
Also, disconnect all ports belonging to it, since inactive
clients have no port connections.
"""
err = _lib.jack_deactivate(self._ptr)
if not ignore_errors:
_check(err, "Error deactivating JACK client")
def cpu_load(self):
"""Return the current CPU load estimated by JACK.
This is a running average of the time it takes to execute a full
process cycle for all clients as a percentage of the real time
available per cycle determined by the :attr:`blocksize` and
:attr:`samplerate`.
"""
return _lib.jack_cpu_load(self._ptr)
def close(self, ignore_errors=True):
"""Close the JACK client."""
if self._ptr:
err = _lib.jack_client_close(self._ptr)
self._ptr = _ffi.NULL
if not ignore_errors:
_check(err, "Error closing JACK client")
def connect(self, source, destination):
"""Establish a connection between two ports.
When a connection exists, data written to the source port will
be available to be read at the destination port.
Audio ports can obviously not be connected with MIDI ports.
Parameters
----------
source : str or Port
One end of the connection. Must be an output port.
destination : str or Port
The other end of the connection. Must be an input port.
See Also
--------
OwnPort.connect
"""
if isinstance(source, Port):
source = source.name
if isinstance(destination, Port):
destination = destination.name
err = _lib.jack_connect(self._ptr, source.encode(),
destination.encode())
if err == _errno.EEXIST:
raise JackError("Connection {0!r} -> {1!r} "
"already exists".format(source, destination))
_check(err,
"Error connecting {0!r} -> {1!r}".format(source, destination))
def disconnect(self, source, destination):
"""Remove a connection between two ports.
Parameters
----------
source, destination : str or Port
See :meth:`connect`.
"""
if isinstance(source, Port):
source = source.name
if isinstance(destination, Port):
destination = destination.name
_check(_lib.jack_disconnect(
self._ptr, source.encode(), destination.encode()),
"Couldn't disconnect {0!r} -> {1!r}".format(source, destination))
def transport_start(self):
"""Start JACK transport."""
_lib.jack_transport_start(self._ptr)
def transport_stop(self):
"""Stop JACK transport."""
_lib.jack_transport_stop(self._ptr)
@property
def transport_state(self):
"""JACK transport state.
This is one of :attr:`STOPPED`, :attr:`ROLLING`,
:attr:`STARTING`, :attr:`NETSTARTING`.
See Also
--------
transport_query
"""
return TransportState(_lib.jack_transport_query(self._ptr, _ffi.NULL))
@property
def transport_frame(self):
"""Get/set current JACK transport frame.
Return an estimate of the current transport frame, including any
time elapsed since the last transport positional update.
Assigning a frame number repositions the JACK transport.
"""
return _lib.jack_get_current_transport_frame(self._ptr)
@transport_frame.setter
def transport_frame(self, frame):
_check(_lib.jack_transport_locate(self._ptr, frame),
"Error locating JACK transport")
def transport_locate(self, frame):
"""
.. deprecated:: 0.4.1
Use :attr:`transport_frame` instead
"""
_warnings.warn(
'transport_locate() is deprecated, use transport_frame',
DeprecationWarning)
self.transport_frame = frame
def transport_query(self):
"""Query the current transport state and position.
This is a convenience function that does the same as
:meth:`transport_query_struct` but it only returns the valid
fields in an easy-to-use ``dict``.
Returns
-------
state : TransportState
The transport state can take following values:
:attr:`STOPPED`, :attr:`ROLLING`, :attr:`STARTING` and
:attr:`NETSTARTING`.
position : dict
A dictionary containing only the valid fields of the
structure returned by :meth:`transport_query_struct`.
See Also
--------
:attr:`transport_state`
"""
state, pos = self.transport_query_struct()
return TransportState(state), position2dict(pos)
def transport_query_struct(self):
"""Query the current transport state and position.
This function is realtime-safe, and can be called from any
thread. If called from the process thread, the returned
position corresponds to the first frame of the current cycle and
the state returned is valid for the entire cycle.
Returns
-------
state : int
The transport state can take following values:
:attr:`STOPPED`, :attr:`ROLLING`, :attr:`STARTING` and
:attr:`NETSTARTING`.
position : jack_position_t
See the `JACK transport documentation`__ for the available
fields.
__ http://jackaudio.org/files/docs/html/
structjack__position__t.html
See Also
--------
transport_query, transport_reposition_struct
"""
state = _lib.jack_transport_query(self._ptr, self._position)
return state, self._position
def transport_reposition_struct(self, position):
"""Request a new transport position.
May be called at any time by any client. The new position takes
effect in two process cycles. If there are slow-sync clients
and the transport is already rolling, it will enter the
:attr:`STARTING` state and begin invoking their sync callbacks
(see :meth:`set_sync_callback`) until ready. This function is
realtime-safe.
Parameters
----------
position : jack_position_t
Requested new transport position. This is the same
structure as returned by :meth:`transport_query_struct`.
See Also
--------
transport_query_struct, transport_locate
"""
_check(_lib.jack_transport_reposition(self._ptr, position),
"Error re-positioning transport")
def set_freewheel(self, onoff):
"""Start/Stop JACK's "freewheel" mode.
When in "freewheel" mode, JACK no longer waits for any external
event to begin the start of the next process cycle.
As a result, freewheel mode causes "faster than realtime"
execution of a JACK graph. If possessed, real-time scheduling is
dropped when entering freewheel mode, and if appropriate it is
reacquired when stopping.
IMPORTANT: on systems using capabilities to provide real-time
scheduling (i.e. Linux kernel 2.4), if onoff is zero, this
function must be called from the thread that originally called
:meth:`activate`. This restriction does not apply to other
systems (e.g. Linux kernel 2.6 or OS X).
Parameters
----------
onoff : bool
If ``True``, freewheel mode starts. Otherwise freewheel mode
ends.
See Also
--------
set_freewheel_callback
"""
_check(_lib.jack_set_freewheel(self._ptr, onoff),
"Error setting freewheel mode")
def set_shutdown_callback(self, callback):
"""Register shutdown callback.
Register a function (and optional argument) to be called if and
when the JACK server shuts down the client thread.
The function must be written as if it were an asynchonrous POSIX
signal handler -- use only async-safe functions, and remember
that it is executed from another thread.
A typical function might set a flag or write to a pipe so that
the rest of the application knows that the JACK client thread
has shut down.
.. note:: Clients do not need to call this. It exists only to
help more complex clients understand what is going on. It
should be called before :meth:`activate`.
Parameters
----------
callback : callable
User-supplied function that is called whenever the JACK
daemon is shutdown. It must have this signature::
callback(status: Status, reason: str) -> None
The argument `status` is of type :class:`jack.Status`.
.. note:: The `callback` should typically signal another
thread to correctly finish cleanup by calling
:meth:`close` (since it cannot be called directly in the
context of the thread that calls the shutdown callback).
After server shutdown, the client is *not*
deallocated by JACK, the user (that's you!) is
responsible to properly use :meth:`close` to release
client ressources. Alternatively, the :class:`Client`
object can be used as a *context manager* in a *with
statement*, which takes care of activating, deactivating
and closing the client automatically.
.. note:: Same as with most callbacks, no functions that
interact with the JACK daemon should be used here.
"""
@self._callback("JackInfoShutdownCallback")
def callback_wrapper(code, reason, _):
callback(Status(code), _ffi.string(reason).decode())
_lib.jack_on_info_shutdown(self._ptr, callback_wrapper, _ffi.NULL)
def set_process_callback(self, callback):
"""Register process callback.
Tell the JACK server to call `callback` whenever there is work
be done.
The code in the supplied function must be suitable for real-time
execution. That means that it cannot call functions that might
block for a long time. This includes malloc, free, printf,
pthread_mutex_lock, sleep, wait, poll, select, pthread_join,
pthread_cond_wait, etc, etc.
.. warning:: Most Python interpreters use a `global interpreter
lock (GIL)`__, which violates the above real-time
requirement. Furthermore, Python's `garbage collector`__
might become active at an inconvenient time and block the
process callback for some time.
Because of this, Python is not really suitable for real-time
processing. If you want to implement a *reliable* real-time
audio/MIDI application, you should use a different
programming language, such as C or C++.
If you can live with some random audio drop-outs now and
then, feel free to continue using Python!
__ http://en.wikipedia.org/wiki/Global_Interpreter_Lock
__ http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
.. note:: This function cannot be called while the client is
activated (after :meth:`activate` has been called).
Parameters
----------
callback : callable
User-supplied function that is called by the engine anytime
there is work to be done. It must have this signature::
callback(frames: int) -> None
The argument `frames` specifies the number of frames that
have to be processed in the current audio block. It will be
the same number as :attr:`blocksize` and it will be a power
of two.
As long as the client is active, the `callback` will be
called once in each process cycle. However, if an exception
is raised inside of a `callback`, it will not be called
anymore. The exception :class:`CallbackExit` can be used to
silently prevent further callback invocations, all other
exceptions will print an error message to *stderr*.
"""
@self._callback("JackProcessCallback", error=_FAILURE)
def callback_wrapper(frames, _):
try:
callback(frames)
except CallbackExit:
return _FAILURE
return _SUCCESS
_check(_lib.jack_set_process_callback(
self._ptr, callback_wrapper, _ffi.NULL),
"Error setting process callback")
def set_freewheel_callback(self, callback):
"""Register freewheel callback.
Tell the JACK server to call `callback` whenever we enter or
leave "freewheel" mode.
The argument to the callback will be ``True`` if JACK is
entering freewheel mode, and ``False`` otherwise.
All "notification events" are received in a separated non RT
thread, the code in the supplied function does not need to be
suitable for real-time execution.
.. note:: This function cannot be called while the client is
activated (after :meth:`activate` has been called).
Parameters
----------
callback : callable
User-supplied function that is called whenever JACK starts
or stops freewheeling. It must have this signature::
callback(starting: bool) -> None
The argument `starting` is ``True`` if we start to
freewheel, ``False`` otherwise.
.. note:: Same as with most callbacks, no functions that
interact with the JACK daemon should be used here.
See Also
--------
set_freewheel
"""
@self._callback("JackFreewheelCallback")
def callback_wrapper(starting, _):
callback(bool(starting))
_check(_lib.jack_set_freewheel_callback(
self._ptr, callback_wrapper, _ffi.NULL),
"Error setting freewheel callback")
def set_blocksize_callback(self, callback):
"""Register blocksize callback.
Tell JACK to call `callback` whenever the size of the the buffer
that will be passed to the process callback is about to change.
Clients that depend on knowing the buffer size must supply a
`callback` before activating themselves.
All "notification events" are received in a separated non RT
thread, the code in the supplied function does not need to be
suitable for real-time execution.
.. note:: This function cannot be called while the client is
activated (after :meth:`activate` has been called).
Parameters
----------
callback : callable
User-supplied function that is invoked whenever the JACK