1 /*
2 * Copyright (C) 2018-2021 Alexandros Theodotou <alex at zrythm dot org>
3 * Copyright (C) 2020 Ryan Gonzalez <rymg19 at gmail dot com>
4 *
5 * This file is part of Zrythm
6 *
7 * Zrythm is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * Zrythm is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with Zrythm. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21 /**
22 * \file
23 *
24 * The audio engine.
25 */
26
27 #ifndef __AUDIO_ENGINE_H__
28 #define __AUDIO_ENGINE_H__
29
30 #include "zrythm-config.h"
31
32 #include "audio/control_room.h"
33 #include "audio/exporter.h"
34 #include "audio/ext_port.h"
35 #include "audio/hardware_processor.h"
36 #include "audio/pan.h"
37 #include "audio/pool.h"
38 #include "audio/sample_processor.h"
39 #include "audio/transport.h"
40 #include "utils/types.h"
41 #include "zix/sem.h"
42
43 #ifdef HAVE_JACK
44 #include "weak_libjack.h"
45 #endif
46
47 #ifdef HAVE_PULSEAUDIO
48 #include <pulse/pulseaudio.h>
49 #endif
50
51 #ifdef HAVE_PORT_AUDIO
52 #include <portaudio.h>
53 #endif
54
55 #ifdef HAVE_ALSA
56 #include <alsa/asoundlib.h>
57 #endif
58
59 #ifdef HAVE_SDL
60 #include <SDL2/SDL_audio.h>
61 #endif
62
63 #ifdef HAVE_RTAUDIO
64 #include <rtaudio/rtaudio_c.h>
65 #endif
66
67 typedef struct StereoPorts StereoPorts;
68 typedef struct Port Port;
69 typedef struct Channel Channel;
70 typedef struct Plugin Plugin;
71 typedef struct Tracklist Tracklist;
72 typedef struct ExtPort ExtPort;
73 typedef struct MidiMappings MidiMappings;
74 typedef struct WindowsMmeDevice WindowsMmeDevice;
75 typedef struct Router Router;
76 typedef struct Metronome Metronome;
77 typedef struct Project Project;
78 typedef struct HardwareProcessor HardwareProcessor;
79 typedef struct ObjectPool ObjectPool;
80 typedef struct MPMCQueue MPMCQueue;
81
82 /**
83 * @addtogroup audio Audio
84 *
85 * @{
86 */
87
88 #define AUDIO_ENGINE_SCHEMA_VERSION 1
89
90 #define BLOCK_LENGTH 4096 // should be set by backend
91 #define MIDI_BUF_SIZE 1024 // should be set by backend
92
93 #define MIDI_IN_NUM_EVENTS \
94 AUDIO_ENGINE->midi_in->midi_events->num_events
95
96
97 #define AUDIO_ENGINE (PROJECT->audio_engine)
98 #define MANUAL_PRESS_EVENTS \
99 (AUDIO_ENGINE->midi_editor_manual_press-> \
100 midi_events)
101
102 #define DENORMAL_PREVENTION_VAL \
103 (AUDIO_ENGINE->denormal_prevention_val)
104
105 #define engine_is_in_active_project(self) \
106 (self->project == PROJECT)
107
108 /** Set whether engine should process (true) or
109 * skip (false). */
110 #define engine_set_run(engine,_run) \
111 g_atomic_int_set (&(engine)->run, _run)
112 #define engine_get_run(engine) \
113 g_atomic_int_get (&(engine)->run)
114
115 #define ENGINE_MAX_EVENTS 100
116
117 #define engine_queue_push_back_event(q,x) \
118 mpmc_queue_push_back ( \
119 q, (void *) x)
120
121 #define engine_queue_dequeue_event(q,x) \
122 mpmc_queue_dequeue ( \
123 q, (void *) x)
124
125 /**
126 * Push events.
127 */
128 #define ENGINE_EVENTS_PUSH( \
129 et,_arg,_uint_arg,_float_arg) \
130 if (true) \
131 { \
132 AudioEngineEvent * _ev = \
133 (AudioEngineEvent *) \
134 object_pool_get (AUDIO_ENGINE->ev_pool); \
135 _ev->file = __FILE__; \
136 _ev->func = __func__; \
137 _ev->lineno = __LINE__; \
138 _ev->type = et; \
139 _ev->arg = (void *) _arg; \
140 _ev->uint_arg = _uint_arg; \
141 _ev->float_arg = _float_arg; \
142 if (zrythm_app->gtk_thread == \
143 g_thread_self ()) \
144 { \
145 _ev->backtrace = \
146 backtrace_get ("", 40, false); \
147 g_debug ( \
148 "pushing engine event " #et \
149 " (%s:%d)", __func__, __LINE__); \
150 } \
151 engine_queue_push_back_event ( \
152 AUDIO_ENGINE->ev_queue, _ev); \
153 }
154
155 /**
156 * Audio engine event type.
157 */
158 typedef enum AudioEngineEventType
159 {
160 AUDIO_ENGINE_EVENT_BUFFER_SIZE_CHANGE,
161 AUDIO_ENGINE_EVENT_SAMPLE_RATE_CHANGE,
162 } AudioEngineEventType;
163
164 /**
165 * Audio engine event.
166 */
167 typedef struct AudioEngineEvent
168 {
169 AudioEngineEventType type;
170 void * arg;
171 uint32_t uint_arg;
172 float float_arg;
173 const char * file;
174 const char * func;
175 int lineno;
176 char * backtrace;
177 } AudioEngineEvent;
178
179 /**
180 * Buffer sizes to be used in combo boxes.
181 */
182 typedef enum AudioEngineBufferSize
183 {
184 AUDIO_ENGINE_BUFFER_SIZE_16,
185 AUDIO_ENGINE_BUFFER_SIZE_32,
186 AUDIO_ENGINE_BUFFER_SIZE_64,
187 AUDIO_ENGINE_BUFFER_SIZE_128,
188 AUDIO_ENGINE_BUFFER_SIZE_256,
189 AUDIO_ENGINE_BUFFER_SIZE_512,
190 AUDIO_ENGINE_BUFFER_SIZE_1024,
191 AUDIO_ENGINE_BUFFER_SIZE_2048,
192 AUDIO_ENGINE_BUFFER_SIZE_4096,
193 NUM_AUDIO_ENGINE_BUFFER_SIZES,
194 } AudioEngineBufferSize;
195
196 static const char * buffer_size_str[] =
197 {
198 "16",
199 "32",
200 "64",
201 "128",
202 "256",
203 "512",
204 __("1,024"),
205 __("2,048"),
206 __("4,096"),
207 };
208
209 static inline const char *
engine_buffer_size_to_string(AudioEngineBufferSize buf_size)210 engine_buffer_size_to_string (
211 AudioEngineBufferSize buf_size)
212 {
213 return buffer_size_str[buf_size];
214 }
215
216 /**
217 * Samplerates to be used in comboboxes.
218 */
219 typedef enum AudioEngineSamplerate
220 {
221 AUDIO_ENGINE_SAMPLERATE_22050,
222 AUDIO_ENGINE_SAMPLERATE_32000,
223 AUDIO_ENGINE_SAMPLERATE_44100,
224 AUDIO_ENGINE_SAMPLERATE_48000,
225 AUDIO_ENGINE_SAMPLERATE_88200,
226 AUDIO_ENGINE_SAMPLERATE_96000,
227 AUDIO_ENGINE_SAMPLERATE_192000,
228 NUM_AUDIO_ENGINE_SAMPLERATES,
229 } AudioEngineSamplerate;
230
231 static const char * sample_rate_str[] =
232 {
233 __("22,050"),
234 __("32,000"),
235 __("44,100"),
236 __("48,000"),
237 __("88,200"),
238 __("96,000"),
239 __("192,000"),
240 };
241
242 static inline const char *
engine_sample_rate_to_string(AudioEngineSamplerate sample_rate)243 engine_sample_rate_to_string (
244 AudioEngineSamplerate sample_rate)
245 {
246 return sample_rate_str[sample_rate];
247 }
248
249 //typedef struct MIDI_Controller
250 //{
251 //jack_midi_event_t in_event[30];
252 //int num_events;
253 //} MIDI_Controller;
254
255 typedef enum AudioBackend
256 {
257 AUDIO_BACKEND_DUMMY,
258 AUDIO_BACKEND_DUMMY_LIBSOUNDIO,
259 AUDIO_BACKEND_ALSA,
260 AUDIO_BACKEND_ALSA_LIBSOUNDIO,
261 AUDIO_BACKEND_ALSA_RTAUDIO,
262 AUDIO_BACKEND_JACK,
263 AUDIO_BACKEND_JACK_LIBSOUNDIO,
264 AUDIO_BACKEND_JACK_RTAUDIO,
265 AUDIO_BACKEND_PULSEAUDIO,
266 AUDIO_BACKEND_PULSEAUDIO_LIBSOUNDIO,
267 AUDIO_BACKEND_PULSEAUDIO_RTAUDIO,
268 AUDIO_BACKEND_COREAUDIO_LIBSOUNDIO,
269 AUDIO_BACKEND_COREAUDIO_RTAUDIO,
270 AUDIO_BACKEND_SDL,
271 AUDIO_BACKEND_WASAPI_LIBSOUNDIO,
272 AUDIO_BACKEND_WASAPI_RTAUDIO,
273 AUDIO_BACKEND_ASIO_RTAUDIO,
274 NUM_AUDIO_BACKENDS,
275 } AudioBackend;
276
277 static inline bool
audio_backend_is_rtaudio(AudioBackend backend)278 audio_backend_is_rtaudio (
279 AudioBackend backend)
280 {
281 return
282 backend == AUDIO_BACKEND_ALSA_RTAUDIO ||
283 backend == AUDIO_BACKEND_JACK_RTAUDIO ||
284 backend == AUDIO_BACKEND_PULSEAUDIO_RTAUDIO ||
285 backend == AUDIO_BACKEND_COREAUDIO_RTAUDIO ||
286 backend == AUDIO_BACKEND_WASAPI_RTAUDIO ||
287 backend == AUDIO_BACKEND_ASIO_RTAUDIO;
288 }
289
290 __attribute__ ((unused))
291 static const char * audio_backend_str[] =
292 {
293 /* TRANSLATORS: Dummy backend */
294 __("Dummy"),
295 __("Dummy (libsoundio)"),
296 "ALSA (not working)",
297 "ALSA (libsoundio)",
298 "ALSA (rtaudio)",
299 "JACK",
300 "JACK (libsoundio)",
301 "JACK (rtaudio)",
302 "PulseAudio",
303 "PulseAudio (libsoundio)",
304 "PulseAudio (rtaudio)",
305 "CoreAudio (libsoundio)",
306 "CoreAudio (rtaudio)",
307 "SDL",
308 "WASAPI (libsoundio)",
309 "WASAPI (rtaudio)",
310 "ASIO (rtaudio)",
311 };
312
313 /**
314 * Mode used when bouncing, either during exporting
315 * or when bouncing tracks or regions to audio.
316 */
317 typedef enum BounceMode
318 {
319 /** Don't bounce. */
320 BOUNCE_OFF,
321
322 /** Bounce. */
323 BOUNCE_ON,
324
325 /**
326 * Bounce if parent is bouncing.
327 *
328 * To be used on regions to bounce if their track
329 * is bouncing.
330 */
331 BOUNCE_INHERIT,
332 } BounceMode;
333
334 typedef enum MidiBackend
335 {
336 MIDI_BACKEND_DUMMY,
337 MIDI_BACKEND_ALSA,
338 MIDI_BACKEND_ALSA_RTMIDI,
339 MIDI_BACKEND_JACK,
340 MIDI_BACKEND_JACK_RTMIDI,
341 MIDI_BACKEND_WINDOWS_MME,
342 MIDI_BACKEND_WINDOWS_MME_RTMIDI,
343 MIDI_BACKEND_COREMIDI_RTMIDI,
344 NUM_MIDI_BACKENDS,
345 } MidiBackend;
346
347 static inline bool
midi_backend_is_rtmidi(MidiBackend backend)348 midi_backend_is_rtmidi (
349 MidiBackend backend)
350 {
351 return
352 backend == MIDI_BACKEND_ALSA_RTMIDI ||
353 backend == MIDI_BACKEND_JACK_RTMIDI ||
354 backend == MIDI_BACKEND_WINDOWS_MME_RTMIDI ||
355 backend == MIDI_BACKEND_COREMIDI_RTMIDI;
356 }
357
358 static const char * midi_backend_str[] =
359 {
360 /* TRANSLATORS: Dummy backend */
361 __("Dummy"),
362 __("ALSA Sequencer (not working)"),
363 __("ALSA Sequencer (rtmidi)"),
364 "JACK MIDI",
365 "JACK MIDI (rtmidi)",
366 "Windows MME",
367 "Windows MME (rtmidi)",
368 "CoreMIDI (rtmidi)",
369 };
370
371 typedef enum AudioEngineJackTransportType
372 {
373 AUDIO_ENGINE_JACK_TIMEBASE_MASTER,
374 AUDIO_ENGINE_JACK_TRANSPORT_CLIENT,
375 AUDIO_ENGINE_NO_JACK_TRANSPORT,
376 } AudioEngineJackTransportType;
377
378 static const cyaml_strval_t
379 jack_transport_type_strings[] =
380 {
381 { "Timebase master",
382 AUDIO_ENGINE_JACK_TIMEBASE_MASTER },
383 { "Transport client",
384 AUDIO_ENGINE_JACK_TRANSPORT_CLIENT },
385 { "No JACK transport",
386 AUDIO_ENGINE_NO_JACK_TRANSPORT },
387 };
388
389 /**
390 * Common struct to pass around during processing
391 * to avoid repeating the data in function
392 * arguments.
393 */
394 typedef struct EngineProcessTimeInfo
395 {
396 /** Global position at the start of the
397 * processing cycle. */
398 /* FIXME in some places this is adjusted to the
399 * local offset. it should be adjusted to the
400 * local offset everywhere */
401 long g_start_frames;
402
403 /** Offset in the current processing cycle,
404 * between 0 and the number of frames in
405 * AudioEngine.block_length. */
406 nframes_t local_offset;
407
408 /**
409 * Number of frames to process in this call.
410 */
411 nframes_t nframes;
412 } EngineProcessTimeInfo;
413
414 /**
415 * The audio engine.
416 */
417 typedef struct AudioEngine
418 {
419 int schema_version;
420
421 /**
422 * Cycle count to know which cycle we are in.
423 *
424 * Useful for debugging.
425 */
426 unsigned long cycle;
427
428 #ifdef HAVE_JACK
429 /** JACK client. */
430 jack_client_t * client;
431 #else
432 void * client;
433 #endif
434
435 /**
436 * Whether transport master/client or no
437 * connection with jack transport.
438 */
439 AudioEngineJackTransportType transport_type;
440
441 /** Current audio backend. */
442 AudioBackend audio_backend;
443
444 /** Current MIDI backend. */
445 MidiBackend midi_backend;
446
447 /** Audio buffer size (block length), per
448 * channel. */
449 nframes_t block_length;
450
451 /** Size of MIDI port buffers in bytes. */
452 size_t midi_buf_size;
453
454 /** Sample rate. */
455 sample_rate_t sample_rate;
456
457 /** Number of frames/samples per tick. */
458 double frames_per_tick;
459
460 /**
461 * Reciprocal of \ref
462 * AudioEngine.frames_per_tick.
463 */
464 double ticks_per_frame;
465
466 /** True iff buffer size callback fired. */
467 int buf_size_set;
468
469 /** The processing graph router. */
470 Router * router;
471
472 /** Input device processor. */
473 HardwareProcessor * hw_in_processor;
474
475 /** Output device processor. */
476 HardwareProcessor * hw_out_processor;
477
478 #if 0
479 /**
480 * Audio intefrace outputs (only 2 are used).
481 *
482 * These should be initialized at the start and
483 * only used at runtime for getting the buffers.
484 *
485 * They should eventually be stored in GSettings
486 * since they are user settings and not project
487 * related.
488 */
489 ExtPort * hw_stereo_outs[EXT_PORTS_MAX];
490 int num_hw_stereo_outs;
491
492 /**
493 * Audio intefrace inputs (only 2 are used).
494 *
495 * These should be initialized at the start and
496 * only used at runtime for getting the buffers.
497 *
498 * They should eventually be stored in GSettings
499 * since they are user settings and not project
500 * related.
501 *
502 * They should only be used in audio tracks as
503 * default recording input.
504 */
505 ExtPort * hw_stereo_ins[EXT_PORTS_MAX];
506 int num_hw_stereo_ins;
507 #endif
508
509 /** MIDI Clock in TODO. */
510 Port * midi_clock_in;
511
512 /** The ControlRoom. */
513 ControlRoom * control_room;
514
515 /** Audio file pool. */
516 AudioPool * pool;
517
518 /**
519 * Used during tests to pass input data for
520 * recording.
521 *
522 * Will be ignored if NULL.
523 */
524 StereoPorts * dummy_input;
525
526 /**
527 * Monitor - these should be the last ports in
528 * the signal chain.
529 */
530 StereoPorts * monitor_out;
531
532 /**
533 * Flag to tell the UI that this channel had
534 * MIDI activity.
535 *
536 * When processing this and setting it to 0,
537 * the UI should create a separate event using
538 * EVENTS_PUSH.
539 */
540 int trigger_midi_activity;
541
542 /**
543 * Manual note press events from the piano roll.
544 *
545 * The events from here should be read by the
546 * corresponding track processor's MIDI in port
547 * (TrackProcessor.midi_in). To avoid having to
548 * recalculate the graph to reattach this port
549 * to the correct track processor, only connect
550 * this port to the initial processor in the
551 * routing graph and fetch the events manually
552 * when processing the corresponding track
553 * processor.
554 */
555 Port * midi_editor_manual_press;
556
557 /**
558 * Port used for receiving MIDI in messages for
559 * binding CC and other non-recording purposes.
560 */
561 Port * midi_in;
562
563 /**
564 * Number of frames/samples in the current
565 * cycle, per channel.
566 *
567 * @note This is used by the engine internally.
568 */
569 nframes_t nframes;
570
571 /** Semaphore for blocking DSP while a plugin and
572 * its ports are deleted. */
573 ZixSem port_operation_lock;
574
575 /** Ok to process or not. */
576 volatile gint run;
577
578 /** 1 if currently exporting. */
579 gint exporting;
580
581 /** Send note off MIDI everywhere. */
582 volatile gint panic;
583
584 //ZixSem alsa_callback_start;
585
586 /* ----------- ALSA --------------- */
587 #ifdef HAVE_ALSA
588 /** Alsa playback handle. */
589 snd_pcm_t * playback_handle;
590 snd_seq_t * seq_handle;
591 snd_pcm_hw_params_t * hw_params;
592 snd_pcm_sw_params_t * sw_params;
593
594 /**
595 * Since ALSA MIDI runs in its own thread,
596 * store the events here temporarily and
597 * pop them in the process cycle.
598 *
599 * Needs to be protected by some kind of
600 * mutex.
601 */
602 //MidiEvents alsa_midi_events;
603
604 /** Semaphore for exclusively writing/reading
605 * ALSA MIDI events from above. */
606 //ZixSem alsa_midi_events_sem;
607 #else
608 void * playback_handle;
609 void * seq_handle;
610 void * hw_params;
611 void * sw_params;
612 #endif
613
614 /** ALSA audio buffer. */
615 float * alsa_out_buf;
616
617 /* ------------------------------- */
618
619
620 /** Flag used when processing in some backends. */
621 volatile gint filled_stereo_out_bufs;
622
623 /** Flag used to check if we are inside
624 * engine_process_prepare(). */
625 gint preparing_for_process;
626
627 #ifdef HAVE_PORT_AUDIO
628 PaStream * pa_stream;
629 #else
630 void * pa_stream;
631 #endif
632
633 /**
634 * Port Audio output buffer.
635 *
636 * Unlike JACK, the audio goes directly here.
637 * FIXME this is not really needed, just
638 * do the calculations in pa_stream_cb.
639 */
640 float * pa_out_buf;
641
642 #ifdef _WOE32
643 /** Windows MME MIDI devices. */
644 WindowsMmeDevice * mme_in_devs[1024];
645 int num_mme_in_devs;
646 WindowsMmeDevice * mme_out_devs[1024];
647 int num_mme_out_devs;
648 #else
649 void * mme_in_devs[1024];
650 int num_mme_in_devs;
651 void * mme_out_devs[1024];
652 int num_mme_out_devs;
653 #endif
654
655 #ifdef HAVE_SDL
656 SDL_AudioDeviceID dev;
657 #else
658 uint32_t sdl_dev;
659 #endif
660
661 #ifdef HAVE_RTAUDIO
662 rtaudio_t rtaudio;
663 #else
664 void * rtaudio;
665 #endif
666
667 #ifdef HAVE_PULSEAUDIO
668 pa_threaded_mainloop * pulse_mainloop;
669 pa_context * pulse_context;
670 pa_stream * pulse_stream;
671 #else
672 void * pulse_mainloop;
673 void * pulse_context;
674 void * pulse_stream;
675 #endif
676 gboolean pulse_notified_underflow;
677
678 /**
679 * Dummy audio DSP processing thread.
680 */
681 GThread * dummy_audio_thread;
682
683 /** Set to 1 to stop the dummy audio thread. */
684 int stop_dummy_audio_thread;
685
686 /**
687 * Timeline metadata like BPM, time signature, etc.
688 */
689 Transport * transport;
690
691 /* note: these 2 are ignored at the moment */
692 /** Pan law. */
693 PanLaw pan_law;
694 /** Pan algorithm */
695 PanAlgorithm pan_algo;
696
697 /** Time taken to process in the last cycle */
698 gint64 last_time_taken;
699
700 /** Max time taken to process in the last few
701 * cycles. */
702 gint64 max_time_taken;
703
704 /** Timestamp at the start of the current
705 * cycle. */
706 gint64 timestamp_start;
707
708 /** Expected timestamp at the end of the current
709 * cycle. */
710 gint64 timestamp_end;
711
712 /** Timestamp at start of previous cycle. */
713 gint64 last_timestamp_start;
714
715 /** Timestamp at end of previous cycle. */
716 gint64 last_timestamp_end;
717
718 /** When first set, it is equal to the max
719 * playback latency of all initial trigger
720 * nodes. */
721 nframes_t remaining_latency_preroll;
722
723 SampleProcessor * sample_processor;
724
725 /** To be set to 1 when the CC from the Midi in
726 * port should be captured. */
727 int capture_cc;
728
729 /** Last MIDI CC captured. */
730 midi_byte_t last_cc[3];
731
732 /**
733 * Last time an XRUN notification was shown.
734 *
735 * This is to prevent multiple XRUN notifications
736 * being shown so quickly that Zrythm becomes
737 * unusable.
738 */
739 gint64 last_xrun_notification;
740
741 /**
742 * Whether the denormal prevention value
743 * (1e-12 ~ 1e-20) is positive.
744 *
745 * This should be swapped often to avoid DC offset
746 * prevention algorithms removing it.
747 *
748 * See https://www.earlevel.com/main/2019/04/19/floating-point-denormals/ for details.
749 */
750 bool denormal_prevention_val_positive;
751 float denormal_prevention_val;
752
753 /* --- trial version flags --- */
754
755 /** Time at start to keep track if trial limit
756 * is reached. */
757 gint64 zrythm_start_time;
758
759 /** Flag to keep track of the first time the
760 * limit is reached. */
761 int limit_reached;
762
763 /* --- end trial version flags --- */
764
765 /**
766 * If this is on, only tracks/regions marked as
767 * "for bounce" will be allowed to make sound.
768 *
769 * Automation and everything else will work as
770 * normal.
771 */
772 BounceMode bounce_mode;
773
774 /** Bounce step cache. */
775 BounceStep bounce_step;
776
777 /** Whether currently bouncing with parents
778 * (cache). */
779 bool bounce_with_parents;
780
781 /** The metronome. */
782 Metronome * metronome;
783
784 /* --- events --- */
785
786 /**
787 * Event queue.
788 *
789 * Events such as buffer size change request and
790 * sample size change request should be queued
791 * here.
792 *
793 * The engine will skip processing while the
794 * queue still has events or is currently
795 * processing events.
796 */
797 MPMCQueue * ev_queue;
798
799 /**
800 * Object pool of event structs to avoid
801 * allocation.
802 */
803 ObjectPool * ev_pool;
804
805 /** ID of the event processing source func. */
806 guint process_source_id;
807
808 /** Whether currently processing events. */
809 int processing_events;
810
811 /** Time last event processing started. */
812 gint64 last_events_process_started;
813
814 /** Time last event processing completed. */
815 gint64 last_events_processed;
816
817 /* --- end events --- */
818
819 /** Whether the cycle is currently running. */
820 volatile gint cycle_running;
821
822 /** Whether the engine is already pre-set up. */
823 bool pre_setup;
824
825 /** Whether the engine is already set up. */
826 bool setup;
827
828 /** Whether the engine is currently activated. */
829 bool activated;
830
831 /** Pointer to owner project, if any. */
832 Project * project;
833 } AudioEngine;
834
835 static const cyaml_schema_field_t
836 engine_fields_schema[] =
837 {
838 YAML_FIELD_INT (
839 AudioEngine, schema_version),
840 YAML_FIELD_ENUM (
841 AudioEngine, transport_type,
842 jack_transport_type_strings),
843 YAML_FIELD_INT (
844 AudioEngine, sample_rate),
845 YAML_FIELD_FLOAT (
846 AudioEngine, frames_per_tick),
847 YAML_FIELD_MAPPING_PTR (
848 AudioEngine, monitor_out,
849 stereo_ports_fields_schema),
850 YAML_FIELD_MAPPING_PTR (
851 AudioEngine, midi_editor_manual_press,
852 port_fields_schema),
853 YAML_FIELD_MAPPING_PTR (
854 AudioEngine, midi_in,
855 port_fields_schema),
856 YAML_FIELD_MAPPING_PTR (
857 AudioEngine, transport,
858 transport_fields_schema),
859 YAML_FIELD_MAPPING_PTR (
860 AudioEngine, pool,
861 audio_pool_fields_schema),
862 YAML_FIELD_MAPPING_PTR (
863 AudioEngine, control_room,
864 control_room_fields_schema),
865 YAML_FIELD_MAPPING_PTR (
866 AudioEngine, sample_processor,
867 sample_processor_fields_schema),
868 YAML_FIELD_MAPPING_PTR (
869 AudioEngine, hw_in_processor,
870 hardware_processor_fields_schema),
871 YAML_FIELD_MAPPING_PTR (
872 AudioEngine, hw_out_processor,
873 hardware_processor_fields_schema),
874
875 CYAML_FIELD_END
876 };
877
878 static const cyaml_schema_value_t
879 engine_schema =
880 {
881 YAML_VALUE_PTR (
882 AudioEngine, engine_fields_schema),
883 };
884
885 void
886 engine_realloc_port_buffers (
887 AudioEngine * self,
888 nframes_t buf_size);
889
890 COLD
891 NONNULL_ARGS (1)
892 void
893 engine_init_loaded (
894 AudioEngine * self,
895 Project * project);
896
897 /**
898 * Create a new audio engine.
899 *
900 * This only initializes the engine and doe snot
901 * connect to the backend.
902 */
903 COLD
904 WARN_UNUSED_RESULT
905 AudioEngine *
906 engine_new (
907 Project * project);
908
909 typedef struct EngineState
910 {
911 /** Engine running. */
912 int running;
913 /** Playback. */
914 bool playing;
915 /** Transport loop. */
916 bool looping;
917 } EngineState;
918
919 /**
920 * @param force_pause Whether to force transport
921 * pause, otherwise for engine to process and
922 * handle the pause request.
923 */
924 void
925 engine_wait_for_pause (
926 AudioEngine * self,
927 EngineState * state,
928 bool force_pause);
929
930 void
931 engine_resume (
932 AudioEngine * self,
933 EngineState * state);
934
935 /**
936 * Waits for n processing cycles to finish.
937 *
938 * Used during tests.
939 */
940 void
941 engine_wait_n_cycles (
942 AudioEngine * self,
943 int n);
944
945 void
946 engine_append_ports (
947 AudioEngine * self,
948 GPtrArray * ports);
949
950 /**
951 * Sets up the audio engine before the project is
952 * initialized/loaded.
953 */
954 void
955 engine_pre_setup (
956 AudioEngine * self);
957
958 /**
959 * Sets up the audio engine after the project
960 * is initialized/loaded.
961 */
962 void
963 engine_setup (
964 AudioEngine * self);
965
966 /**
967 * Activates the audio engine to start processing
968 * and receiving events.
969 *
970 * @param activate Activate or deactivate.
971 */
972 COLD
973 void
974 engine_activate (
975 AudioEngine * self,
976 bool activate);
977
978 /**
979 * Updates frames per tick based on the time sig,
980 * the BPM, and the sample rate
981 *
982 * @param thread_check Whether to throw a warning
983 * if not called from GTK thread.
984 * @param update_from_ticks Whether to update the
985 * positions based on ticks (true) or frames
986 * (false).
987 */
988 void
989 engine_update_frames_per_tick (
990 AudioEngine * self,
991 const int beats_per_bar,
992 const bpm_t bpm,
993 const sample_rate_t sample_rate,
994 bool thread_check,
995 bool update_from_ticks);
996
997 /**
998 * GSourceFunc to be added using idle add.
999 *
1000 * This will loop indefinintely.
1001 */
1002 int
1003 engine_process_events (
1004 AudioEngine * self);
1005
1006 /**
1007 * To be called by each implementation to prepare
1008 * the structures before processing.
1009 *
1010 * Clears buffers, marks all as unprocessed, etc.
1011 *
1012 * @return Whether the cycle should be skipped.
1013 */
1014 NONNULL
1015 HOT
1016 bool
1017 engine_process_prepare (
1018 AudioEngine * self,
1019 nframes_t nframes);
1020
1021 /**
1022 * Processes current cycle.
1023 *
1024 * To be called by each implementation in its
1025 * callback.
1026 */
1027 NONNULL
1028 HOT
1029 int
1030 engine_process (
1031 AudioEngine * self,
1032 const nframes_t total_frames_to_process);
1033
1034 /**
1035 * To be called after processing for common logic.
1036 *
1037 * @param roll_nframes Frames to roll (add to the
1038 * playhead - if transport rolling).
1039 * @param nframes Total frames for this processing
1040 * cycle.
1041 */
1042 NONNULL
1043 HOT
1044 void
1045 engine_post_process (
1046 AudioEngine * self,
1047 const nframes_t roll_nframes,
1048 const nframes_t nframes);
1049
1050 /**
1051 * Called to fill in the external buffers at the end
1052 * of the processing cycle.
1053 */
1054 NONNULL
1055 void
1056 engine_fill_out_bufs (
1057 AudioEngine * self,
1058 const nframes_t nframes);
1059
1060 /**
1061 * Returns the int value correesponding to the
1062 * given AudioEngineBufferSize.
1063 */
1064 int
1065 engine_buffer_size_enum_to_int (
1066 AudioEngineBufferSize buffer_size);
1067
1068 /**
1069 * Returns the int value correesponding to the
1070 * given AudioEngineSamplerate.
1071 */
1072 int
1073 engine_samplerate_enum_to_int (
1074 AudioEngineSamplerate samplerate);
1075
1076 /**
1077 * Request the backend to set the buffer size.
1078 *
1079 * The backend is expected to call the buffer size
1080 * change callbacks.
1081 *
1082 * @seealso jack_set_buffer_size().
1083 */
1084 void
1085 engine_set_buffer_size (
1086 AudioEngine * self,
1087 uint32_t buf_size);
1088
1089 /**
1090 * Returns 1 if the port is an engine port or
1091 * control room port, otherwise 0.
1092 */
1093 #define engine_is_port_own(self,port) \
1094 (port == MONITOR_FADER->stereo_in->l || \
1095 port == MONITOR_FADER->stereo_in->r || \
1096 port == MONITOR_FADER->stereo_out->l || \
1097 port == MONITOR_FADER->stereo_out->r)
1098
1099 /**
1100 * Returns the audio backend as a string.
1101 */
1102 const char *
1103 engine_audio_backend_to_string (
1104 AudioBackend backend);
1105
1106 AudioBackend
1107 engine_audio_backend_from_string (
1108 char * str);
1109
1110 /**
1111 * Returns the MIDI backend as a string.
1112 */
1113 static inline const char *
engine_midi_backend_to_string(MidiBackend backend)1114 engine_midi_backend_to_string (
1115 MidiBackend backend)
1116 {
1117 return midi_backend_str[backend];
1118 }
1119
1120 MidiBackend
1121 engine_midi_backend_from_string (
1122 char * str);
1123
1124 /**
1125 * Reset the bounce mode on the engine, all tracks
1126 * and regions to OFF.
1127 */
1128 void
1129 engine_reset_bounce_mode (
1130 AudioEngine * self);
1131
1132 /**
1133 * Clones the audio engine.
1134 *
1135 * To be used for serialization.
1136 */
1137 COLD
1138 NONNULL
1139 AudioEngine *
1140 engine_clone (
1141 const AudioEngine * src);
1142
1143 /**
1144 * Closes any connections and free's data.
1145 */
1146 COLD
1147 NONNULL
1148 void
1149 engine_free (
1150 AudioEngine * self);
1151
1152 /**
1153 * @}
1154 */
1155
1156 #endif
1157