-
Notifications
You must be signed in to change notification settings - Fork 716
/
Copy pathsession.cc
8184 lines (6706 loc) · 216 KB
/
session.cc
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) 1999-2019 Paul Davis <[email protected]>
* Copyright (C) 2006-2007 Jesse Chappell <[email protected]>
* Copyright (C) 2006-2009 Sampo Savolainen <[email protected]>
* Copyright (C) 2006-2015 David Robillard <[email protected]>
* Copyright (C) 2006-2016 Tim Mayberry <[email protected]>
* Copyright (C) 2007-2012 Carl Hetherington <[email protected]>
* Copyright (C) 2008-2009 Hans Baier <[email protected]>
* Copyright (C) 2012-2019 Robin Gareus <[email protected]>
* Copyright (C) 2013-2017 Nick Mainsbridge <[email protected]>
* Copyright (C) 2014-2019 Ben Loftis <[email protected]>
* Copyright (C) 2015 GZharun <[email protected]>
* Copyright (C) 2016-2018 Len Ovens <[email protected]>
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdint.h>
#include <algorithm>
#include <string>
#include <vector>
#include <sstream>
#include <cstdio> /* sprintf(3) ... grrr */
#include <cmath>
#include <cerrno>
#include <unistd.h>
#include <limits.h>
#include <glibmm/datetime.h>
#include <glibmm/threads.h>
#include <glibmm/miscutils.h>
#include <glibmm/fileutils.h>
#include "pbd/atomic.h"
#include "pbd/basename.h"
#include "pbd/convert.h"
#include "pbd/error.h"
#include "pbd/file_utils.h"
#include "pbd/md5.h"
#include "pbd/pthread_utils.h"
#include "pbd/search_path.h"
#include "pbd/stl_delete.h"
#include "pbd/replace_all.h"
#include "pbd/types_convert.h"
#include "pbd/unwind.h"
#include "temporal/types_convert.h"
#include "ardour/amp.h"
#include "ardour/analyser.h"
#include "ardour/async_midi_port.h"
#include "ardour/audio_buffer.h"
#include "ardour/audio_port.h"
#include "ardour/audio_track.h"
#include "ardour/audioengine.h"
#include "ardour/audiofilesource.h"
#include "ardour/auditioner.h"
#include "ardour/boost_debug.h"
#include "ardour/buffer_manager.h"
#include "ardour/buffer_set.h"
#include "ardour/bundle.h"
#include "ardour/butler.h"
#include "ardour/click.h"
#include "ardour/control_protocol_manager.h"
#include "ardour/data_type.h"
#include "ardour/debug.h"
#include "ardour/disk_reader.h"
#include "ardour/directory_names.h"
#include "ardour/filename_extensions.h"
#include "ardour/gain_control.h"
#include "ardour/graph.h"
#include "ardour/io_plug.h"
#include "ardour/io_tasklist.h"
#include "ardour/luabindings.h"
#include "ardour/lv2_plugin.h"
#include "ardour/midiport_manager.h"
#include "ardour/scene_changer.h"
#include "ardour/midi_patch_manager.h"
#include "ardour/midi_track.h"
#include "ardour/midi_ui.h"
#include "ardour/mixer_scene.h"
#include "ardour/operations.h"
#include "ardour/playlist.h"
#include "ardour/playlist_factory.h"
#include "ardour/plugin.h"
#include "ardour/plugin_insert.h"
#include "ardour/plugin_manager.h"
#include "ardour/polarity_processor.h"
#include "ardour/presentation_info.h"
#include "ardour/process_thread.h"
#include "ardour/profile.h"
#include "ardour/rc_configuration.h"
#include "ardour/recent_sessions.h"
#include "ardour/region.h"
#include "ardour/region_factory.h"
#include "ardour/revision.h"
#include "ardour/route_group.h"
#include "ardour/rt_tasklist.h"
#include "ardour/wrong_program.h"
#include "ardour/rt_safe_delete.h"
#include "ardour/silentfilesource.h"
#include "ardour/send.h"
#include "ardour/selection.h"
#include "ardour/session.h"
#include "ardour/session_directory.h"
#include "ardour/session_playlists.h"
#include "ardour/session_route.h"
#include "ardour/smf_source.h"
#include "ardour/solo_isolate_control.h"
#include "ardour/source_factory.h"
#include "ardour/speakers.h"
#include "ardour/surround_return.h"
#include "ardour/tempo.h"
#include "ardour/ticker.h"
#include "ardour/transport_fsm.h"
#include "ardour/transport_master.h"
#include "ardour/transport_master_manager.h"
#include "ardour/track.h"
#include "ardour/triggerbox.h"
#include "ardour/types_convert.h"
#include "ardour/user_bundle.h"
#include "ardour/utils.h"
#include "ardour/vca_manager.h"
#include "ardour/vca.h"
#ifdef VST3_SUPPORT
#include "ardour/vst3_plugin.h"
#endif // VST3_SUPPORT
#include "midi++/port.h"
#include "midi++/mmc.h"
#include "LuaBridge/LuaBridge.h"
#include <glibmm/checksum.h>
#include "pbd/i18n.h"
namespace ARDOUR {
class MidiSource;
class Processor;
class Speakers;
}
using namespace std;
using namespace ARDOUR;
using namespace PBD;
using namespace Temporal;
bool Session::_disable_all_loaded_plugins = false;
bool Session::_bypass_all_loaded_plugins = false;
std::atomic<unsigned int> Session::_name_id_counter (0);
PBD::Signal<void(std::string)> Session::Dialog;
PBD::Signal<int()> Session::AskAboutPendingState;
PBD::Signal<int(samplecnt_t, samplecnt_t)> Session::AskAboutSampleRateMismatch;
PBD::Signal<void(samplecnt_t, samplecnt_t)> Session::NotifyAboutSampleRateMismatch;
PBD::Signal<void()> Session::SendFeedback;
PBD::Signal<int(Session*,std::string,DataType)> Session::MissingFile;
PBD::Signal<void(samplepos_t)> Session::StartTimeChanged;
PBD::Signal<void(samplepos_t)> Session::EndTimeChanged;
PBD::Signal<void(std::string, std::string, bool, samplepos_t)> Session::Exported;
PBD::Signal<int(std::shared_ptr<Playlist> )> Session::AskAboutPlaylistDeletion;
PBD::Signal<void()> Session::Quit;
PBD::Signal<void()> Session::FeedbackDetected;
PBD::Signal<void()> Session::SuccessfulGraphSort;
PBD::Signal<void(std::string,std::string)> Session::VersionMismatch;
PBD::Signal<void()> Session::AfterConnect;
const samplecnt_t Session::bounce_chunk_size = 8192;
static void clean_up_session_event (SessionEvent* ev) { delete ev; }
const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
const uint32_t Session::session_end_shift = 0;
/** @param snapshot_name Snapshot name, without .ardour suffix */
Session::Session (AudioEngine &eng,
const string& fullpath,
const string& snapshot_name,
BusProfile const * bus_profile,
string mix_template,
bool unnamed,
samplecnt_t sr)
: HistoryOwner (X_("editor"))
, _playlists (new SessionPlaylists)
, _engine (eng)
, process_function (&Session::process_with_events)
, _bounce_processing_active (false)
, waiting_for_sync_offset (false)
, _base_sample_rate (sr)
, _current_sample_rate (0)
, _transport_sample (0)
, _session_range_location (0)
, _session_range_is_free (true)
, _silent (false)
, _remaining_latency_preroll (0)
, _last_touched_mixer_scene_idx (std::numeric_limits<size_t>::max())
, _engine_speed (1.0)
, _signalled_varispeed (0)
, auto_play_legal (false)
, _requested_return_sample (-1)
, current_block_size (0)
, _worst_output_latency (0)
, _worst_input_latency (0)
, _worst_route_latency (0)
, _io_latency (0)
, _send_latency_changes (0)
, _update_send_delaylines (false)
, _have_captured (false)
, _capture_duration (0)
, _capture_xruns (0)
, _export_xruns (0)
, _non_soloed_outs_muted (false)
, _listening (false)
, _listen_cnt (0)
, _solo_isolated_cnt (0)
, _writable (false)
, _under_nsm_control (false)
, _xrun_count (0)
, _required_thread_buffersize (0)
, master_wait_end (0)
, post_export_sync (false)
, post_export_position (0)
, _exporting (false)
, _export_rolling (false)
, _realtime_export (false)
, _region_export (false)
, _export_preroll (0)
, _pre_export_mmc_enabled (false)
, _name (snapshot_name)
, _is_new (true)
, _send_qf_mtc (false)
, _pframes_since_last_mtc (0)
, play_loop (false)
, loop_changing (false)
, last_loopend (0)
, _session_dir (new SessionDirectory (fullpath))
, _current_snapshot_name (snapshot_name)
, state_tree (0)
, _state_of_the_state (StateOfTheState (CannotSave | InitialConnecting | Loading))
, _save_queued (false)
, _save_queued_pending (false)
, _no_save_signal (false)
, _last_roll_location (0)
, _last_roll_or_reversal_location (0)
, _last_record_location (0)
, pending_auto_loop (false)
, _mempool ("Session", 4194304)
#ifdef USE_TLSF
, lua (lua_newstate (&PBD::TLSF::lalloc, &_mempool))
#elif defined USE_MALLOC
, lua (lua_newstate (true, true))
#else
, lua (lua_newstate (&PBD::ReallocPool::lalloc, &_mempool))
#endif
, _lua_run (0)
, _lua_add (0)
, _lua_del (0)
, _lua_list (0)
, _lua_load (0)
, _lua_save (0)
, _lua_cleanup (0)
, _n_lua_scripts (0)
, _io_plugins (new IOPlugList)
, _butler (new Butler (*this))
, _transport_fsm (new TransportFSM (*this))
, _locations (new Locations (*this))
, _ignore_skips_updates (false)
, _rt_thread_active (false)
, _rt_emit_pending (false)
, _ac_thread_active (0)
, step_speed (0)
, outbound_mtc_timecode_frame (0)
, next_quarter_frame_to_send (-1)
, _samples_per_timecode_frame (0)
, _frames_per_hour (0)
, _timecode_frames_per_hour (0)
, last_timecode_valid (false)
, last_timecode_when (0)
, _send_timecode_update (false)
, ltc_encoder (0)
, ltc_enc_buf(0)
, ltc_buf_off (0)
, ltc_buf_len (0)
, ltc_speed (0)
, ltc_enc_byte (0)
, ltc_enc_pos (0)
, ltc_enc_cnt (0)
, ltc_enc_off (0)
, restarting (false)
, ltc_prev_cycle (0)
, ltc_timecode_offset (0)
, ltc_timecode_negative_offset (false)
, midi_control_ui (0)
, _punch_or_loop (NoConstraint)
, _all_route_group (new RouteGroup (*this, "all"))
, routes (new RouteList)
, _adding_routes_in_progress (false)
, _reconnecting_routes_in_progress (false)
, _route_deletion_in_progress (false)
, _route_reorder_in_progress (false)
, _track_number_decimals(1)
, default_fade_steepness (0)
, default_fade_msecs (0)
, _total_free_4k_blocks (0)
, _total_free_4k_blocks_uncertain (false)
, no_questions_about_missing_files (false)
, _bundles (new BundleList)
, _bundle_xml_node (0)
, _clicking (false)
, _click_rec_only (false)
, click_data (0)
, click_emphasis_data (0)
, click_length (0)
, click_emphasis_length (0)
, _clicks_cleared (0)
, _count_in_samples (0)
, _play_range (false)
, _range_selection (timepos_t::max (Temporal::AudioTime), timepos_t::max (Temporal::AudioTime))
, _object_selection (timepos_t::max (Temporal::AudioTime), timepos_t::max (Temporal::AudioTime))
, _preroll_record_trim_len (0)
, _count_in_once (false)
, main_outs (0)
, first_file_data_format_reset (true)
, first_file_header_format_reset (true)
, have_looped (false)
, _step_editors (0)
, _speakers (new Speakers)
, _ignore_route_processor_changes (0)
, _ignored_a_processor_change (0)
, midi_clock (0)
, _scene_changer (0)
, _midi_ports (0)
, _mmc (0)
, _vca_manager (new VCAManager (*this))
, _selection (new CoreSelection (*this))
, _global_locate_pending (false)
, _had_destructive_tracks (false)
, _pending_cue (-1)
, _active_cue (-1)
, tb_with_filled_slots (0)
, _global_quantization (Config->get_default_quantization())
{
_suspend_save.store (0);
_playback_load.store (0);
_capture_load.store (0);
_post_transport_work.store (PostTransportWork (0));
_processing_prohibited.store (Disabled);
_record_status.store (Disabled);
_punch_or_loop.store (NoConstraint);
_current_usecs_per_track.store (1000);
_have_rec_enabled_track.store (0);
_have_rec_disabled_track.store (1);
_latency_recompute_pending.store (0);
_suspend_timecode_transmission.store (0);
_update_pretty_names.store (0);
_seek_counter.store (0);
_butler_seek_counter.store (0);
created_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
pthread_mutex_init (&_rt_emit_mutex, 0);
pthread_cond_init (&_rt_emit_cond, 0);
pthread_mutex_init (&_auto_connect_mutex, 0);
pthread_cond_init (&_auto_connect_cond, 0);
init_name_id_counter (1); // reset for new sessions, start at 1
VCA::set_next_vca_number (1); // reset for new sessions, start at 1
_cue_events.reserve (1024);
Temporal::reset();
pre_engine_init (fullpath); // sets _is_new
setup_lua ();
/* The engine sould be running at this point */
if (!AudioEngine::instance()->running()) {
destroy ();
throw SessionException (_("Session initialization failed because Audio/MIDI engine is not running."));
}
immediately_post_engine ();
bool need_template_resave = false;
std::string template_description;
if (_is_new) {
Stateful::loading_state_version = CURRENT_SESSION_FILE_VERSION;
if (create (mix_template, bus_profile, unnamed)) {
destroy ();
throw SessionException (_("Session initialization failed"));
}
/* if a mix template was provided, then ::create() will
* have copied it into the session and we need to load it
* so that we have the state ready for ::set_state()
* after the engine is started.
*
* Note that templates are saved without sample rate, and the
* current / previous sample rate will thus also be used after load_state()
*/
if (!mix_template.empty()) {
try {
if (load_state (_current_snapshot_name, /* from_template = */ true)) {
destroy ();
throw SessionException (_("Failed to load template/snapshot state"));
}
} catch (PBD::unknown_enumeration& e) {
destroy ();
throw SessionException (_("Failed to parse template/snapshot state"));
}
if (state_tree && Stateful::loading_state_version < CURRENT_SESSION_FILE_VERSION) {
need_template_resave = true;
XMLNode const & root (*state_tree->root());
XMLNode* desc_nd = root.child (X_("description"));
if (desc_nd) {
template_description = desc_nd->attribute_value();
}
}
store_recent_templates (mix_template);
}
/* load default session properties - if any */
config.load_state();
} else {
if (load_state (_current_snapshot_name)) {
destroy ();
throw SessionException (_("Failed to load state"));
}
ensure_subdirs (); // archived or zipped sessions may lack peaks/ analysis/ etc
}
/* apply the loaded state_tree */
int err = post_engine_init ();
if (err) {
destroy ();
switch (err) {
case -1:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Failed to create background threads.")));
break;
case -2:
case -3:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid TempoMap in session-file.")));
break;
case -4:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Invalid or corrupt session state.")));
break;
case -5:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Port registration failed.")));
break;
case -6:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Audio/MIDI Engine is not running or sample-rate mismatches.")));
break;
case -8:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Required Plugin/Processor is missing.")));
break;
case -9:
throw WrongProgram (modified_with);
break;
default:
throw SessionException (string_compose (_("Cannot initialize session/engine: %1"), _("Unexpected exception during session setup, possibly invalid audio/midi engine parameters. Please see stdout/stderr for details")));
break;
}
}
if (!mix_template.empty()) {
/* fixup monitor-sends */
if (Config->get_use_monitor_bus ()) {
/* Session::config_changed will have set use-monitor-bus to match the template.
* search for want_ms, have_ms
*/
assert (_monitor_out);
/* ..but sends do not exist, since templated track bitslots are unset */
setup_route_monitor_sends (true, true);
} else {
/* remove any monitor-sends that may be in the template */
assert (!_monitor_out);
setup_route_monitor_sends (false, true);
}
}
if (!unnamed) {
store_recent_sessions (_name, _path);
}
bool was_dirty = dirty();
PresentationInfo::Change.connect_same_thread (*this, std::bind (&Session::notify_presentation_info_change, this, _1));
Config->ParameterChanged.connect_same_thread (*this, std::bind (&Session::config_changed, this, _1, false));
config.ParameterChanged.connect_same_thread (*this, std::bind (&Session::config_changed, this, _1, true));
StartTimeChanged.connect_same_thread (*this, std::bind (&Session::start_time_changed, this, _1));
EndTimeChanged.connect_same_thread (*this, std::bind (&Session::end_time_changed, this, _1));
LatentSend::ChangedLatency.connect_same_thread (*this, std::bind (&Session::send_latency_compensation_change, this));
LatentSend::QueueUpdate.connect_same_thread (*this, std::bind (&Session::update_send_delaylines, this));
Latent::DisableSwitchChanged.connect_same_thread (*this, std::bind (&Session::queue_latency_recompute, this));
Controllable::ControlTouched.connect_same_thread (*this, std::bind (&Session::controllable_touched, this, _1));
Location::cue_change.connect_same_thread (*this, std::bind (&Session::cue_marker_change, this, _1));
IOPluginsChanged.connect_same_thread (*this, std::bind (&Session::resort_io_plugs, this));
TempoMap::MapChanged.connect_same_thread (*this, std::bind (&Session::tempo_map_changed, this));
emit_thread_start ();
auto_connect_thread_start ();
/* hook us up to the engine since we are now completely constructed */
BootMessage (_("Connect to engine"));
_engine.set_session (this);
_engine.reset_timebase ();
if (!mix_template.empty ()) {
/* ::create() unsets _is_new after creating the session.
* But for templated sessions, the sample-rate is initially unset
* (not read from template), so we need to save it (again).
*/
_is_new = true;
}
/* unsets dirty flag */
session_loaded ();
if (_is_new && unnamed) {
set_dirty ();
was_dirty = false;
}
if (was_dirty) {
DirtyChanged (); /* EMIT SIGNAL */
}
_is_new = false;
if (need_template_resave) {
save_template (mix_template, template_description, true);
}
BootMessage (_("Session loading complete"));
}
Session::~Session ()
{
#ifdef PT_TIMING
ST.dump ("ST.dump");
#endif
destroy ();
}
unsigned int
Session::next_name_id ()
{
return _name_id_counter.fetch_add (1);
}
unsigned int
Session::name_id_counter ()
{
return _name_id_counter.load ();
}
void
Session::init_name_id_counter (guint n)
{
_name_id_counter.store (n);
}
int
Session::immediately_post_engine ()
{
/* Do various initializations that should take place directly after we
* know that the engine is running, but before we either create a
* session or set state for an existing one.
*/
Port::setup_resampler (Config->get_port_resampler_quality ());
_process_graph.reset (new Graph (*this));
_rt_tasklist.reset (new RTTaskList (_process_graph));
_io_tasklist.reset (new IOTaskList (how_many_io_threads ()));
/* every time we reconnect, recompute worst case output latencies */
_engine.Running.connect_same_thread (*this, std::bind (&Session::initialize_latencies, this));
/* Restart transport FSM */
_transport_fsm->start ();
/* every time we reconnect, do stuff ... */
_engine.Running.connect_same_thread (*this, std::bind (&Session::engine_running, this));
try {
BootMessage (_("Set up LTC"));
setup_ltc ();
BootMessage (_("Set up Click"));
setup_click ();
BootMessage (_("Set up standard connections"));
setup_bundles ();
}
catch (failed_constructor& err) {
return -1;
}
/* TODO, connect in different thread. (PortRegisteredOrUnregistered may be in RT context)
* can we do that? */
_engine.PortRegisteredOrUnregistered.connect_same_thread (*this, std::bind (&Session::port_registry_changed, this));
_engine.PortPrettyNameChanged.connect_same_thread (*this, std::bind (&Session::setup_bundles, this));
// set samplerate for plugins added early
// e.g from templates or MB channelstrip
set_block_size (_engine.samples_per_cycle());
set_sample_rate (_engine.sample_rate());
return 0;
}
void
Session::destroy ()
{
/* if we got to here, leaving pending state around
* is a mistake.
*/
remove_pending_capture_state ();
Analyser::flush ();
_state_of_the_state = StateOfTheState (CannotSave | Deletion);
{
Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
ltc_tx_cleanup();
if (_ltc_output_port) {
AudioEngine::instance()->unregister_port (_ltc_output_port);
}
}
/* disconnect from any and all signals that we are connected to */
Port::PortSignalDrop (); /* EMIT SIGNAL */
drop_connections ();
/* stop auto dis/connecting */
auto_connect_thread_terminate ();
/* shutdown control surface protocols while we still have ports
* and the engine to move data to any devices.
*/
ControlProtocolManager::instance().drop_protocols ();
_engine.remove_session ();
/* deregister all ports - there will be no process or any other
* callbacks from the engine any more.
*/
Port::PortDrop (); /* EMIT SIGNAL */
/* remove I/O objects that we (the session) own */
_click_io.reset ();
_click_io_connection.disconnect ();
{
Glib::Threads::Mutex::Lock lm (controllables_lock);
for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
(*i)->DropReferences (); /* EMIT SIGNAL */
}
controllables.clear ();
}
/* clear history so that no references to objects are held any more */
_history.clear ();
/* clear state tree so that no references to objects are held any more */
delete state_tree;
state_tree = 0;
{
/* unregister all lua functions, drop held references (if any) */
Glib::Threads::Mutex::Lock tm (lua_lock, Glib::Threads::TRY_LOCK);
if (_lua_cleanup) {
(*_lua_cleanup)();
}
lua.do_command ("Session = nil");
delete _lua_run;
delete _lua_add;
delete _lua_del;
delete _lua_list;
delete _lua_save;
delete _lua_load;
delete _lua_cleanup;
lua.collect_garbage ();
}
/* reset dynamic state version back to default */
Stateful::loading_state_version = 0;
/* drop GraphNode references */
_graph_chain.reset ();
_current_route_graph = GraphEdges ();
_io_graph_chain[0].reset ();
_io_graph_chain[1].reset ();
_io_tasklist.reset ();
_butler->drop_references ();
delete _butler;
_butler = 0;
delete _all_route_group;
DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
delete *i;
}
if (click_data != default_click) {
delete [] click_data;
}
if (click_emphasis_data != default_click_emphasis) {
delete [] click_emphasis_data;
}
clear_clicks ();
/* need to remove auditioner before monitoring section
* otherwise it is re-connected.
* Note: If a session was never successfully loaded, there
* may not yet be an auditioner.
*/
if (auditioner) {
auditioner->drop_references ();
}
auditioner.reset ();
/* unregister IO Plugin */
{
RCUWriter<IOPlugList> writer (_io_plugins);
std::shared_ptr<IOPlugList> iop = writer.get_copy ();
for (auto const& i : *iop) {
i->DropReferences ();
}
iop->clear ();
}
/* drop references to routes held by the monitoring section
* specifically _monitor_out aux/listen references */
remove_monitor_section();
/* clear out any pending dead wood from RCU managed objects */
routes.flush ();
_bundles.flush ();
_io_plugins.flush ();
/* tell everyone who is still standing that we're about to die */
drop_references ();
/* tell everyone to drop references and delete objects as we go */
DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
RegionFactory::delete_all_regions ();
/* Do this early so that VCAs no longer hold references to routes */
DEBUG_TRACE (DEBUG::Destruction, "delete vcas\n");
delete _vca_manager;
DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
/* reset these three references to special routes before we do the usual route delete thing */
_master_out.reset ();
_monitor_out.reset ();
_surround_master.reset ();
{
RCUWriter<RouteList> writer (routes);
std::shared_ptr<RouteList> r = writer.get_copy ();
for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
(*i)->drop_references ();
DEBUG_TRACE(DEBUG::Destruction, string_compose ("post pre-ref = %2\n", (*i)->name(), (*i).use_count()));
}
r->clear ();
/* writer goes out of scope and updates master */
}
routes.flush ();
{
DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
Glib::Threads::Mutex::Lock lm (source_lock);
for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
i->second->drop_references ();
}
sources.clear ();
}
/* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
_playlists.reset ();
emit_thread_terminate ();
pthread_cond_destroy (&_rt_emit_cond);
pthread_mutex_destroy (&_rt_emit_mutex);
pthread_cond_destroy (&_auto_connect_cond);
pthread_mutex_destroy (&_auto_connect_mutex);
delete _scene_changer; _scene_changer = 0;
delete midi_control_ui; midi_control_ui = 0;
delete _mmc; _mmc = 0;
delete _midi_ports; _midi_ports = 0;
delete _locations; _locations = 0;
delete midi_clock;
/* clear event queue, the session is gone, nobody is interested in
* those anymore, but they do leak memory if not removed
*/
while (!immediate_events.empty ()) {
Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
SessionEvent *ev = immediate_events.front ();
DEBUG_TRACE (DEBUG::SessionEvents, string_compose ("Drop event: %1\n", enum_2_string (ev->type)));
immediate_events.pop_front ();
bool remove = true;
bool del = true;
switch (ev->type) {
case SessionEvent::AutoLoop:
case SessionEvent::Skip:
case SessionEvent::PunchIn:
case SessionEvent::PunchOut:
case SessionEvent::RangeStop:
case SessionEvent::RangeLocate:
case SessionEvent::RealTimeOperation:
process_rtop (ev);
del = false;
break;
default:
break;
}
if (remove) {
del = del && !_remove_event (ev);
}
if (del) {
delete ev;
}
}
{
/* unregister all dropped ports, process pending port deletion. */
// this may call ARDOUR::Port::drop ... jack_port_unregister ()
// jack1 cannot cope with removing ports while processing
Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
AudioEngine::instance()->clear_pending_port_deletions ();
}
DEBUG_TRACE (DEBUG::Destruction, "delete selection\n");
delete _selection;
_selection = 0;
_transport_fsm->stop ();
#ifdef VST3_SUPPORT
/* close VST3 Modules */
for (auto const& nfo : PluginManager::instance().vst3_plugin_info()) {
std::dynamic_pointer_cast<VST3PluginInfo> (nfo)->m.reset ();
}
#endif // VST3_SUPPORT
DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
#ifndef NDEBUG
Controllable::dump_registry ();
#endif
BOOST_SHOW_POINTERS ();
}
void
Session::port_registry_changed()
{
setup_bundles ();
_butler->delegate (std::bind (&Session::probe_ctrl_surfaces, this));
}
void
Session::probe_ctrl_surfaces()
{
if (!_engine.running() || deletion_in_progress ()) {
return;
}
ControlProtocolManager::instance ().probe_midi_control_protocols ();
}
void
Session::block_processing()
{
_processing_prohibited.store (1);
/* processing_blocked() is only checked at the beginning
* of the next cycle. So wait until any ongoing
* process-callback returns.
*/
Glib::Threads::Mutex::Lock lm (_engine.process_lock());
/* latency callback may be in process, wait until it completed */
Glib::Threads::Mutex::Lock lx (_engine.latency_lock());
}
void
Session::setup_ltc ()
{
_ltc_output_port = AudioEngine::instance()->register_output_port (DataType::AUDIO, X_("LTC-Out"), false, TransportGenerator);
{
Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
/* TODO use auto-connect thread */
reconnect_ltc_output ();
}
}
void
Session::setup_click ()
{
_clicking = false;
std::shared_ptr<AutomationList> gl (new AutomationList (Evoral::Parameter (GainAutomation), Temporal::TimeDomainProvider (Temporal::AudioTime)));
std::shared_ptr<GainControl> gain_control = std::shared_ptr<GainControl> (new GainControl (*this, Evoral::Parameter(GainAutomation), gl));
_click_io.reset (new ClickIO (*this, X_("Click")));
_click_gain.reset (new Amp (*this, _("Fader"), gain_control, true));
_click_gain->activate ();
if (state_tree) {
setup_click_state (state_tree->root());
} else {
setup_click_state (0);
}
click_io_resync_latency (true);
LatencyUpdated.connect_same_thread (_click_io_connection, std::bind (&Session::click_io_resync_latency, this, _1));
}
void
Session::setup_click_state (const XMLNode* node)
{
const XMLNode* child = 0;
if (node && (child = find_named_node (*node, "Click")) != 0) {
/* existing state for Click */
int c = 0;
if (Stateful::loading_state_version < 3000) {
c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
} else {
const XMLNodeList& children (child->children());
XMLNodeList::const_iterator i = children.begin();
if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
++i;